blob: ae6ad0b275b62ee4e71a846d16170bac016f4fd3 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expression parsing implementation for C++.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner60f36222009-01-29 05:15:15 +000014#include "clang/Parse/ParseDiagnostic.h"
Chris Lattner29375652006-12-04 18:06:35 +000015#include "clang/Parse/Parser.h"
Douglas Gregor94a32472011-01-11 00:33:19 +000016#include "RAIIObjectsForParser.h"
Eli Friedmanc7c97142012-01-04 02:40:39 +000017#include "clang/Basic/PrettyStackTrace.h"
Richard Smith7d182a72012-03-08 23:06:02 +000018#include "clang/Lex/LiteralSupport.h"
John McCall8b0666c2010-08-20 18:27:03 +000019#include "clang/Sema/DeclSpec.h"
Douglas Gregordb0b9f12011-08-04 15:30:47 +000020#include "clang/Sema/Scope.h"
John McCall8b0666c2010-08-20 18:27:03 +000021#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor7861a802009-11-03 01:35:08 +000022#include "llvm/Support/ErrorHandling.h"
23
Chris Lattner29375652006-12-04 18:06:35 +000024using namespace clang;
25
Richard Smith55858492011-04-14 21:45:45 +000026static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
27 switch (Kind) {
28 case tok::kw_template: return 0;
29 case tok::kw_const_cast: return 1;
30 case tok::kw_dynamic_cast: return 2;
31 case tok::kw_reinterpret_cast: return 3;
32 case tok::kw_static_cast: return 4;
33 default:
David Blaikie83d382b2011-09-23 05:06:16 +000034 llvm_unreachable("Unknown type for digraph error message.");
Richard Smith55858492011-04-14 21:45:45 +000035 }
36}
37
38// Are the two tokens adjacent in the same source file?
39static bool AreTokensAdjacent(Preprocessor &PP, Token &First, Token &Second) {
40 SourceManager &SM = PP.getSourceManager();
41 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000042 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
Richard Smith55858492011-04-14 21:45:45 +000043 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
44}
45
46// Suggest fixit for "<::" after a cast.
47static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
48 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
49 // Pull '<:' and ':' off token stream.
50 if (!AtDigraph)
51 PP.Lex(DigraphToken);
52 PP.Lex(ColonToken);
53
54 SourceRange Range;
55 Range.setBegin(DigraphToken.getLocation());
56 Range.setEnd(ColonToken.getLocation());
57 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
58 << SelectDigraphErrorMessage(Kind)
59 << FixItHint::CreateReplacement(Range, "< ::");
60
61 // Update token information to reflect their change in token type.
62 ColonToken.setKind(tok::coloncolon);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000063 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
Richard Smith55858492011-04-14 21:45:45 +000064 ColonToken.setLength(2);
65 DigraphToken.setKind(tok::less);
66 DigraphToken.setLength(1);
67
68 // Push new tokens back to token stream.
69 PP.EnterToken(ColonToken);
70 if (!AtDigraph)
71 PP.EnterToken(DigraphToken);
72}
73
Richard Trieu01fc0012011-09-19 19:01:00 +000074// Check for '<::' which should be '< ::' instead of '[:' when following
75// a template name.
76void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
77 bool EnteringContext,
78 IdentifierInfo &II, CXXScopeSpec &SS) {
Richard Trieu02e25db2011-09-20 20:03:50 +000079 if (!Next.is(tok::l_square) || Next.getLength() != 2)
Richard Trieu01fc0012011-09-19 19:01:00 +000080 return;
81
82 Token SecondToken = GetLookAheadToken(2);
83 if (!SecondToken.is(tok::colon) || !AreTokensAdjacent(PP, Next, SecondToken))
84 return;
85
86 TemplateTy Template;
87 UnqualifiedId TemplateName;
88 TemplateName.setIdentifier(&II, Tok.getLocation());
89 bool MemberOfUnknownSpecialization;
90 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
91 TemplateName, ObjectType, EnteringContext,
92 Template, MemberOfUnknownSpecialization))
93 return;
94
95 FixDigraph(*this, PP, Next, SecondToken, tok::kw_template,
96 /*AtDigraph*/false);
97}
98
Mike Stump11289f42009-09-09 15:08:12 +000099/// \brief Parse global scope or nested-name-specifier if present.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000100///
101/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
Mike Stump11289f42009-09-09 15:08:12 +0000102/// may be preceded by '::'). Note that this routine will not parse ::new or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000103/// ::delete; it will just leave them in the token stream.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000104///
105/// '::'[opt] nested-name-specifier
106/// '::'
107///
108/// nested-name-specifier:
109/// type-name '::'
110/// namespace-name '::'
111/// nested-name-specifier identifier '::'
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000112/// nested-name-specifier 'template'[opt] simple-template-id '::'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000113///
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000114///
Mike Stump11289f42009-09-09 15:08:12 +0000115/// \param SS the scope specifier that will be set to the parsed
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000116/// nested-name-specifier (or empty)
117///
Mike Stump11289f42009-09-09 15:08:12 +0000118/// \param ObjectType if this nested-name-specifier is being parsed following
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000119/// the "." or "->" of a member access expression, this parameter provides the
120/// type of the object whose members are being accessed.
121///
122/// \param EnteringContext whether we will be entering into the context of
123/// the nested-name-specifier after parsing it.
124///
Douglas Gregore610ada2010-02-24 18:44:31 +0000125/// \param MayBePseudoDestructor When non-NULL, points to a flag that
126/// indicates whether this nested-name-specifier may be part of a
127/// pseudo-destructor name. In this case, the flag will be set false
128/// if we don't actually end up parsing a destructor name. Moreorover,
129/// if we do end up determining that we are parsing a destructor name,
130/// the last component of the nested-name-specifier is not parsed as
131/// part of the scope specifier.
132
Douglas Gregor90d554e2010-02-21 18:36:56 +0000133/// member access expression, e.g., the \p T:: in \p p->T::m.
134///
John McCall1f476a12010-02-26 08:45:28 +0000135/// \returns true if there was an error parsing a scope specifier
Douglas Gregore861bac2009-08-25 22:51:20 +0000136bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +0000137 ParsedType ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000138 bool EnteringContext,
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000139 bool *MayBePseudoDestructor,
140 bool IsTypename) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000141 assert(getLangOpts().CPlusPlus &&
Chris Lattnerb5134c02009-01-05 01:24:05 +0000142 "Call sites of this function should be guarded by checking for C++");
Mike Stump11289f42009-09-09 15:08:12 +0000143
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000144 if (Tok.is(tok::annot_cxxscope)) {
Douglas Gregor869ad452011-02-24 17:54:50 +0000145 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
146 Tok.getAnnotationRange(),
147 SS);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000148 ConsumeToken();
John McCall1f476a12010-02-26 08:45:28 +0000149 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000150 }
Chris Lattnerf9b2cd42009-01-04 21:14:15 +0000151
Douglas Gregor7f741122009-02-25 19:37:18 +0000152 bool HasScopeSpecifier = false;
153
Chris Lattner8a7d10d2009-01-05 03:55:46 +0000154 if (Tok.is(tok::coloncolon)) {
155 // ::new and ::delete aren't nested-name-specifiers.
156 tok::TokenKind NextKind = NextToken().getKind();
157 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
158 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000159
Chris Lattner45ddec32009-01-05 00:13:00 +0000160 // '::' - Global scope qualifier.
Douglas Gregor90c99722011-02-24 00:17:56 +0000161 if (Actions.ActOnCXXGlobalScopeSpecifier(getCurScope(), ConsumeToken(), SS))
162 return true;
163
Douglas Gregor7f741122009-02-25 19:37:18 +0000164 HasScopeSpecifier = true;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000165 }
166
Douglas Gregore610ada2010-02-24 18:44:31 +0000167 bool CheckForDestructor = false;
168 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
169 CheckForDestructor = true;
170 *MayBePseudoDestructor = false;
171 }
172
David Blaikie15a430a2011-12-04 05:04:18 +0000173 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
174 DeclSpec DS(AttrFactory);
175 SourceLocation DeclLoc = Tok.getLocation();
176 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
177 if (Tok.isNot(tok::coloncolon)) {
178 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
179 return false;
180 }
181
182 SourceLocation CCLoc = ConsumeToken();
183 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
184 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
185
186 HasScopeSpecifier = true;
187 }
188
Douglas Gregor7f741122009-02-25 19:37:18 +0000189 while (true) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000190 if (HasScopeSpecifier) {
191 // C++ [basic.lookup.classref]p5:
192 // If the qualified-id has the form
Douglas Gregor308047d2009-09-09 00:23:06 +0000193 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000194 // ::class-name-or-namespace-name::...
Douglas Gregor308047d2009-09-09 00:23:06 +0000195 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000196 // the class-name-or-namespace-name is looked up in global scope as a
197 // class-name or namespace-name.
198 //
199 // To implement this, we clear out the object type as soon as we've
200 // seen a leading '::' or part of a nested-name-specifier.
John McCallba7bf592010-08-24 05:47:05 +0000201 ObjectType = ParsedType();
Douglas Gregor2436e712009-09-17 21:32:03 +0000202
203 if (Tok.is(tok::code_completion)) {
204 // Code completion for a nested-name-specifier, where the code
205 // code completion token follows the '::'.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000206 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
Argyrios Kyrtzidis7d94c922011-04-23 01:04:12 +0000207 // Include code completion token into the range of the scope otherwise
208 // when we try to annotate the scope tokens the dangling code completion
209 // token will cause assertion in
210 // Preprocessor::AnnotatePreviousCachedTokens.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000211 SS.setEndLoc(Tok.getLocation());
212 cutOffParsing();
213 return true;
Douglas Gregor2436e712009-09-17 21:32:03 +0000214 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000215 }
Mike Stump11289f42009-09-09 15:08:12 +0000216
Douglas Gregor7f741122009-02-25 19:37:18 +0000217 // nested-name-specifier:
Chris Lattner0eed3a62009-06-26 03:47:46 +0000218 // nested-name-specifier 'template'[opt] simple-template-id '::'
219
220 // Parse the optional 'template' keyword, then make sure we have
221 // 'identifier <' after it.
222 if (Tok.is(tok::kw_template)) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000223 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedman2624be42009-08-29 04:08:08 +0000224 // nested-name-specifier, since they aren't allowed to start with
225 // 'template'.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000226 if (!HasScopeSpecifier && !ObjectType)
Eli Friedman2624be42009-08-29 04:08:08 +0000227 break;
228
Douglas Gregor120635b2009-11-11 16:39:34 +0000229 TentativeParsingAction TPA(*this);
Chris Lattner0eed3a62009-06-26 03:47:46 +0000230 SourceLocation TemplateKWLoc = ConsumeToken();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000231
232 UnqualifiedId TemplateName;
233 if (Tok.is(tok::identifier)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000234 // Consume the identifier.
Douglas Gregor120635b2009-11-11 16:39:34 +0000235 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregor71395fa2009-11-04 00:56:37 +0000236 ConsumeToken();
237 } else if (Tok.is(tok::kw_operator)) {
238 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor120635b2009-11-11 16:39:34 +0000239 TemplateName)) {
240 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000241 break;
Douglas Gregor120635b2009-11-11 16:39:34 +0000242 }
Douglas Gregor71395fa2009-11-04 00:56:37 +0000243
Alexis Hunted0530f2009-11-28 08:58:14 +0000244 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
245 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000246 Diag(TemplateName.getSourceRange().getBegin(),
247 diag::err_id_after_template_in_nested_name_spec)
248 << TemplateName.getSourceRange();
Douglas Gregor120635b2009-11-11 16:39:34 +0000249 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000250 break;
251 }
252 } else {
Douglas Gregor120635b2009-11-11 16:39:34 +0000253 TPA.Revert();
Chris Lattner0eed3a62009-06-26 03:47:46 +0000254 break;
255 }
Mike Stump11289f42009-09-09 15:08:12 +0000256
Douglas Gregor120635b2009-11-11 16:39:34 +0000257 // If the next token is not '<', we have a qualified-id that refers
258 // to a template name, such as T::template apply, but is not a
259 // template-id.
260 if (Tok.isNot(tok::less)) {
261 TPA.Revert();
262 break;
263 }
264
265 // Commit to parsing the template-id.
266 TPA.Commit();
Douglas Gregorbb119652010-06-16 23:00:59 +0000267 TemplateTy Template;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000268 if (TemplateNameKind TNK
269 = Actions.ActOnDependentTemplateName(getCurScope(),
270 SS, TemplateKWLoc, TemplateName,
271 ObjectType, EnteringContext,
272 Template)) {
273 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
274 TemplateName, false))
Douglas Gregorbb119652010-06-16 23:00:59 +0000275 return true;
276 } else
John McCall1f476a12010-02-26 08:45:28 +0000277 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000278
Chris Lattner0eed3a62009-06-26 03:47:46 +0000279 continue;
280 }
Mike Stump11289f42009-09-09 15:08:12 +0000281
Douglas Gregor7f741122009-02-25 19:37:18 +0000282 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump11289f42009-09-09 15:08:12 +0000283 // We have
Douglas Gregor7f741122009-02-25 19:37:18 +0000284 //
285 // simple-template-id '::'
286 //
287 // So we need to check whether the simple-template-id is of the
Douglas Gregorb67535d2009-03-31 00:43:58 +0000288 // right kind (it should name a type or be dependent), and then
289 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +0000290 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregore610ada2010-02-24 18:44:31 +0000291 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
292 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000293 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000294 }
295
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000296 // Consume the template-id token.
297 ConsumeToken();
298
299 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
300 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000301
David Blaikie8c045bc2011-11-07 03:30:03 +0000302 HasScopeSpecifier = true;
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000303
304 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
305 TemplateId->getTemplateArgs(),
306 TemplateId->NumArgs);
307
308 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000309 SS,
310 TemplateId->TemplateKWLoc,
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000311 TemplateId->Template,
312 TemplateId->TemplateNameLoc,
313 TemplateId->LAngleLoc,
314 TemplateArgsPtr,
315 TemplateId->RAngleLoc,
316 CCLoc,
317 EnteringContext)) {
318 SourceLocation StartLoc
319 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
320 : TemplateId->TemplateNameLoc;
321 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner704edfb2009-06-26 03:45:46 +0000322 }
Argyrios Kyrtzidis13935672011-05-03 18:45:38 +0000323
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000324 continue;
Douglas Gregor7f741122009-02-25 19:37:18 +0000325 }
326
Chris Lattnere2355f72009-06-26 03:52:38 +0000327
328 // The rest of the nested-name-specifier possibilities start with
329 // tok::identifier.
330 if (Tok.isNot(tok::identifier))
331 break;
332
333 IdentifierInfo &II = *Tok.getIdentifierInfo();
334
335 // nested-name-specifier:
336 // type-name '::'
337 // namespace-name '::'
338 // nested-name-specifier identifier '::'
339 Token Next = NextToken();
Chris Lattner1c428032009-12-07 01:36:53 +0000340
341 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
342 // and emit a fixit hint for it.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000343 if (Next.is(tok::colon) && !ColonIsSacred) {
Douglas Gregor90c99722011-02-24 00:17:56 +0000344 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
345 Tok.getLocation(),
346 Next.getLocation(), ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000347 EnteringContext) &&
348 // If the token after the colon isn't an identifier, it's still an
349 // error, but they probably meant something else strange so don't
350 // recover like this.
351 PP.LookAhead(1).is(tok::identifier)) {
352 Diag(Next, diag::err_unexected_colon_in_nested_name_spec)
Douglas Gregora771f462010-03-31 17:46:05 +0000353 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregor90d554e2010-02-21 18:36:56 +0000354
355 // Recover as if the user wrote '::'.
356 Next.setKind(tok::coloncolon);
357 }
Chris Lattner1c428032009-12-07 01:36:53 +0000358 }
359
Chris Lattnere2355f72009-06-26 03:52:38 +0000360 if (Next.is(tok::coloncolon)) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +0000361 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Douglas Gregor0be31a22010-07-02 17:43:08 +0000362 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(),
Douglas Gregor0d5b0a12010-02-24 21:29:12 +0000363 II, ObjectType)) {
Douglas Gregore610ada2010-02-24 18:44:31 +0000364 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000365 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000366 }
367
Chris Lattnere2355f72009-06-26 03:52:38 +0000368 // We have an identifier followed by a '::'. Lookup this name
369 // as the name in a nested-name-specifier.
370 SourceLocation IdLoc = ConsumeToken();
Chris Lattner1c428032009-12-07 01:36:53 +0000371 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
372 "NextToken() not working properly!");
Chris Lattnere2355f72009-06-26 03:52:38 +0000373 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000374
Douglas Gregor90c99722011-02-24 00:17:56 +0000375 HasScopeSpecifier = true;
376 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
377 ObjectType, EnteringContext, SS))
378 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
379
Chris Lattnere2355f72009-06-26 03:52:38 +0000380 continue;
381 }
Mike Stump11289f42009-09-09 15:08:12 +0000382
Richard Trieu01fc0012011-09-19 19:01:00 +0000383 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smith55858492011-04-14 21:45:45 +0000384
Chris Lattnere2355f72009-06-26 03:52:38 +0000385 // nested-name-specifier:
386 // type-name '<'
387 if (Next.is(tok::less)) {
388 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000389 UnqualifiedId TemplateName;
390 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor786123d2010-05-21 23:18:07 +0000391 bool MemberOfUnknownSpecialization;
Douglas Gregor0be31a22010-07-02 17:43:08 +0000392 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000393 /*hasTemplateKeyword=*/false,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000394 TemplateName,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000395 ObjectType,
Douglas Gregore861bac2009-08-25 22:51:20 +0000396 EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000397 Template,
398 MemberOfUnknownSpecialization)) {
David Blaikie8c045bc2011-11-07 03:30:03 +0000399 // We have found a template name, so annotate this token
Chris Lattnere2355f72009-06-26 03:52:38 +0000400 // with a template-id annotation. We do not permit the
401 // template-id to be translated into a type annotation,
402 // because some clients (e.g., the parsing of class template
403 // specializations) still want to see the original template-id
404 // token.
Douglas Gregor71395fa2009-11-04 00:56:37 +0000405 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000406 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
407 TemplateName, false))
John McCall1f476a12010-02-26 08:45:28 +0000408 return true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000409 continue;
Douglas Gregor20c38a72010-05-21 23:43:39 +0000410 }
411
412 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000413 (IsTypename || IsTemplateArgumentList(1))) {
Douglas Gregor20c38a72010-05-21 23:43:39 +0000414 // We have something like t::getAs<T>, where getAs is a
415 // member of an unknown specialization. However, this will only
416 // parse correctly as a template, so suggest the keyword 'template'
417 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000418 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000419 if (getLangOpts().MicrosoftExt)
Francois Pichet93921652011-04-22 08:25:24 +0000420 DiagID = diag::warn_missing_dependent_template_keyword;
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000421
422 Diag(Tok.getLocation(), DiagID)
Douglas Gregor20c38a72010-05-21 23:43:39 +0000423 << II.getName()
424 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
425
Douglas Gregorbb119652010-06-16 23:00:59 +0000426 if (TemplateNameKind TNK
Douglas Gregor0be31a22010-07-02 17:43:08 +0000427 = Actions.ActOnDependentTemplateName(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000428 SS, SourceLocation(),
Douglas Gregorbb119652010-06-16 23:00:59 +0000429 TemplateName, ObjectType,
430 EnteringContext, Template)) {
431 // Consume the identifier.
432 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000433 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
434 TemplateName, false))
435 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000436 }
437 else
Douglas Gregor20c38a72010-05-21 23:43:39 +0000438 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000439
Douglas Gregor20c38a72010-05-21 23:43:39 +0000440 continue;
Chris Lattnere2355f72009-06-26 03:52:38 +0000441 }
442 }
443
Douglas Gregor7f741122009-02-25 19:37:18 +0000444 // We don't have any tokens that form the beginning of a
445 // nested-name-specifier, so we're done.
446 break;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000447 }
Mike Stump11289f42009-09-09 15:08:12 +0000448
Douglas Gregore610ada2010-02-24 18:44:31 +0000449 // Even if we didn't see any pieces of a nested-name-specifier, we
450 // still check whether there is a tilde in this position, which
451 // indicates a potential pseudo-destructor.
452 if (CheckForDestructor && Tok.is(tok::tilde))
453 *MayBePseudoDestructor = true;
454
John McCall1f476a12010-02-26 08:45:28 +0000455 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000456}
457
458/// ParseCXXIdExpression - Handle id-expression.
459///
460/// id-expression:
461/// unqualified-id
462/// qualified-id
463///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000464/// qualified-id:
465/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
466/// '::' identifier
467/// '::' operator-function-id
Douglas Gregora727cb92009-06-30 22:34:41 +0000468/// '::' template-id
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000469///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000470/// NOTE: The standard specifies that, for qualified-id, the parser does not
471/// expect:
472///
473/// '::' conversion-function-id
474/// '::' '~' class-name
475///
476/// This may cause a slight inconsistency on diagnostics:
477///
478/// class C {};
479/// namespace A {}
480/// void f() {
481/// :: A :: ~ C(); // Some Sema error about using destructor with a
482/// // namespace.
483/// :: ~ C(); // Some Parser error like 'unexpected ~'.
484/// }
485///
486/// We simplify the parser a bit and make it work like:
487///
488/// qualified-id:
489/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
490/// '::' unqualified-id
491///
492/// That way Sema can handle and report similar errors for namespaces and the
493/// global scope.
494///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000495/// The isAddressOfOperand parameter indicates that this id-expression is a
496/// direct operand of the address-of operator. This is, besides member contexts,
497/// the only place where a qualified-id naming a non-static class member may
498/// appear.
499///
John McCalldadc5752010-08-24 06:29:42 +0000500ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000501 // qualified-id:
502 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
503 // '::' unqualified-id
504 //
505 CXXScopeSpec SS;
Douglas Gregordf593fb2011-11-07 17:33:42 +0000506 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000507
508 SourceLocation TemplateKWLoc;
Douglas Gregora121b752009-11-03 16:56:39 +0000509 UnqualifiedId Name;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000510 if (ParseUnqualifiedId(SS,
511 /*EnteringContext=*/false,
512 /*AllowDestructorName=*/false,
513 /*AllowConstructorName=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000514 /*ObjectType=*/ ParsedType(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000515 TemplateKWLoc,
Douglas Gregora121b752009-11-03 16:56:39 +0000516 Name))
517 return ExprError();
John McCalla9ee3252009-11-22 02:49:43 +0000518
519 // This is only the direct operand of an & operator if it is not
520 // followed by a postfix-expression suffix.
John McCall8d08b9b2010-08-27 09:08:28 +0000521 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
522 isAddressOfOperand = false;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000523
524 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
525 Tok.is(tok::l_paren), isAddressOfOperand);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000526}
527
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000528/// ParseLambdaExpression - Parse a C++0x lambda expression.
529///
530/// lambda-expression:
531/// lambda-introducer lambda-declarator[opt] compound-statement
532///
533/// lambda-introducer:
534/// '[' lambda-capture[opt] ']'
535///
536/// lambda-capture:
537/// capture-default
538/// capture-list
539/// capture-default ',' capture-list
540///
541/// capture-default:
542/// '&'
543/// '='
544///
545/// capture-list:
546/// capture
547/// capture-list ',' capture
548///
549/// capture:
550/// identifier
551/// '&' identifier
552/// 'this'
553///
554/// lambda-declarator:
555/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
556/// 'mutable'[opt] exception-specification[opt]
557/// trailing-return-type[opt]
558///
559ExprResult Parser::ParseLambdaExpression() {
560 // Parse lambda-introducer.
561 LambdaIntroducer Intro;
562
563 llvm::Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro));
564 if (DiagID) {
565 Diag(Tok, DiagID.getValue());
566 SkipUntil(tok::r_square);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000567 SkipUntil(tok::l_brace);
568 SkipUntil(tok::r_brace);
569 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000570 }
571
572 return ParseLambdaExpressionAfterIntroducer(Intro);
573}
574
575/// TryParseLambdaExpression - Use lookahead and potentially tentative
576/// parsing to determine if we are looking at a C++0x lambda expression, and parse
577/// it if we are.
578///
579/// If we are not looking at a lambda expression, returns ExprError().
580ExprResult Parser::TryParseLambdaExpression() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000581 assert(getLangOpts().CPlusPlus0x
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000582 && Tok.is(tok::l_square)
583 && "Not at the start of a possible lambda expression.");
584
585 const Token Next = NextToken(), After = GetLookAheadToken(2);
586
587 // If lookahead indicates this is a lambda...
588 if (Next.is(tok::r_square) || // []
589 Next.is(tok::equal) || // [=
590 (Next.is(tok::amp) && // [&] or [&,
591 (After.is(tok::r_square) ||
592 After.is(tok::comma))) ||
593 (Next.is(tok::identifier) && // [identifier]
594 After.is(tok::r_square))) {
595 return ParseLambdaExpression();
596 }
597
Eli Friedmanc7c97142012-01-04 02:40:39 +0000598 // If lookahead indicates an ObjC message send...
599 // [identifier identifier
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000600 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000601 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000602 }
603
Eli Friedmanc7c97142012-01-04 02:40:39 +0000604 // Here, we're stuck: lambda introducers and Objective-C message sends are
605 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
606 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
607 // writing two routines to parse a lambda introducer, just try to parse
608 // a lambda introducer first, and fall back if that fails.
609 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000610 LambdaIntroducer Intro;
611 if (TryParseLambdaIntroducer(Intro))
Eli Friedmanc7c97142012-01-04 02:40:39 +0000612 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000613 return ParseLambdaExpressionAfterIntroducer(Intro);
614}
615
616/// ParseLambdaExpression - Parse a lambda introducer.
617///
618/// Returns a DiagnosticID if it hit something unexpected.
Douglas Gregord8c61782012-02-15 15:34:24 +0000619llvm::Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro){
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000620 typedef llvm::Optional<unsigned> DiagResult;
621
622 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000623 BalancedDelimiterTracker T(*this, tok::l_square);
624 T.consumeOpen();
625
626 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000627
628 bool first = true;
629
630 // Parse capture-default.
631 if (Tok.is(tok::amp) &&
632 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
633 Intro.Default = LCD_ByRef;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000634 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000635 first = false;
636 } else if (Tok.is(tok::equal)) {
637 Intro.Default = LCD_ByCopy;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000638 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000639 first = false;
640 }
641
642 while (Tok.isNot(tok::r_square)) {
643 if (!first) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000644 if (Tok.isNot(tok::comma)) {
645 if (Tok.is(tok::code_completion)) {
646 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
647 /*AfterAmpersand=*/false);
648 ConsumeCodeCompletionToken();
649 break;
650 }
651
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000652 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregord8c61782012-02-15 15:34:24 +0000653 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000654 ConsumeToken();
655 }
656
Douglas Gregord8c61782012-02-15 15:34:24 +0000657 if (Tok.is(tok::code_completion)) {
658 // If we're in Objective-C++ and we have a bare '[', then this is more
659 // likely to be a message receiver.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000660 if (getLangOpts().ObjC1 && first)
Douglas Gregord8c61782012-02-15 15:34:24 +0000661 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
662 else
663 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
664 /*AfterAmpersand=*/false);
665 ConsumeCodeCompletionToken();
666 break;
667 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000668
Douglas Gregord8c61782012-02-15 15:34:24 +0000669 first = false;
670
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000671 // Parse capture.
672 LambdaCaptureKind Kind = LCK_ByCopy;
673 SourceLocation Loc;
674 IdentifierInfo* Id = 0;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000675 SourceLocation EllipsisLoc;
676
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000677 if (Tok.is(tok::kw_this)) {
678 Kind = LCK_This;
679 Loc = ConsumeToken();
680 } else {
681 if (Tok.is(tok::amp)) {
682 Kind = LCK_ByRef;
683 ConsumeToken();
Douglas Gregord8c61782012-02-15 15:34:24 +0000684
685 if (Tok.is(tok::code_completion)) {
686 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
687 /*AfterAmpersand=*/true);
688 ConsumeCodeCompletionToken();
689 break;
690 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000691 }
692
693 if (Tok.is(tok::identifier)) {
694 Id = Tok.getIdentifierInfo();
695 Loc = ConsumeToken();
Douglas Gregor3e308b12012-02-14 19:27:52 +0000696
697 if (Tok.is(tok::ellipsis))
698 EllipsisLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000699 } else if (Tok.is(tok::kw_this)) {
700 // FIXME: If we want to suggest a fixit here, will need to return more
701 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
702 // Clear()ed to prevent emission in case of tentative parsing?
703 return DiagResult(diag::err_this_captured_by_reference);
704 } else {
705 return DiagResult(diag::err_expected_capture);
706 }
707 }
708
Douglas Gregor3e308b12012-02-14 19:27:52 +0000709 Intro.addCapture(Kind, Loc, Id, EllipsisLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000710 }
711
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000712 T.consumeClose();
713 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000714
715 return DiagResult();
716}
717
Douglas Gregord8c61782012-02-15 15:34:24 +0000718/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000719///
720/// Returns true if it hit something unexpected.
721bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
722 TentativeParsingAction PA(*this);
723
724 llvm::Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro));
725
726 if (DiagID) {
727 PA.Revert();
728 return true;
729 }
730
731 PA.Commit();
732 return false;
733}
734
735/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
736/// expression.
737ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
738 LambdaIntroducer &Intro) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000739 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
740 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
741
742 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
743 "lambda expression parsing");
744
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000745 // Parse lambda-declarator[opt].
746 DeclSpec DS(AttrFactory);
Eli Friedman36d12942012-01-04 04:41:38 +0000747 Declarator D(DS, Declarator::LambdaExprContext);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000748
749 if (Tok.is(tok::l_paren)) {
750 ParseScope PrototypeScope(this,
751 Scope::FunctionPrototypeScope |
752 Scope::DeclScope);
753
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000754 SourceLocation DeclLoc, DeclEndLoc;
755 BalancedDelimiterTracker T(*this, tok::l_paren);
756 T.consumeOpen();
757 DeclLoc = T.getOpenLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000758
759 // Parse parameter-declaration-clause.
760 ParsedAttributes Attr(AttrFactory);
761 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
762 SourceLocation EllipsisLoc;
763
764 if (Tok.isNot(tok::r_paren))
765 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
766
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000767 T.consumeClose();
768 DeclEndLoc = T.getCloseLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000769
770 // Parse 'mutable'[opt].
771 SourceLocation MutableLoc;
772 if (Tok.is(tok::kw_mutable)) {
773 MutableLoc = ConsumeToken();
774 DeclEndLoc = MutableLoc;
775 }
776
777 // Parse exception-specification[opt].
778 ExceptionSpecificationType ESpecType = EST_None;
779 SourceRange ESpecRange;
780 llvm::SmallVector<ParsedType, 2> DynamicExceptions;
781 llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges;
782 ExprResult NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +0000783 CachedTokens *ExceptionSpecTokens;
784 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
785 ESpecRange,
786 DynamicExceptions,
787 DynamicExceptionRanges,
788 NoexceptExpr,
789 ExceptionSpecTokens);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000790
791 if (ESpecType != EST_None)
792 DeclEndLoc = ESpecRange.getEnd();
793
794 // Parse attribute-specifier[opt].
795 MaybeParseCXX0XAttributes(Attr, &DeclEndLoc);
796
797 // Parse trailing-return-type[opt].
798 ParsedType TrailingReturnType;
799 if (Tok.is(tok::arrow)) {
800 SourceRange Range;
801 TrailingReturnType = ParseTrailingReturnType(Range).get();
802 if (Range.getEnd().isValid())
803 DeclEndLoc = Range.getEnd();
804 }
805
806 PrototypeScope.Exit();
807
808 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
809 /*isVariadic=*/EllipsisLoc.isValid(),
810 EllipsisLoc,
811 ParamInfo.data(), ParamInfo.size(),
812 DS.getTypeQualifiers(),
813 /*RefQualifierIsLValueRef=*/true,
814 /*RefQualifierLoc=*/SourceLocation(),
Douglas Gregore248eea2011-10-19 06:04:55 +0000815 /*ConstQualifierLoc=*/SourceLocation(),
816 /*VolatileQualifierLoc=*/SourceLocation(),
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000817 MutableLoc,
818 ESpecType, ESpecRange.getBegin(),
819 DynamicExceptions.data(),
820 DynamicExceptionRanges.data(),
821 DynamicExceptions.size(),
822 NoexceptExpr.isUsable() ?
823 NoexceptExpr.get() : 0,
Douglas Gregor433e0532012-04-16 18:27:27 +0000824 0,
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000825 DeclLoc, DeclEndLoc, D,
826 TrailingReturnType),
827 Attr, DeclEndLoc);
Douglas Gregor6746c5d2012-02-16 21:53:36 +0000828 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow)) {
829 // It's common to forget that one needs '()' before 'mutable' or the
830 // result type. Deal with this.
831 Diag(Tok, diag::err_lambda_missing_parens)
832 << Tok.is(tok::arrow)
833 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
834 SourceLocation DeclLoc = Tok.getLocation();
835 SourceLocation DeclEndLoc = DeclLoc;
836
837 // Parse 'mutable', if it's there.
838 SourceLocation MutableLoc;
839 if (Tok.is(tok::kw_mutable)) {
840 MutableLoc = ConsumeToken();
841 DeclEndLoc = MutableLoc;
842 }
843
844 // Parse the return type, if there is one.
845 ParsedType TrailingReturnType;
846 if (Tok.is(tok::arrow)) {
847 SourceRange Range;
848 TrailingReturnType = ParseTrailingReturnType(Range).get();
849 if (Range.getEnd().isValid())
850 DeclEndLoc = Range.getEnd();
851 }
852
853 ParsedAttributes Attr(AttrFactory);
854 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
855 /*isVariadic=*/false,
856 /*EllipsisLoc=*/SourceLocation(),
857 /*Params=*/0, /*NumParams=*/0,
858 /*TypeQuals=*/0,
859 /*RefQualifierIsLValueRef=*/true,
860 /*RefQualifierLoc=*/SourceLocation(),
861 /*ConstQualifierLoc=*/SourceLocation(),
862 /*VolatileQualifierLoc=*/SourceLocation(),
863 MutableLoc,
864 EST_None,
865 /*ESpecLoc=*/SourceLocation(),
866 /*Exceptions=*/0,
867 /*ExceptionRanges=*/0,
868 /*NumExceptions=*/0,
869 /*NoexceptExpr=*/0,
Douglas Gregor433e0532012-04-16 18:27:27 +0000870 /*ExceptionSpecTokens=*/0,
Douglas Gregor6746c5d2012-02-16 21:53:36 +0000871 DeclLoc, DeclEndLoc, D,
872 TrailingReturnType),
873 Attr, DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000874 }
Douglas Gregor6746c5d2012-02-16 21:53:36 +0000875
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000876
Eli Friedman4817cf72012-01-06 03:05:34 +0000877 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
878 // it.
Douglas Gregorb8389972012-02-21 22:51:27 +0000879 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
Douglas Gregorb8389972012-02-21 22:51:27 +0000880 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman4817cf72012-01-06 03:05:34 +0000881
Eli Friedman71c80552012-01-05 03:35:19 +0000882 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
883
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000884 // Parse compound-statement.
Eli Friedmanc7c97142012-01-04 02:40:39 +0000885 if (!Tok.is(tok::l_brace)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000886 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000887 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
888 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000889 }
890
Eli Friedmanc7c97142012-01-04 02:40:39 +0000891 StmtResult Stmt(ParseCompoundStatementBody());
892 BodyScope.Exit();
893
Eli Friedman898caf82012-01-04 02:46:53 +0000894 if (!Stmt.isInvalid())
Douglas Gregor63798542012-02-20 19:44:39 +0000895 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.take(), getCurScope());
Eli Friedmanc7c97142012-01-04 02:40:39 +0000896
Eli Friedman898caf82012-01-04 02:46:53 +0000897 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
898 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000899}
900
Chris Lattner29375652006-12-04 18:06:35 +0000901/// ParseCXXCasts - This handles the various ways to cast expressions to another
902/// type.
903///
904/// postfix-expression: [C++ 5.2p1]
905/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
906/// 'static_cast' '<' type-name '>' '(' expression ')'
907/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
908/// 'const_cast' '<' type-name '>' '(' expression ')'
909///
John McCalldadc5752010-08-24 06:29:42 +0000910ExprResult Parser::ParseCXXCasts() {
Chris Lattner29375652006-12-04 18:06:35 +0000911 tok::TokenKind Kind = Tok.getKind();
912 const char *CastName = 0; // For error messages
913
914 switch (Kind) {
David Blaikieaa347f92011-09-23 20:26:49 +0000915 default: llvm_unreachable("Unknown C++ cast!");
Chris Lattner29375652006-12-04 18:06:35 +0000916 case tok::kw_const_cast: CastName = "const_cast"; break;
917 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
918 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
919 case tok::kw_static_cast: CastName = "static_cast"; break;
920 }
921
922 SourceLocation OpLoc = ConsumeToken();
923 SourceLocation LAngleBracketLoc = Tok.getLocation();
924
Richard Smith55858492011-04-14 21:45:45 +0000925 // Check for "<::" which is parsed as "[:". If found, fix token stream,
926 // diagnose error, suggest fix, and recover parsing.
927 Token Next = NextToken();
928 if (Tok.is(tok::l_square) && Tok.getLength() == 2 && Next.is(tok::colon) &&
929 AreTokensAdjacent(PP, Tok, Next))
930 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
931
Chris Lattner29375652006-12-04 18:06:35 +0000932 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redld65cea82008-12-11 22:51:44 +0000933 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +0000934
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000935 // Parse the common declaration-specifiers piece.
936 DeclSpec DS(AttrFactory);
937 ParseSpecifierQualifierList(DS);
938
939 // Parse the abstract-declarator, if present.
940 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
941 ParseDeclarator(DeclaratorInfo);
942
Chris Lattner29375652006-12-04 18:06:35 +0000943 SourceLocation RAngleBracketLoc = Tok.getLocation();
944
Chris Lattner6d29c102008-11-18 07:48:38 +0000945 if (ExpectAndConsume(tok::greater, diag::err_expected_greater))
Sebastian Redld65cea82008-12-11 22:51:44 +0000946 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<");
Chris Lattner29375652006-12-04 18:06:35 +0000947
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000948 SourceLocation LParenLoc, RParenLoc;
949 BalancedDelimiterTracker T(*this, tok::l_paren);
Chris Lattner29375652006-12-04 18:06:35 +0000950
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000951 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +0000952 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +0000953
John McCalldadc5752010-08-24 06:29:42 +0000954 ExprResult Result = ParseExpression();
Mike Stump11289f42009-09-09 15:08:12 +0000955
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +0000956 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000957 T.consumeClose();
Chris Lattner29375652006-12-04 18:06:35 +0000958
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000959 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregore200adc2008-10-27 19:41:14 +0000960 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000961 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor220cac52009-02-18 17:45:20 +0000962 RAngleBracketLoc,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000963 T.getOpenLocation(), Result.take(),
964 T.getCloseLocation());
Chris Lattner29375652006-12-04 18:06:35 +0000965
Sebastian Redld65cea82008-12-11 22:51:44 +0000966 return move(Result);
Chris Lattner29375652006-12-04 18:06:35 +0000967}
Bill Wendling4073ed52007-02-13 01:51:42 +0000968
Sebastian Redlc4704762008-11-11 11:37:55 +0000969/// ParseCXXTypeid - This handles the C++ typeid expression.
970///
971/// postfix-expression: [C++ 5.2p1]
972/// 'typeid' '(' expression ')'
973/// 'typeid' '(' type-id ')'
974///
John McCalldadc5752010-08-24 06:29:42 +0000975ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc4704762008-11-11 11:37:55 +0000976 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
977
978 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000979 SourceLocation LParenLoc, RParenLoc;
980 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc4704762008-11-11 11:37:55 +0000981
982 // typeid expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000983 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redld65cea82008-12-11 22:51:44 +0000984 return ExprError();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000985 LParenLoc = T.getOpenLocation();
Sebastian Redlc4704762008-11-11 11:37:55 +0000986
John McCalldadc5752010-08-24 06:29:42 +0000987 ExprResult Result;
Sebastian Redlc4704762008-11-11 11:37:55 +0000988
989 if (isTypeIdInParens()) {
Douglas Gregor220cac52009-02-18 17:45:20 +0000990 TypeResult Ty = ParseTypeName();
Sebastian Redlc4704762008-11-11 11:37:55 +0000991
992 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000993 T.consumeClose();
994 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000995 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +0000996 return ExprError();
Sebastian Redlc4704762008-11-11 11:37:55 +0000997
998 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallba7bf592010-08-24 05:47:05 +0000999 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001000 } else {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001001 // C++0x [expr.typeid]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001002 // When typeid is applied to an expression other than an lvalue of a
1003 // polymorphic class type [...] The expression is an unevaluated
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001004 // operand (Clause 5).
1005 //
Mike Stump11289f42009-09-09 15:08:12 +00001006 // Note that we can't tell whether the expression is an lvalue of a
Eli Friedman456f0182012-01-20 01:26:23 +00001007 // polymorphic class type until after we've parsed the expression; we
1008 // speculatively assume the subexpression is unevaluated, and fix it up
1009 // later.
1010 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
Sebastian Redlc4704762008-11-11 11:37:55 +00001011 Result = ParseExpression();
1012
1013 // Match the ')'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001014 if (Result.isInvalid())
Sebastian Redlc4704762008-11-11 11:37:55 +00001015 SkipUntil(tok::r_paren);
1016 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001017 T.consumeClose();
1018 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001019 if (RParenLoc.isInvalid())
1020 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00001021
Sebastian Redlc4704762008-11-11 11:37:55 +00001022 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001023 Result.release(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001024 }
1025 }
1026
Sebastian Redld65cea82008-12-11 22:51:44 +00001027 return move(Result);
Sebastian Redlc4704762008-11-11 11:37:55 +00001028}
1029
Francois Pichet9f4f2072010-09-08 12:20:18 +00001030/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1031///
1032/// '__uuidof' '(' expression ')'
1033/// '__uuidof' '(' type-id ')'
1034///
1035ExprResult Parser::ParseCXXUuidof() {
1036 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1037
1038 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001039 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001040
1041 // __uuidof expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001042 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet9f4f2072010-09-08 12:20:18 +00001043 return ExprError();
1044
1045 ExprResult Result;
1046
1047 if (isTypeIdInParens()) {
1048 TypeResult Ty = ParseTypeName();
1049
1050 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001051 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001052
1053 if (Ty.isInvalid())
1054 return ExprError();
1055
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001056 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1057 Ty.get().getAsOpaquePtr(),
1058 T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001059 } else {
1060 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1061 Result = ParseExpression();
1062
1063 // Match the ')'.
1064 if (Result.isInvalid())
1065 SkipUntil(tok::r_paren);
1066 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001067 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001068
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001069 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1070 /*isType=*/false,
1071 Result.release(), T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001072 }
1073 }
1074
1075 return move(Result);
1076}
1077
Douglas Gregore610ada2010-02-24 18:44:31 +00001078/// \brief Parse a C++ pseudo-destructor expression after the base,
1079/// . or -> operator, and nested-name-specifier have already been
1080/// parsed.
1081///
1082/// postfix-expression: [C++ 5.2]
1083/// postfix-expression . pseudo-destructor-name
1084/// postfix-expression -> pseudo-destructor-name
1085///
1086/// pseudo-destructor-name:
1087/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1088/// ::[opt] nested-name-specifier template simple-template-id ::
1089/// ~type-name
1090/// ::[opt] nested-name-specifier[opt] ~type-name
1091///
John McCalldadc5752010-08-24 06:29:42 +00001092ExprResult
Douglas Gregore610ada2010-02-24 18:44:31 +00001093Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1094 tok::TokenKind OpKind,
1095 CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +00001096 ParsedType ObjectType) {
Douglas Gregore610ada2010-02-24 18:44:31 +00001097 // We're parsing either a pseudo-destructor-name or a dependent
1098 // member access that has the same form as a
1099 // pseudo-destructor-name. We parse both in the same way and let
1100 // the action model sort them out.
1101 //
1102 // Note that the ::[opt] nested-name-specifier[opt] has already
1103 // been parsed, and if there was a simple-template-id, it has
1104 // been coalesced into a template-id annotation token.
1105 UnqualifiedId FirstTypeName;
1106 SourceLocation CCLoc;
1107 if (Tok.is(tok::identifier)) {
1108 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1109 ConsumeToken();
1110 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1111 CCLoc = ConsumeToken();
1112 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001113 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1114 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregore610ada2010-02-24 18:44:31 +00001115 FirstTypeName.setTemplateId(
1116 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1117 ConsumeToken();
1118 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1119 CCLoc = ConsumeToken();
1120 } else {
1121 FirstTypeName.setIdentifier(0, SourceLocation());
1122 }
1123
1124 // Parse the tilde.
1125 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1126 SourceLocation TildeLoc = ConsumeToken();
David Blaikie1d578782011-12-16 16:03:09 +00001127
1128 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1129 DeclSpec DS(AttrFactory);
Benjamin Kramer198e0832011-12-18 12:18:02 +00001130 ParseDecltypeSpecifier(DS);
David Blaikie1d578782011-12-16 16:03:09 +00001131 if (DS.getTypeSpecType() == TST_error)
1132 return ExprError();
1133 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1134 OpKind, TildeLoc, DS,
1135 Tok.is(tok::l_paren));
1136 }
1137
Douglas Gregore610ada2010-02-24 18:44:31 +00001138 if (!Tok.is(tok::identifier)) {
1139 Diag(Tok, diag::err_destructor_tilde_identifier);
1140 return ExprError();
1141 }
1142
1143 // Parse the second type.
1144 UnqualifiedId SecondTypeName;
1145 IdentifierInfo *Name = Tok.getIdentifierInfo();
1146 SourceLocation NameLoc = ConsumeToken();
1147 SecondTypeName.setIdentifier(Name, NameLoc);
1148
1149 // If there is a '<', the second type name is a template-id. Parse
1150 // it as such.
1151 if (Tok.is(tok::less) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +00001152 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1153 Name, NameLoc,
1154 false, ObjectType, SecondTypeName,
1155 /*AssumeTemplateName=*/true))
Douglas Gregore610ada2010-02-24 18:44:31 +00001156 return ExprError();
1157
John McCallb268a282010-08-23 23:25:46 +00001158 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1159 OpLoc, OpKind,
Douglas Gregore610ada2010-02-24 18:44:31 +00001160 SS, FirstTypeName, CCLoc,
1161 TildeLoc, SecondTypeName,
1162 Tok.is(tok::l_paren));
1163}
1164
Bill Wendling4073ed52007-02-13 01:51:42 +00001165/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1166///
1167/// boolean-literal: [C++ 2.13.5]
1168/// 'true'
1169/// 'false'
John McCalldadc5752010-08-24 06:29:42 +00001170ExprResult Parser::ParseCXXBoolLiteral() {
Bill Wendling4073ed52007-02-13 01:51:42 +00001171 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001172 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Bill Wendling4073ed52007-02-13 01:51:42 +00001173}
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001174
1175/// ParseThrowExpression - This handles the C++ throw expression.
1176///
1177/// throw-expression: [C++ 15]
1178/// 'throw' assignment-expression[opt]
John McCalldadc5752010-08-24 06:29:42 +00001179ExprResult Parser::ParseThrowExpression() {
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001180 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001181 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redld65cea82008-12-11 22:51:44 +00001182
Chris Lattner65dd8432008-04-06 06:02:23 +00001183 // If the current token isn't the start of an assignment-expression,
1184 // then the expression is not present. This handles things like:
1185 // "C ? throw : (void)42", which is crazy but legal.
1186 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1187 case tok::semi:
1188 case tok::r_paren:
1189 case tok::r_square:
1190 case tok::r_brace:
1191 case tok::colon:
1192 case tok::comma:
Douglas Gregor53e191ed2011-07-06 22:04:06 +00001193 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, 0);
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001194
Chris Lattner65dd8432008-04-06 06:02:23 +00001195 default:
John McCalldadc5752010-08-24 06:29:42 +00001196 ExprResult Expr(ParseAssignmentExpression());
Sebastian Redld65cea82008-12-11 22:51:44 +00001197 if (Expr.isInvalid()) return move(Expr);
Douglas Gregor53e191ed2011-07-06 22:04:06 +00001198 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.take());
Chris Lattner65dd8432008-04-06 06:02:23 +00001199 }
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001200}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001201
1202/// ParseCXXThis - This handles the C++ 'this' pointer.
1203///
1204/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1205/// a non-lvalue expression whose value is the address of the object for which
1206/// the function is called.
John McCalldadc5752010-08-24 06:29:42 +00001207ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001208 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1209 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001210 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001211}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001212
1213/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1214/// Can be interpreted either as function-style casting ("int(x)")
1215/// or class type construction ("ClassType(x,y,z)")
1216/// or creation of a value-initialized type ("int()").
Sebastian Redl3da34892011-06-05 12:23:16 +00001217/// See [C++ 5.2.3].
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001218///
1219/// postfix-expression: [C++ 5.2p1]
Sebastian Redl3da34892011-06-05 12:23:16 +00001220/// simple-type-specifier '(' expression-list[opt] ')'
1221/// [C++0x] simple-type-specifier braced-init-list
1222/// typename-specifier '(' expression-list[opt] ')'
1223/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001224///
John McCalldadc5752010-08-24 06:29:42 +00001225ExprResult
Sebastian Redld65cea82008-12-11 22:51:44 +00001226Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001227 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
John McCallba7bf592010-08-24 05:47:05 +00001228 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001229
Sebastian Redl3da34892011-06-05 12:23:16 +00001230 assert((Tok.is(tok::l_paren) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001231 (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)))
Sebastian Redl3da34892011-06-05 12:23:16 +00001232 && "Expected '(' or '{'!");
Douglas Gregor94a32472011-01-11 00:33:19 +00001233
Sebastian Redl3da34892011-06-05 12:23:16 +00001234 if (Tok.is(tok::l_brace)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001235 ExprResult Init = ParseBraceInitializer();
1236 if (Init.isInvalid())
1237 return Init;
1238 Expr *InitList = Init.take();
1239 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1240 MultiExprArg(&InitList, 1),
1241 SourceLocation());
Sebastian Redl3da34892011-06-05 12:23:16 +00001242 } else {
1243 GreaterThanIsOperatorScope G(GreaterThanIsOperator, true);
1244
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001245 BalancedDelimiterTracker T(*this, tok::l_paren);
1246 T.consumeOpen();
Sebastian Redl3da34892011-06-05 12:23:16 +00001247
1248 ExprVector Exprs(Actions);
1249 CommaLocsTy CommaLocs;
1250
1251 if (Tok.isNot(tok::r_paren)) {
1252 if (ParseExpressionList(Exprs, CommaLocs)) {
1253 SkipUntil(tok::r_paren);
1254 return ExprError();
1255 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001256 }
Sebastian Redl3da34892011-06-05 12:23:16 +00001257
1258 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001259 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00001260
1261 // TypeRep could be null, if it references an invalid typedef.
1262 if (!TypeRep)
1263 return ExprError();
1264
1265 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1266 "Unexpected number of commas!");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001267 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1268 move_arg(Exprs),
1269 T.getCloseLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001270 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001271}
1272
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001273/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001274///
1275/// condition:
1276/// expression
1277/// type-specifier-seq declarator '=' assignment-expression
Richard Smith2a15b742012-02-22 06:49:09 +00001278/// [C++11] type-specifier-seq declarator '=' initializer-clause
1279/// [C++11] type-specifier-seq declarator braced-init-list
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001280/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1281/// '=' assignment-expression
1282///
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001283/// \param ExprResult if the condition was parsed as an expression, the
1284/// parsed expression.
1285///
1286/// \param DeclResult if the condition was parsed as a declaration, the
1287/// parsed declaration.
1288///
Douglas Gregore60e41a2010-05-06 17:25:47 +00001289/// \param Loc The location of the start of the statement that requires this
1290/// condition, e.g., the "for" in a for loop.
1291///
1292/// \param ConvertToBoolean Whether the condition expression should be
1293/// converted to a boolean value.
1294///
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001295/// \returns true if there was a parsing, false otherwise.
John McCalldadc5752010-08-24 06:29:42 +00001296bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1297 Decl *&DeclOut,
Douglas Gregore60e41a2010-05-06 17:25:47 +00001298 SourceLocation Loc,
1299 bool ConvertToBoolean) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001300 if (Tok.is(tok::code_completion)) {
John McCallfaf5fb42010-08-26 23:41:50 +00001301 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001302 cutOffParsing();
1303 return true;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001304 }
1305
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001306 if (!isCXXConditionDeclaration()) {
Douglas Gregore60e41a2010-05-06 17:25:47 +00001307 // Parse the expression.
John McCalldadc5752010-08-24 06:29:42 +00001308 ExprOut = ParseExpression(); // expression
1309 DeclOut = 0;
1310 if (ExprOut.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001311 return true;
1312
1313 // If required, convert to a boolean value.
1314 if (ConvertToBoolean)
John McCalldadc5752010-08-24 06:29:42 +00001315 ExprOut
1316 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1317 return ExprOut.isInvalid();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001318 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001319
1320 // type-specifier-seq
John McCall084e83d2011-03-24 11:26:52 +00001321 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001322 ParseSpecifierQualifierList(DS);
1323
1324 // declarator
1325 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1326 ParseDeclarator(DeclaratorInfo);
1327
1328 // simple-asm-expr[opt]
1329 if (Tok.is(tok::kw_asm)) {
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001330 SourceLocation Loc;
John McCalldadc5752010-08-24 06:29:42 +00001331 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001332 if (AsmLabel.isInvalid()) {
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001333 SkipUntil(tok::semi);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001334 return true;
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001335 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001336 DeclaratorInfo.setAsmLabel(AsmLabel.release());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001337 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001338 }
1339
1340 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001341 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001342
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001343 // Type-check the declaration itself.
John McCalldadc5752010-08-24 06:29:42 +00001344 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall53fa7142010-12-24 02:08:15 +00001345 DeclaratorInfo);
John McCalldadc5752010-08-24 06:29:42 +00001346 DeclOut = Dcl.get();
1347 ExprOut = ExprError();
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001348
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001349 // '=' assignment-expression
Richard Trieuc64d3232012-01-18 22:54:52 +00001350 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith2a15b742012-02-22 06:49:09 +00001351 bool CopyInitialization = isTokenEqualOrEqualTypo();
1352 if (CopyInitialization)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001353 ConsumeToken();
Richard Smith2a15b742012-02-22 06:49:09 +00001354
1355 ExprResult InitExpr = ExprError();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001356 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
Richard Smith2a15b742012-02-22 06:49:09 +00001357 Diag(Tok.getLocation(),
1358 diag::warn_cxx98_compat_generalized_initializer_lists);
1359 InitExpr = ParseBraceInitializer();
1360 } else if (CopyInitialization) {
1361 InitExpr = ParseAssignmentExpression();
1362 } else if (Tok.is(tok::l_paren)) {
1363 // This was probably an attempt to initialize the variable.
1364 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1365 if (SkipUntil(tok::r_paren, true, /*DontConsume=*/true))
1366 RParen = ConsumeParen();
1367 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1368 diag::err_expected_init_in_condition_lparen)
1369 << SourceRange(LParen, RParen);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001370 } else {
Richard Smith2a15b742012-02-22 06:49:09 +00001371 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1372 diag::err_expected_init_in_condition);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001373 }
Richard Smith2a15b742012-02-22 06:49:09 +00001374
1375 if (!InitExpr.isInvalid())
1376 Actions.AddInitializerToDecl(DeclOut, InitExpr.take(), !CopyInitialization,
1377 DS.getTypeSpecType() == DeclSpec::TST_auto);
1378
Douglas Gregore60e41a2010-05-06 17:25:47 +00001379 // FIXME: Build a reference to this declaration? Convert it to bool?
1380 // (This is currently handled by Sema).
Richard Smithb2bc2e62011-02-21 20:05:19 +00001381
1382 Actions.FinalizeDeclaration(DeclOut);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001383
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001384 return false;
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001385}
1386
Douglas Gregor8d4de672010-04-21 22:36:40 +00001387/// \brief Determine whether the current token starts a C++
1388/// simple-type-specifier.
1389bool Parser::isCXXSimpleTypeSpecifier() const {
1390 switch (Tok.getKind()) {
1391 case tok::annot_typename:
1392 case tok::kw_short:
1393 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00001394 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00001395 case tok::kw___int128:
Douglas Gregor8d4de672010-04-21 22:36:40 +00001396 case tok::kw_signed:
1397 case tok::kw_unsigned:
1398 case tok::kw_void:
1399 case tok::kw_char:
1400 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001401 case tok::kw_half:
Douglas Gregor8d4de672010-04-21 22:36:40 +00001402 case tok::kw_float:
1403 case tok::kw_double:
1404 case tok::kw_wchar_t:
1405 case tok::kw_char16_t:
1406 case tok::kw_char32_t:
1407 case tok::kw_bool:
Douglas Gregor19b7acf2011-04-27 05:41:15 +00001408 case tok::kw_decltype:
Douglas Gregor8d4de672010-04-21 22:36:40 +00001409 case tok::kw_typeof:
Alexis Hunt4a257072011-05-19 05:37:45 +00001410 case tok::kw___underlying_type:
Douglas Gregor8d4de672010-04-21 22:36:40 +00001411 return true;
1412
1413 default:
1414 break;
1415 }
1416
1417 return false;
1418}
1419
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001420/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1421/// This should only be called when the current token is known to be part of
1422/// simple-type-specifier.
1423///
1424/// simple-type-specifier:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001425/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001426/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1427/// char
1428/// wchar_t
1429/// bool
1430/// short
1431/// int
1432/// long
1433/// signed
1434/// unsigned
1435/// float
1436/// double
1437/// void
1438/// [GNU] typeof-specifier
1439/// [C++0x] auto [TODO]
1440///
1441/// type-name:
1442/// class-name
1443/// enum-name
1444/// typedef-name
1445///
1446void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1447 DS.SetRangeStart(Tok.getLocation());
1448 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +00001449 unsigned DiagID;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001450 SourceLocation Loc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001451
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001452 switch (Tok.getKind()) {
Chris Lattner45ddec32009-01-05 00:13:00 +00001453 case tok::identifier: // foo::bar
1454 case tok::coloncolon: // ::foo::bar
David Blaikie83d382b2011-09-23 05:06:16 +00001455 llvm_unreachable("Annotation token should already be formed!");
Mike Stump11289f42009-09-09 15:08:12 +00001456 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001457 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner45ddec32009-01-05 00:13:00 +00001458
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001459 // type-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00001460 case tok::annot_typename: {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001461 if (getTypeAnnotation(Tok))
1462 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1463 getTypeAnnotation(Tok));
1464 else
1465 DS.SetTypeSpecError();
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001466
1467 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1468 ConsumeToken();
1469
1470 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1471 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1472 // Objective-C interface. If we don't have Objective-C or a '<', this is
1473 // just a normal reference to a typedef name.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001474 if (Tok.is(tok::less) && getLangOpts().ObjC1)
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001475 ParseObjCProtocolQualifiers(DS);
1476
1477 DS.Finish(Diags, PP);
1478 return;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001479 }
Mike Stump11289f42009-09-09 15:08:12 +00001480
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001481 // builtin types
1482 case tok::kw_short:
John McCall49bfce42009-08-03 20:12:06 +00001483 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001484 break;
1485 case tok::kw_long:
John McCall49bfce42009-08-03 20:12:06 +00001486 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001487 break;
Francois Pichet84133e42011-04-28 01:59:37 +00001488 case tok::kw___int64:
1489 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID);
1490 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001491 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00001492 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001493 break;
1494 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00001495 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001496 break;
1497 case tok::kw_void:
John McCall49bfce42009-08-03 20:12:06 +00001498 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001499 break;
1500 case tok::kw_char:
John McCall49bfce42009-08-03 20:12:06 +00001501 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001502 break;
1503 case tok::kw_int:
John McCall49bfce42009-08-03 20:12:06 +00001504 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001505 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00001506 case tok::kw___int128:
1507 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID);
1508 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001509 case tok::kw_half:
1510 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID);
1511 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001512 case tok::kw_float:
John McCall49bfce42009-08-03 20:12:06 +00001513 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001514 break;
1515 case tok::kw_double:
John McCall49bfce42009-08-03 20:12:06 +00001516 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001517 break;
1518 case tok::kw_wchar_t:
John McCall49bfce42009-08-03 20:12:06 +00001519 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001520 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001521 case tok::kw_char16_t:
John McCall49bfce42009-08-03 20:12:06 +00001522 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001523 break;
1524 case tok::kw_char32_t:
John McCall49bfce42009-08-03 20:12:06 +00001525 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001526 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001527 case tok::kw_bool:
John McCall49bfce42009-08-03 20:12:06 +00001528 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001529 break;
David Blaikie25896afb2012-01-24 05:47:35 +00001530 case tok::annot_decltype:
1531 case tok::kw_decltype:
1532 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1533 return DS.Finish(Diags, PP);
Mike Stump11289f42009-09-09 15:08:12 +00001534
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001535 // GNU typeof support.
1536 case tok::kw_typeof:
1537 ParseTypeofSpecifier(DS);
Douglas Gregore3e01a22009-04-01 22:41:11 +00001538 DS.Finish(Diags, PP);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001539 return;
1540 }
Chris Lattnera8a3f732009-01-06 05:06:21 +00001541 if (Tok.is(tok::annot_typename))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001542 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1543 else
1544 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001545 ConsumeToken();
Douglas Gregore3e01a22009-04-01 22:41:11 +00001546 DS.Finish(Diags, PP);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001547}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001548
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001549/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1550/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1551/// e.g., "const short int". Note that the DeclSpec is *not* finished
1552/// by parsing the type-specifier-seq, because these sequences are
1553/// typically followed by some form of declarator. Returns true and
1554/// emits diagnostics if this is not a type-specifier-seq, false
1555/// otherwise.
1556///
1557/// type-specifier-seq: [C++ 8.1]
1558/// type-specifier type-specifier-seq[opt]
1559///
1560bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Richard Smithc5b05522012-03-12 07:56:15 +00001561 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
Douglas Gregor40d732f2010-02-24 23:13:13 +00001562 DS.Finish(Diags, PP);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001563 return false;
1564}
1565
Douglas Gregor7861a802009-11-03 01:35:08 +00001566/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1567/// some form.
1568///
1569/// This routine is invoked when a '<' is encountered after an identifier or
1570/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1571/// whether the unqualified-id is actually a template-id. This routine will
1572/// then parse the template arguments and form the appropriate template-id to
1573/// return to the caller.
1574///
1575/// \param SS the nested-name-specifier that precedes this template-id, if
1576/// we're actually parsing a qualified-id.
1577///
1578/// \param Name for constructor and destructor names, this is the actual
1579/// identifier that may be a template-name.
1580///
1581/// \param NameLoc the location of the class-name in a constructor or
1582/// destructor.
1583///
1584/// \param EnteringContext whether we're entering the scope of the
1585/// nested-name-specifier.
1586///
Douglas Gregor127ea592009-11-03 21:24:04 +00001587/// \param ObjectType if this unqualified-id occurs within a member access
1588/// expression, the type of the base object whose member is being accessed.
1589///
Douglas Gregor7861a802009-11-03 01:35:08 +00001590/// \param Id as input, describes the template-name or operator-function-id
1591/// that precedes the '<'. If template arguments were parsed successfully,
1592/// will be updated with the template-id.
1593///
Douglas Gregore610ada2010-02-24 18:44:31 +00001594/// \param AssumeTemplateId When true, this routine will assume that the name
1595/// refers to a template without performing name lookup to verify.
1596///
Douglas Gregor7861a802009-11-03 01:35:08 +00001597/// \returns true if a parse error occurred, false otherwise.
1598bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001599 SourceLocation TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00001600 IdentifierInfo *Name,
1601 SourceLocation NameLoc,
1602 bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00001603 ParsedType ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00001604 UnqualifiedId &Id,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001605 bool AssumeTemplateId) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00001606 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1607 "Expected '<' to finish parsing a template-id");
Douglas Gregor7861a802009-11-03 01:35:08 +00001608
1609 TemplateTy Template;
1610 TemplateNameKind TNK = TNK_Non_template;
1611 switch (Id.getKind()) {
1612 case UnqualifiedId::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +00001613 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunted0530f2009-11-28 08:58:14 +00001614 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregore610ada2010-02-24 18:44:31 +00001615 if (AssumeTemplateId) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001616 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00001617 Id, ObjectType, EnteringContext,
1618 Template);
1619 if (TNK == TNK_Non_template)
1620 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00001621 } else {
1622 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001623 TNK = Actions.isTemplateName(getCurScope(), SS,
1624 TemplateKWLoc.isValid(), Id,
1625 ObjectType, EnteringContext, Template,
Douglas Gregor786123d2010-05-21 23:18:07 +00001626 MemberOfUnknownSpecialization);
1627
1628 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1629 ObjectType && IsTemplateArgumentList()) {
1630 // We have something like t->getAs<T>(), where getAs is a
1631 // member of an unknown specialization. However, this will only
1632 // parse correctly as a template, so suggest the keyword 'template'
1633 // before 'getAs' and treat this as a dependent template name.
1634 std::string Name;
1635 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1636 Name = Id.Identifier->getName();
1637 else {
1638 Name = "operator ";
1639 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1640 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1641 else
1642 Name += Id.Identifier->getName();
1643 }
1644 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1645 << Name
1646 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Abramo Bagnara7945c982012-01-27 09:46:47 +00001647 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1648 SS, TemplateKWLoc, Id,
1649 ObjectType, EnteringContext,
1650 Template);
Douglas Gregorbb119652010-06-16 23:00:59 +00001651 if (TNK == TNK_Non_template)
Douglas Gregor786123d2010-05-21 23:18:07 +00001652 return true;
1653 }
1654 }
Douglas Gregor7861a802009-11-03 01:35:08 +00001655 break;
1656
Douglas Gregor3cf81312009-11-03 23:16:33 +00001657 case UnqualifiedId::IK_ConstructorName: {
1658 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00001659 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001660 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001661 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1662 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00001663 EnteringContext, Template,
1664 MemberOfUnknownSpecialization);
Douglas Gregor7861a802009-11-03 01:35:08 +00001665 break;
1666 }
1667
Douglas Gregor3cf81312009-11-03 23:16:33 +00001668 case UnqualifiedId::IK_DestructorName: {
1669 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00001670 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001671 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001672 if (ObjectType) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001673 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1674 SS, TemplateKWLoc, TemplateName,
1675 ObjectType, EnteringContext,
1676 Template);
Douglas Gregorbb119652010-06-16 23:00:59 +00001677 if (TNK == TNK_Non_template)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001678 return true;
1679 } else {
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001680 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1681 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00001682 EnteringContext, Template,
1683 MemberOfUnknownSpecialization);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001684
John McCallba7bf592010-08-24 05:47:05 +00001685 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001686 Diag(NameLoc, diag::err_destructor_template_id)
1687 << Name << SS.getRange();
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001688 return true;
1689 }
1690 }
Douglas Gregor7861a802009-11-03 01:35:08 +00001691 break;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001692 }
Douglas Gregor7861a802009-11-03 01:35:08 +00001693
1694 default:
1695 return false;
1696 }
1697
1698 if (TNK == TNK_Non_template)
1699 return false;
1700
1701 // Parse the enclosed template argument list.
1702 SourceLocation LAngleLoc, RAngleLoc;
1703 TemplateArgList TemplateArgs;
Douglas Gregorb22ee882010-05-05 05:58:24 +00001704 if (Tok.is(tok::less) &&
1705 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
Douglas Gregore7c20652011-03-02 00:47:37 +00001706 SS, true, LAngleLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00001707 TemplateArgs,
Douglas Gregor7861a802009-11-03 01:35:08 +00001708 RAngleLoc))
1709 return true;
1710
1711 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
Alexis Hunted0530f2009-11-28 08:58:14 +00001712 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1713 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor7861a802009-11-03 01:35:08 +00001714 // Form a parsed representation of the template-id to be stored in the
1715 // UnqualifiedId.
1716 TemplateIdAnnotation *TemplateId
Benjamin Kramer1e6b6062012-04-14 12:14:03 +00001717 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor7861a802009-11-03 01:35:08 +00001718
1719 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
1720 TemplateId->Name = Id.Identifier;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001721 TemplateId->Operator = OO_None;
Douglas Gregor7861a802009-11-03 01:35:08 +00001722 TemplateId->TemplateNameLoc = Id.StartLocation;
1723 } else {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001724 TemplateId->Name = 0;
1725 TemplateId->Operator = Id.OperatorFunctionId.Operator;
1726 TemplateId->TemplateNameLoc = Id.StartLocation;
Douglas Gregor7861a802009-11-03 01:35:08 +00001727 }
1728
Douglas Gregore7c20652011-03-02 00:47:37 +00001729 TemplateId->SS = SS;
Benjamin Kramer807c2db2012-02-19 23:37:39 +00001730 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall3e56fd42010-08-23 07:28:44 +00001731 TemplateId->Template = Template;
Douglas Gregor7861a802009-11-03 01:35:08 +00001732 TemplateId->Kind = TNK;
1733 TemplateId->LAngleLoc = LAngleLoc;
1734 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001735 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
Douglas Gregor7861a802009-11-03 01:35:08 +00001736 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001737 Arg != ArgEnd; ++Arg)
Douglas Gregor7861a802009-11-03 01:35:08 +00001738 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor7861a802009-11-03 01:35:08 +00001739
1740 Id.setTemplateId(TemplateId);
1741 return false;
1742 }
1743
1744 // Bundle the template arguments together.
1745 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
Douglas Gregor7861a802009-11-03 01:35:08 +00001746 TemplateArgs.size());
Abramo Bagnara4244b432012-01-27 08:46:19 +00001747
Douglas Gregor7861a802009-11-03 01:35:08 +00001748 // Constructor and destructor names.
John McCallfaf5fb42010-08-26 23:41:50 +00001749 TypeResult Type
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001750 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
1751 Template, NameLoc,
Abramo Bagnara4244b432012-01-27 08:46:19 +00001752 LAngleLoc, TemplateArgsPtr, RAngleLoc,
1753 /*IsCtorOrDtorName=*/true);
Douglas Gregor7861a802009-11-03 01:35:08 +00001754 if (Type.isInvalid())
1755 return true;
1756
1757 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
1758 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
1759 else
1760 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
1761
1762 return false;
1763}
1764
Douglas Gregor71395fa2009-11-04 00:56:37 +00001765/// \brief Parse an operator-function-id or conversion-function-id as part
1766/// of a C++ unqualified-id.
1767///
1768/// This routine is responsible only for parsing the operator-function-id or
1769/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor7861a802009-11-03 01:35:08 +00001770///
1771/// \code
Douglas Gregor7861a802009-11-03 01:35:08 +00001772/// operator-function-id: [C++ 13.5]
1773/// 'operator' operator
1774///
Douglas Gregor71395fa2009-11-04 00:56:37 +00001775/// operator: one of
Douglas Gregor7861a802009-11-03 01:35:08 +00001776/// new delete new[] delete[]
1777/// + - * / % ^ & | ~
1778/// ! = < > += -= *= /= %=
1779/// ^= &= |= << >> >>= <<= == !=
1780/// <= >= && || ++ -- , ->* ->
1781/// () []
1782///
1783/// conversion-function-id: [C++ 12.3.2]
1784/// operator conversion-type-id
1785///
1786/// conversion-type-id:
1787/// type-specifier-seq conversion-declarator[opt]
1788///
1789/// conversion-declarator:
1790/// ptr-operator conversion-declarator[opt]
1791/// \endcode
1792///
1793/// \param The nested-name-specifier that preceded this unqualified-id. If
1794/// non-empty, then we are parsing the unqualified-id of a qualified-id.
1795///
1796/// \param EnteringContext whether we are entering the scope of the
1797/// nested-name-specifier.
1798///
Douglas Gregor71395fa2009-11-04 00:56:37 +00001799/// \param ObjectType if this unqualified-id occurs within a member access
1800/// expression, the type of the base object whose member is being accessed.
1801///
1802/// \param Result on a successful parse, contains the parsed unqualified-id.
1803///
1804/// \returns true if parsing fails, false otherwise.
1805bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00001806 ParsedType ObjectType,
Douglas Gregor71395fa2009-11-04 00:56:37 +00001807 UnqualifiedId &Result) {
1808 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
1809
1810 // Consume the 'operator' keyword.
1811 SourceLocation KeywordLoc = ConsumeToken();
1812
1813 // Determine what kind of operator name we have.
1814 unsigned SymbolIdx = 0;
1815 SourceLocation SymbolLocations[3];
1816 OverloadedOperatorKind Op = OO_None;
1817 switch (Tok.getKind()) {
1818 case tok::kw_new:
1819 case tok::kw_delete: {
1820 bool isNew = Tok.getKind() == tok::kw_new;
1821 // Consume the 'new' or 'delete'.
1822 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001823 // Check for array new/delete.
1824 if (Tok.is(tok::l_square) &&
1825 (!getLangOpts().CPlusPlus0x || NextToken().isNot(tok::l_square))) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001826 // Consume the '[' and ']'.
1827 BalancedDelimiterTracker T(*this, tok::l_square);
1828 T.consumeOpen();
1829 T.consumeClose();
1830 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00001831 return true;
1832
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001833 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1834 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00001835 Op = isNew? OO_Array_New : OO_Array_Delete;
1836 } else {
1837 Op = isNew? OO_New : OO_Delete;
1838 }
1839 break;
1840 }
1841
1842#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1843 case tok::Token: \
1844 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
1845 Op = OO_##Name; \
1846 break;
1847#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
1848#include "clang/Basic/OperatorKinds.def"
1849
1850 case tok::l_paren: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001851 // Consume the '(' and ')'.
1852 BalancedDelimiterTracker T(*this, tok::l_paren);
1853 T.consumeOpen();
1854 T.consumeClose();
1855 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00001856 return true;
1857
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001858 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1859 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00001860 Op = OO_Call;
1861 break;
1862 }
1863
1864 case tok::l_square: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001865 // Consume the '[' and ']'.
1866 BalancedDelimiterTracker T(*this, tok::l_square);
1867 T.consumeOpen();
1868 T.consumeClose();
1869 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00001870 return true;
1871
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001872 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1873 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00001874 Op = OO_Subscript;
1875 break;
1876 }
1877
1878 case tok::code_completion: {
1879 // Code completion for the operator name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001880 Actions.CodeCompleteOperatorName(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001881 cutOffParsing();
Douglas Gregor71395fa2009-11-04 00:56:37 +00001882 // Don't try to parse any further.
1883 return true;
1884 }
1885
1886 default:
1887 break;
1888 }
1889
1890 if (Op != OO_None) {
1891 // We have parsed an operator-function-id.
1892 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
1893 return false;
1894 }
Alexis Hunt34458502009-11-28 04:44:28 +00001895
1896 // Parse a literal-operator-id.
1897 //
1898 // literal-operator-id: [C++0x 13.5.8]
1899 // operator "" identifier
1900
David Blaikiebbafb8a2012-03-11 07:00:24 +00001901 if (getLangOpts().CPlusPlus0x && isTokenStringLiteral()) {
Richard Smith5d164bc2011-10-15 05:09:34 +00001902 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Alexis Hunt34458502009-11-28 04:44:28 +00001903
Richard Smith7d182a72012-03-08 23:06:02 +00001904 SourceLocation DiagLoc;
1905 unsigned DiagId = 0;
1906
1907 // We're past translation phase 6, so perform string literal concatenation
1908 // before checking for "".
1909 llvm::SmallVector<Token, 4> Toks;
1910 llvm::SmallVector<SourceLocation, 4> TokLocs;
1911 while (isTokenStringLiteral()) {
1912 if (!Tok.is(tok::string_literal) && !DiagId) {
1913 DiagLoc = Tok.getLocation();
1914 DiagId = diag::err_literal_operator_string_prefix;
1915 }
1916 Toks.push_back(Tok);
1917 TokLocs.push_back(ConsumeStringToken());
1918 }
1919
1920 StringLiteralParser Literal(Toks.data(), Toks.size(), PP);
1921 if (Literal.hadError)
1922 return true;
1923
1924 // Grab the literal operator's suffix, which will be either the next token
1925 // or a ud-suffix from the string literal.
1926 IdentifierInfo *II = 0;
1927 SourceLocation SuffixLoc;
1928 if (!Literal.getUDSuffix().empty()) {
1929 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
1930 SuffixLoc =
1931 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
1932 Literal.getUDSuffixOffset(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001933 PP.getSourceManager(), getLangOpts());
Richard Smith7d182a72012-03-08 23:06:02 +00001934 // This form is not permitted by the standard (yet).
1935 DiagLoc = SuffixLoc;
1936 DiagId = diag::err_literal_operator_missing_space;
1937 } else if (Tok.is(tok::identifier)) {
1938 II = Tok.getIdentifierInfo();
1939 SuffixLoc = ConsumeToken();
1940 TokLocs.push_back(SuffixLoc);
1941 } else {
Alexis Hunt34458502009-11-28 04:44:28 +00001942 Diag(Tok.getLocation(), diag::err_expected_ident);
1943 return true;
1944 }
1945
Richard Smith7d182a72012-03-08 23:06:02 +00001946 // The string literal must be empty.
1947 if (!Literal.GetString().empty() || Literal.Pascal) {
1948 DiagLoc = TokLocs.front();
1949 DiagId = diag::err_literal_operator_string_not_empty;
1950 }
1951
1952 if (DiagId) {
1953 // This isn't a valid literal-operator-id, but we think we know
1954 // what the user meant. Tell them what they should have written.
1955 llvm::SmallString<32> Str;
1956 Str += "\"\" ";
1957 Str += II->getName();
1958 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
1959 SourceRange(TokLocs.front(), TokLocs.back()), Str);
1960 }
1961
1962 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Alexis Hunt3d221f22009-11-29 07:34:05 +00001963 return false;
Alexis Hunt34458502009-11-28 04:44:28 +00001964 }
Douglas Gregor71395fa2009-11-04 00:56:37 +00001965
1966 // Parse a conversion-function-id.
1967 //
1968 // conversion-function-id: [C++ 12.3.2]
1969 // operator conversion-type-id
1970 //
1971 // conversion-type-id:
1972 // type-specifier-seq conversion-declarator[opt]
1973 //
1974 // conversion-declarator:
1975 // ptr-operator conversion-declarator[opt]
1976
1977 // Parse the type-specifier-seq.
John McCall084e83d2011-03-24 11:26:52 +00001978 DeclSpec DS(AttrFactory);
Douglas Gregora25d65d2009-11-20 22:03:38 +00001979 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregor71395fa2009-11-04 00:56:37 +00001980 return true;
1981
1982 // Parse the conversion-declarator, which is merely a sequence of
1983 // ptr-operators.
1984 Declarator D(DS, Declarator::TypeNameContext);
1985 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
1986
1987 // Finish up the type.
John McCallfaf5fb42010-08-26 23:41:50 +00001988 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregor71395fa2009-11-04 00:56:37 +00001989 if (Ty.isInvalid())
1990 return true;
1991
1992 // Note that this is a conversion-function-id.
1993 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
1994 D.getSourceRange().getEnd());
1995 return false;
1996}
1997
1998/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
1999/// name of an entity.
2000///
2001/// \code
2002/// unqualified-id: [C++ expr.prim.general]
2003/// identifier
2004/// operator-function-id
2005/// conversion-function-id
2006/// [C++0x] literal-operator-id [TODO]
2007/// ~ class-name
2008/// template-id
2009///
2010/// \endcode
2011///
2012/// \param The nested-name-specifier that preceded this unqualified-id. If
2013/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2014///
2015/// \param EnteringContext whether we are entering the scope of the
2016/// nested-name-specifier.
2017///
Douglas Gregor7861a802009-11-03 01:35:08 +00002018/// \param AllowDestructorName whether we allow parsing of a destructor name.
2019///
2020/// \param AllowConstructorName whether we allow parsing a constructor name.
2021///
Douglas Gregor127ea592009-11-03 21:24:04 +00002022/// \param ObjectType if this unqualified-id occurs within a member access
2023/// expression, the type of the base object whose member is being accessed.
2024///
Douglas Gregor7861a802009-11-03 01:35:08 +00002025/// \param Result on a successful parse, contains the parsed unqualified-id.
2026///
2027/// \returns true if parsing fails, false otherwise.
2028bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2029 bool AllowDestructorName,
2030 bool AllowConstructorName,
John McCallba7bf592010-08-24 05:47:05 +00002031 ParsedType ObjectType,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002032 SourceLocation& TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002033 UnqualifiedId &Result) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00002034
2035 // Handle 'A::template B'. This is for template-ids which have not
2036 // already been annotated by ParseOptionalCXXScopeSpecifier().
2037 bool TemplateSpecified = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002038 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002039 (ObjectType || SS.isSet())) {
2040 TemplateSpecified = true;
2041 TemplateKWLoc = ConsumeToken();
2042 }
2043
Douglas Gregor7861a802009-11-03 01:35:08 +00002044 // unqualified-id:
2045 // identifier
2046 // template-id (when it hasn't already been annotated)
2047 if (Tok.is(tok::identifier)) {
2048 // Consume the identifier.
2049 IdentifierInfo *Id = Tok.getIdentifierInfo();
2050 SourceLocation IdLoc = ConsumeToken();
2051
David Blaikiebbafb8a2012-03-11 07:00:24 +00002052 if (!getLangOpts().CPlusPlus) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002053 // If we're not in C++, only identifiers matter. Record the
2054 // identifier and return.
2055 Result.setIdentifier(Id, IdLoc);
2056 return false;
2057 }
2058
Douglas Gregor7861a802009-11-03 01:35:08 +00002059 if (AllowConstructorName &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002060 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002061 // We have parsed a constructor name.
Abramo Bagnara4244b432012-01-27 08:46:19 +00002062 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2063 &SS, false, false,
2064 ParsedType(),
2065 /*IsCtorOrDtorName=*/true,
2066 /*NonTrivialTypeSourceInfo=*/true);
2067 Result.setConstructorName(Ty, IdLoc, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002068 } else {
2069 // We have parsed an identifier.
2070 Result.setIdentifier(Id, IdLoc);
2071 }
2072
2073 // If the next token is a '<', we may have a template.
Douglas Gregorb22ee882010-05-05 05:58:24 +00002074 if (TemplateSpecified || Tok.is(tok::less))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002075 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2076 EnteringContext, ObjectType,
2077 Result, TemplateSpecified);
Douglas Gregor7861a802009-11-03 01:35:08 +00002078
2079 return false;
2080 }
2081
2082 // unqualified-id:
2083 // template-id (already parsed and annotated)
2084 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00002085 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002086
2087 // If the template-name names the current class, then this is a constructor
2088 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002089 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002090 if (SS.isSet()) {
2091 // C++ [class.qual]p2 specifies that a qualified template-name
2092 // is taken as the constructor name where a constructor can be
2093 // declared. Thus, the template arguments are extraneous, so
2094 // complain about them and remove them entirely.
2095 Diag(TemplateId->TemplateNameLoc,
2096 diag::err_out_of_line_constructor_template_id)
2097 << TemplateId->Name
Douglas Gregora771f462010-03-31 17:46:05 +00002098 << FixItHint::CreateRemoval(
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002099 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Abramo Bagnara4244b432012-01-27 08:46:19 +00002100 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2101 TemplateId->TemplateNameLoc,
2102 getCurScope(),
2103 &SS, false, false,
2104 ParsedType(),
2105 /*IsCtorOrDtorName=*/true,
2106 /*NontrivialTypeSourceInfo=*/true);
2107 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002108 TemplateId->RAngleLoc);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002109 ConsumeToken();
2110 return false;
2111 }
2112
2113 Result.setConstructorTemplateId(TemplateId);
2114 ConsumeToken();
2115 return false;
2116 }
2117
Douglas Gregor7861a802009-11-03 01:35:08 +00002118 // We have already parsed a template-id; consume the annotation token as
2119 // our unqualified-id.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002120 Result.setTemplateId(TemplateId);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002121 TemplateKWLoc = TemplateId->TemplateKWLoc;
Douglas Gregor7861a802009-11-03 01:35:08 +00002122 ConsumeToken();
2123 return false;
2124 }
2125
2126 // unqualified-id:
2127 // operator-function-id
2128 // conversion-function-id
2129 if (Tok.is(tok::kw_operator)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00002130 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor7861a802009-11-03 01:35:08 +00002131 return true;
2132
Alexis Hunted0530f2009-11-28 08:58:14 +00002133 // If we have an operator-function-id or a literal-operator-id and the next
2134 // token is a '<', we may have a
Douglas Gregor71395fa2009-11-04 00:56:37 +00002135 //
2136 // template-id:
2137 // operator-function-id < template-argument-list[opt] >
Alexis Hunted0530f2009-11-28 08:58:14 +00002138 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2139 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002140 (TemplateSpecified || Tok.is(tok::less)))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002141 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2142 0, SourceLocation(),
2143 EnteringContext, ObjectType,
2144 Result, TemplateSpecified);
Douglas Gregor7861a802009-11-03 01:35:08 +00002145
Douglas Gregor7861a802009-11-03 01:35:08 +00002146 return false;
2147 }
2148
David Blaikiebbafb8a2012-03-11 07:00:24 +00002149 if (getLangOpts().CPlusPlus &&
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002150 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002151 // C++ [expr.unary.op]p10:
2152 // There is an ambiguity in the unary-expression ~X(), where X is a
2153 // class-name. The ambiguity is resolved in favor of treating ~ as a
2154 // unary complement rather than treating ~X as referring to a destructor.
2155
2156 // Parse the '~'.
2157 SourceLocation TildeLoc = ConsumeToken();
David Blaikieecd8a942011-12-08 16:13:53 +00002158
2159 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2160 DeclSpec DS(AttrFactory);
2161 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2162 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2163 Result.setDestructorName(TildeLoc, Type, EndLoc);
2164 return false;
2165 }
2166 return true;
2167 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002168
2169 // Parse the class-name.
2170 if (Tok.isNot(tok::identifier)) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002171 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00002172 return true;
2173 }
2174
2175 // Parse the class-name (or template-name in a simple-template-id).
2176 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2177 SourceLocation ClassNameLoc = ConsumeToken();
2178
Douglas Gregorb22ee882010-05-05 05:58:24 +00002179 if (TemplateSpecified || Tok.is(tok::less)) {
John McCallba7bf592010-08-24 05:47:05 +00002180 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002181 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2182 ClassName, ClassNameLoc,
2183 EnteringContext, ObjectType,
2184 Result, TemplateSpecified);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002185 }
2186
Douglas Gregor7861a802009-11-03 01:35:08 +00002187 // Note that this is a destructor name.
John McCallba7bf592010-08-24 05:47:05 +00002188 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2189 ClassNameLoc, getCurScope(),
2190 SS, ObjectType,
2191 EnteringContext);
Douglas Gregorfe17d252010-02-16 19:09:40 +00002192 if (!Ty)
Douglas Gregor7861a802009-11-03 01:35:08 +00002193 return true;
Douglas Gregorfe17d252010-02-16 19:09:40 +00002194
Douglas Gregor7861a802009-11-03 01:35:08 +00002195 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002196 return false;
2197 }
2198
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002199 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002200 << getLangOpts().CPlusPlus;
Douglas Gregor7861a802009-11-03 01:35:08 +00002201 return true;
2202}
2203
Sebastian Redlbd150f42008-11-21 19:14:01 +00002204/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2205/// memory in a typesafe manner and call constructors.
Mike Stump11289f42009-09-09 15:08:12 +00002206///
Chris Lattner109faf22009-01-04 21:25:24 +00002207/// This method is called to parse the new expression after the optional :: has
2208/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2209/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002210///
2211/// new-expression:
2212/// '::'[opt] 'new' new-placement[opt] new-type-id
2213/// new-initializer[opt]
2214/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2215/// new-initializer[opt]
2216///
2217/// new-placement:
2218/// '(' expression-list ')'
2219///
Sebastian Redl351bb782008-12-02 14:43:59 +00002220/// new-type-id:
2221/// type-specifier-seq new-declarator[opt]
Douglas Gregora3a020a2011-04-15 19:40:02 +00002222/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redl351bb782008-12-02 14:43:59 +00002223///
2224/// new-declarator:
2225/// ptr-operator new-declarator[opt]
2226/// direct-new-declarator
2227///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002228/// new-initializer:
2229/// '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00002230/// [C++0x] braced-init-list
Sebastian Redlbd150f42008-11-21 19:14:01 +00002231///
John McCalldadc5752010-08-24 06:29:42 +00002232ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002233Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2234 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2235 ConsumeToken(); // Consume 'new'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002236
2237 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2238 // second form of new-expression. It can't be a new-type-id.
2239
Sebastian Redl511ed552008-11-25 22:21:31 +00002240 ExprVector PlacementArgs(Actions);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002241 SourceLocation PlacementLParen, PlacementRParen;
2242
Douglas Gregorf2753b32010-07-13 15:54:32 +00002243 SourceRange TypeIdParens;
John McCall084e83d2011-03-24 11:26:52 +00002244 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +00002245 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002246 if (Tok.is(tok::l_paren)) {
2247 // If it turns out to be a placement, we change the type location.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002248 BalancedDelimiterTracker T(*this, tok::l_paren);
2249 T.consumeOpen();
2250 PlacementLParen = T.getOpenLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002251 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2252 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redld65cea82008-12-11 22:51:44 +00002253 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002254 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002255
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002256 T.consumeClose();
2257 PlacementRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002258 if (PlacementRParen.isInvalid()) {
2259 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redld65cea82008-12-11 22:51:44 +00002260 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002261 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002262
Sebastian Redl351bb782008-12-02 14:43:59 +00002263 if (PlacementArgs.empty()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002264 // Reset the placement locations. There was no placement.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002265 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002266 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002267 } else {
2268 // We still need the type.
2269 if (Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002270 BalancedDelimiterTracker T(*this, tok::l_paren);
2271 T.consumeOpen();
Douglas Gregora3a020a2011-04-15 19:40:02 +00002272 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002273 ParseSpecifierQualifierList(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002274 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002275 ParseDeclarator(DeclaratorInfo);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002276 T.consumeClose();
2277 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002278 } else {
Douglas Gregora3a020a2011-04-15 19:40:02 +00002279 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002280 if (ParseCXXTypeSpecifierSeq(DS))
2281 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002282 else {
2283 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002284 ParseDeclaratorInternal(DeclaratorInfo,
2285 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002286 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002287 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002288 }
2289 } else {
Sebastian Redl351bb782008-12-02 14:43:59 +00002290 // A new-type-id is a simplified type-id, where essentially the
2291 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregora3a020a2011-04-15 19:40:02 +00002292 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002293 if (ParseCXXTypeSpecifierSeq(DS))
2294 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002295 else {
2296 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002297 ParseDeclaratorInternal(DeclaratorInfo,
2298 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002299 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002300 }
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002301 if (DeclaratorInfo.isInvalidType()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00002302 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redld65cea82008-12-11 22:51:44 +00002303 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002304 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002305
Sebastian Redl6047f072012-02-16 12:22:20 +00002306 ExprResult Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002307
2308 if (Tok.is(tok::l_paren)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00002309 SourceLocation ConstructorLParen, ConstructorRParen;
2310 ExprVector ConstructorArgs(Actions);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002311 BalancedDelimiterTracker T(*this, tok::l_paren);
2312 T.consumeOpen();
2313 ConstructorLParen = T.getOpenLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002314 if (Tok.isNot(tok::r_paren)) {
2315 CommaLocsTy CommaLocs;
Sebastian Redl351bb782008-12-02 14:43:59 +00002316 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
2317 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redld65cea82008-12-11 22:51:44 +00002318 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002319 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002320 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002321 T.consumeClose();
2322 ConstructorRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002323 if (ConstructorRParen.isInvalid()) {
2324 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redld65cea82008-12-11 22:51:44 +00002325 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002326 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002327 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2328 ConstructorRParen,
2329 move_arg(ConstructorArgs));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002330 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus0x) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002331 Diag(Tok.getLocation(),
2332 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl6047f072012-02-16 12:22:20 +00002333 Initializer = ParseBraceInitializer();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002334 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002335 if (Initializer.isInvalid())
2336 return Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002337
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002338 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2339 move_arg(PlacementArgs), PlacementRParen,
Sebastian Redl6047f072012-02-16 12:22:20 +00002340 TypeIdParens, DeclaratorInfo, Initializer.take());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002341}
2342
Sebastian Redlbd150f42008-11-21 19:14:01 +00002343/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2344/// passed to ParseDeclaratorInternal.
2345///
2346/// direct-new-declarator:
2347/// '[' expression ']'
2348/// direct-new-declarator '[' constant-expression ']'
2349///
Chris Lattner109faf22009-01-04 21:25:24 +00002350void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002351 // Parse the array dimensions.
2352 bool first = true;
2353 while (Tok.is(tok::l_square)) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002354 // An array-size expression can't start with a lambda.
2355 if (CheckProhibitedCXX11Attribute())
2356 continue;
2357
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002358 BalancedDelimiterTracker T(*this, tok::l_square);
2359 T.consumeOpen();
2360
John McCalldadc5752010-08-24 06:29:42 +00002361 ExprResult Size(first ? ParseExpression()
Sebastian Redl59b5e512008-12-11 21:36:32 +00002362 : ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002363 if (Size.isInvalid()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002364 // Recover
2365 SkipUntil(tok::r_square);
2366 return;
2367 }
2368 first = false;
2369
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002370 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00002371
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002372 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2373 ParsedAttributes Attrs(AttrFactory);
2374 MaybeParseCXX0XAttributes(Attrs);
2375
John McCall084e83d2011-03-24 11:26:52 +00002376 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall53fa7142010-12-24 02:08:15 +00002377 /*static=*/false, /*star=*/false,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002378 Size.release(),
2379 T.getOpenLocation(),
2380 T.getCloseLocation()),
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002381 Attrs, T.getCloseLocation());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002382
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002383 if (T.getCloseLocation().isInvalid())
Sebastian Redlbd150f42008-11-21 19:14:01 +00002384 return;
2385 }
2386}
2387
2388/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2389/// This ambiguity appears in the syntax of the C++ new operator.
2390///
2391/// new-expression:
2392/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2393/// new-initializer[opt]
2394///
2395/// new-placement:
2396/// '(' expression-list ')'
2397///
John McCall37ad5512010-08-23 06:44:23 +00002398bool Parser::ParseExpressionListOrTypeId(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002399 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner109faf22009-01-04 21:25:24 +00002400 Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002401 // The '(' was already consumed.
2402 if (isTypeIdInParens()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00002403 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002404 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002405 ParseDeclarator(D);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002406 return D.isInvalidType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002407 }
2408
2409 // It's not a type, it has to be an expression list.
2410 // Discard the comma locations - ActOnCXXNew has enough parameters.
2411 CommaLocsTy CommaLocs;
2412 return ParseExpressionList(PlacementArgs, CommaLocs);
2413}
2414
2415/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2416/// to free memory allocated by new.
2417///
Chris Lattner109faf22009-01-04 21:25:24 +00002418/// This method is called to parse the 'delete' expression after the optional
2419/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2420/// and "Start" is its location. Otherwise, "Start" is the location of the
2421/// 'delete' token.
2422///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002423/// delete-expression:
2424/// '::'[opt] 'delete' cast-expression
2425/// '::'[opt] 'delete' '[' ']' cast-expression
John McCalldadc5752010-08-24 06:29:42 +00002426ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002427Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2428 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2429 ConsumeToken(); // Consume 'delete'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002430
2431 // Array delete?
2432 bool ArrayDelete = false;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002433 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2434 // FIXME: This could be the start of a lambda-expression. We should
2435 // disambiguate this, but that will require arbitrary lookahead if
2436 // the next token is '(':
2437 // delete [](int*){ /* ... */
Sebastian Redlbd150f42008-11-21 19:14:01 +00002438 ArrayDelete = true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002439 BalancedDelimiterTracker T(*this, tok::l_square);
2440
2441 T.consumeOpen();
2442 T.consumeClose();
2443 if (T.getCloseLocation().isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00002444 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002445 }
2446
John McCalldadc5752010-08-24 06:29:42 +00002447 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002448 if (Operand.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00002449 return move(Operand);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002450
John McCallb268a282010-08-23 23:25:46 +00002451 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002452}
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002453
Mike Stump11289f42009-09-09 15:08:12 +00002454static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002455 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002456 default: llvm_unreachable("Not a known unary type trait.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002457 case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002458 case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor;
John Wiegley65497cc2011-04-27 23:09:49 +00002459 case tok::kw___has_nothrow_copy: return UTT_HasNothrowCopy;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002460 case tok::kw___has_trivial_assign: return UTT_HasTrivialAssign;
Alexis Huntf479f1b2011-05-09 18:22:59 +00002461 case tok::kw___has_trivial_constructor:
2462 return UTT_HasTrivialDefaultConstructor;
John Wiegley65497cc2011-04-27 23:09:49 +00002463 case tok::kw___has_trivial_copy: return UTT_HasTrivialCopy;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002464 case tok::kw___has_trivial_destructor: return UTT_HasTrivialDestructor;
2465 case tok::kw___has_virtual_destructor: return UTT_HasVirtualDestructor;
2466 case tok::kw___is_abstract: return UTT_IsAbstract;
John Wiegley65497cc2011-04-27 23:09:49 +00002467 case tok::kw___is_arithmetic: return UTT_IsArithmetic;
2468 case tok::kw___is_array: return UTT_IsArray;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002469 case tok::kw___is_class: return UTT_IsClass;
John Wiegley65497cc2011-04-27 23:09:49 +00002470 case tok::kw___is_complete_type: return UTT_IsCompleteType;
2471 case tok::kw___is_compound: return UTT_IsCompound;
2472 case tok::kw___is_const: return UTT_IsConst;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002473 case tok::kw___is_empty: return UTT_IsEmpty;
2474 case tok::kw___is_enum: return UTT_IsEnum;
Douglas Gregordca70af2011-12-03 18:14:24 +00002475 case tok::kw___is_final: return UTT_IsFinal;
John Wiegley65497cc2011-04-27 23:09:49 +00002476 case tok::kw___is_floating_point: return UTT_IsFloatingPoint;
2477 case tok::kw___is_function: return UTT_IsFunction;
2478 case tok::kw___is_fundamental: return UTT_IsFundamental;
2479 case tok::kw___is_integral: return UTT_IsIntegral;
John Wiegley65497cc2011-04-27 23:09:49 +00002480 case tok::kw___is_lvalue_reference: return UTT_IsLvalueReference;
2481 case tok::kw___is_member_function_pointer: return UTT_IsMemberFunctionPointer;
2482 case tok::kw___is_member_object_pointer: return UTT_IsMemberObjectPointer;
2483 case tok::kw___is_member_pointer: return UTT_IsMemberPointer;
2484 case tok::kw___is_object: return UTT_IsObject;
Chandler Carruth79803482011-04-23 10:47:20 +00002485 case tok::kw___is_literal: return UTT_IsLiteral;
Chandler Carruth65fa1fd2011-04-24 02:49:28 +00002486 case tok::kw___is_literal_type: return UTT_IsLiteral;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002487 case tok::kw___is_pod: return UTT_IsPOD;
John Wiegley65497cc2011-04-27 23:09:49 +00002488 case tok::kw___is_pointer: return UTT_IsPointer;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002489 case tok::kw___is_polymorphic: return UTT_IsPolymorphic;
John Wiegley65497cc2011-04-27 23:09:49 +00002490 case tok::kw___is_reference: return UTT_IsReference;
John Wiegley65497cc2011-04-27 23:09:49 +00002491 case tok::kw___is_rvalue_reference: return UTT_IsRvalueReference;
2492 case tok::kw___is_scalar: return UTT_IsScalar;
2493 case tok::kw___is_signed: return UTT_IsSigned;
2494 case tok::kw___is_standard_layout: return UTT_IsStandardLayout;
2495 case tok::kw___is_trivial: return UTT_IsTrivial;
Alexis Huntd9a5cc12011-05-13 00:31:07 +00002496 case tok::kw___is_trivially_copyable: return UTT_IsTriviallyCopyable;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002497 case tok::kw___is_union: return UTT_IsUnion;
John Wiegley65497cc2011-04-27 23:09:49 +00002498 case tok::kw___is_unsigned: return UTT_IsUnsigned;
2499 case tok::kw___is_void: return UTT_IsVoid;
2500 case tok::kw___is_volatile: return UTT_IsVolatile;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002501 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002502}
2503
2504static BinaryTypeTrait BinaryTypeTraitFromTokKind(tok::TokenKind kind) {
2505 switch(kind) {
Francois Pichet347c4c72010-12-07 00:55:57 +00002506 default: llvm_unreachable("Not a known binary type trait");
Francois Pichet34b21132010-12-08 22:35:30 +00002507 case tok::kw___is_base_of: return BTT_IsBaseOf;
John Wiegley65497cc2011-04-27 23:09:49 +00002508 case tok::kw___is_convertible: return BTT_IsConvertible;
2509 case tok::kw___is_same: return BTT_IsSame;
Francois Pichet34b21132010-12-08 22:35:30 +00002510 case tok::kw___builtin_types_compatible_p: return BTT_TypeCompatible;
Douglas Gregor8006e762011-01-27 20:28:01 +00002511 case tok::kw___is_convertible_to: return BTT_IsConvertibleTo;
Douglas Gregor1be329d2012-02-23 07:33:15 +00002512 case tok::kw___is_trivially_assignable: return BTT_IsTriviallyAssignable;
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002513 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002514}
2515
Douglas Gregor29c42f22012-02-24 07:38:34 +00002516static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2517 switch (kind) {
2518 default: llvm_unreachable("Not a known type trait");
2519 case tok::kw___is_trivially_constructible:
2520 return TT_IsTriviallyConstructible;
2521 }
2522}
2523
John Wiegley6242b6a2011-04-28 00:16:57 +00002524static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2525 switch(kind) {
2526 default: llvm_unreachable("Not a known binary type trait");
2527 case tok::kw___array_rank: return ATT_ArrayRank;
2528 case tok::kw___array_extent: return ATT_ArrayExtent;
2529 }
2530}
2531
John Wiegleyf9f65842011-04-25 06:54:41 +00002532static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2533 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002534 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegleyf9f65842011-04-25 06:54:41 +00002535 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2536 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2537 }
2538}
2539
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002540/// ParseUnaryTypeTrait - Parse the built-in unary type-trait
2541/// pseudo-functions that allow implementation of the TR1/C++0x type traits
2542/// templates.
2543///
2544/// primary-expression:
2545/// [GNU] unary-type-trait '(' type-id ')'
2546///
John McCalldadc5752010-08-24 06:29:42 +00002547ExprResult Parser::ParseUnaryTypeTrait() {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002548 UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind());
2549 SourceLocation Loc = ConsumeToken();
2550
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002551 BalancedDelimiterTracker T(*this, tok::l_paren);
2552 if (T.expectAndConsume(diag::err_expected_lparen))
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002553 return ExprError();
2554
2555 // FIXME: Error reporting absolutely sucks! If the this fails to parse a type
2556 // there will be cryptic errors about mismatched parentheses and missing
2557 // specifiers.
Douglas Gregor220cac52009-02-18 17:45:20 +00002558 TypeResult Ty = ParseTypeName();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002559
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002560 T.consumeClose();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002561
Douglas Gregor220cac52009-02-18 17:45:20 +00002562 if (Ty.isInvalid())
2563 return ExprError();
2564
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002565 return Actions.ActOnUnaryTypeTrait(UTT, Loc, Ty.get(), T.getCloseLocation());
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002566}
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002567
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002568/// ParseBinaryTypeTrait - Parse the built-in binary type-trait
2569/// pseudo-functions that allow implementation of the TR1/C++0x type traits
2570/// templates.
2571///
2572/// primary-expression:
2573/// [GNU] binary-type-trait '(' type-id ',' type-id ')'
2574///
2575ExprResult Parser::ParseBinaryTypeTrait() {
2576 BinaryTypeTrait BTT = BinaryTypeTraitFromTokKind(Tok.getKind());
2577 SourceLocation Loc = ConsumeToken();
2578
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002579 BalancedDelimiterTracker T(*this, tok::l_paren);
2580 if (T.expectAndConsume(diag::err_expected_lparen))
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002581 return ExprError();
2582
2583 TypeResult LhsTy = ParseTypeName();
2584 if (LhsTy.isInvalid()) {
2585 SkipUntil(tok::r_paren);
2586 return ExprError();
2587 }
2588
2589 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2590 SkipUntil(tok::r_paren);
2591 return ExprError();
2592 }
2593
2594 TypeResult RhsTy = ParseTypeName();
2595 if (RhsTy.isInvalid()) {
2596 SkipUntil(tok::r_paren);
2597 return ExprError();
2598 }
2599
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002600 T.consumeClose();
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002601
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002602 return Actions.ActOnBinaryTypeTrait(BTT, Loc, LhsTy.get(), RhsTy.get(),
2603 T.getCloseLocation());
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002604}
2605
Douglas Gregor29c42f22012-02-24 07:38:34 +00002606/// \brief Parse the built-in type-trait pseudo-functions that allow
2607/// implementation of the TR1/C++11 type traits templates.
2608///
2609/// primary-expression:
2610/// type-trait '(' type-id-seq ')'
2611///
2612/// type-id-seq:
2613/// type-id ...[opt] type-id-seq[opt]
2614///
2615ExprResult Parser::ParseTypeTrait() {
2616 TypeTrait Kind = TypeTraitFromTokKind(Tok.getKind());
2617 SourceLocation Loc = ConsumeToken();
2618
2619 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2620 if (Parens.expectAndConsume(diag::err_expected_lparen))
2621 return ExprError();
2622
2623 llvm::SmallVector<ParsedType, 2> Args;
2624 do {
2625 // Parse the next type.
2626 TypeResult Ty = ParseTypeName();
2627 if (Ty.isInvalid()) {
2628 Parens.skipToEnd();
2629 return ExprError();
2630 }
2631
2632 // Parse the ellipsis, if present.
2633 if (Tok.is(tok::ellipsis)) {
2634 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2635 if (Ty.isInvalid()) {
2636 Parens.skipToEnd();
2637 return ExprError();
2638 }
2639 }
2640
2641 // Add this type to the list of arguments.
2642 Args.push_back(Ty.get());
2643
2644 if (Tok.is(tok::comma)) {
2645 ConsumeToken();
2646 continue;
2647 }
2648
2649 break;
2650 } while (true);
2651
2652 if (Parens.consumeClose())
2653 return ExprError();
2654
2655 return Actions.ActOnTypeTrait(Kind, Loc, Args, Parens.getCloseLocation());
2656}
2657
John Wiegley6242b6a2011-04-28 00:16:57 +00002658/// ParseArrayTypeTrait - Parse the built-in array type-trait
2659/// pseudo-functions.
2660///
2661/// primary-expression:
2662/// [Embarcadero] '__array_rank' '(' type-id ')'
2663/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2664///
2665ExprResult Parser::ParseArrayTypeTrait() {
2666 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2667 SourceLocation Loc = ConsumeToken();
2668
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002669 BalancedDelimiterTracker T(*this, tok::l_paren);
2670 if (T.expectAndConsume(diag::err_expected_lparen))
John Wiegley6242b6a2011-04-28 00:16:57 +00002671 return ExprError();
2672
2673 TypeResult Ty = ParseTypeName();
2674 if (Ty.isInvalid()) {
2675 SkipUntil(tok::comma);
2676 SkipUntil(tok::r_paren);
2677 return ExprError();
2678 }
2679
2680 switch (ATT) {
2681 case ATT_ArrayRank: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002682 T.consumeClose();
2683 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), NULL,
2684 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00002685 }
2686 case ATT_ArrayExtent: {
2687 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2688 SkipUntil(tok::r_paren);
2689 return ExprError();
2690 }
2691
2692 ExprResult DimExpr = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002693 T.consumeClose();
John Wiegley6242b6a2011-04-28 00:16:57 +00002694
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002695 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2696 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00002697 }
John Wiegley6242b6a2011-04-28 00:16:57 +00002698 }
David Blaikiee4d798f2012-01-20 21:50:17 +00002699 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley6242b6a2011-04-28 00:16:57 +00002700}
2701
John Wiegleyf9f65842011-04-25 06:54:41 +00002702/// ParseExpressionTrait - Parse built-in expression-trait
2703/// pseudo-functions like __is_lvalue_expr( xxx ).
2704///
2705/// primary-expression:
2706/// [Embarcadero] expression-trait '(' expression ')'
2707///
2708ExprResult Parser::ParseExpressionTrait() {
2709 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2710 SourceLocation Loc = ConsumeToken();
2711
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002712 BalancedDelimiterTracker T(*this, tok::l_paren);
2713 if (T.expectAndConsume(diag::err_expected_lparen))
John Wiegleyf9f65842011-04-25 06:54:41 +00002714 return ExprError();
2715
2716 ExprResult Expr = ParseExpression();
2717
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002718 T.consumeClose();
John Wiegleyf9f65842011-04-25 06:54:41 +00002719
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002720 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2721 T.getCloseLocation());
John Wiegleyf9f65842011-04-25 06:54:41 +00002722}
2723
2724
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002725/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2726/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2727/// based on the context past the parens.
John McCalldadc5752010-08-24 06:29:42 +00002728ExprResult
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002729Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallba7bf592010-08-24 05:47:05 +00002730 ParsedType &CastTy,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002731 BalancedDelimiterTracker &Tracker) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002732 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002733 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2734 assert(isTypeIdInParens() && "Not a type-id!");
2735
John McCalldadc5752010-08-24 06:29:42 +00002736 ExprResult Result(true);
John McCallba7bf592010-08-24 05:47:05 +00002737 CastTy = ParsedType();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002738
2739 // We need to disambiguate a very ugly part of the C++ syntax:
2740 //
2741 // (T())x; - type-id
2742 // (T())*x; - type-id
2743 // (T())/x; - expression
2744 // (T()); - expression
2745 //
2746 // The bad news is that we cannot use the specialized tentative parser, since
2747 // it can only verify that the thing inside the parens can be parsed as
2748 // type-id, it is not useful for determining the context past the parens.
2749 //
2750 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidis24ad6922009-05-22 15:12:46 +00002751 // making any unnecessary Action calls.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002752 //
2753 // It uses a scheme similar to parsing inline methods. The parenthesized
2754 // tokens are cached, the context that follows is determined (possibly by
2755 // parsing a cast-expression), and then we re-introduce the cached tokens
2756 // into the token stream and parse them appropriately.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002757
Mike Stump11289f42009-09-09 15:08:12 +00002758 ParenParseOption ParseAs;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002759 CachedTokens Toks;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002760
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002761 // Store the tokens of the parentheses. We will parse them after we determine
2762 // the context that follows them.
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +00002763 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002764 // We didn't find the ')' we expected.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002765 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002766 return ExprError();
2767 }
2768
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002769 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002770 ParseAs = CompoundLiteral;
2771 } else {
2772 bool NotCastExpr;
Eli Friedmancf7530f2009-05-25 19:41:42 +00002773 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
2774 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
2775 NotCastExpr = true;
2776 } else {
2777 // Try parsing the cast-expression that may follow.
2778 // If it is not a cast-expression, NotCastExpr will be true and no token
2779 // will be consumed.
2780 Result = ParseCastExpression(false/*isUnaryExpression*/,
2781 false/*isAddressofOperand*/,
John McCallba7bf592010-08-24 05:47:05 +00002782 NotCastExpr,
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00002783 // type-id has priority.
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00002784 IsTypeCast);
Eli Friedmancf7530f2009-05-25 19:41:42 +00002785 }
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002786
2787 // If we parsed a cast-expression, it's really a type-id, otherwise it's
2788 // an expression.
2789 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002790 }
2791
Mike Stump11289f42009-09-09 15:08:12 +00002792 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002793 Toks.push_back(Tok);
2794 // Re-enter the stored parenthesized tokens into the token stream, so we may
2795 // parse them now.
2796 PP.EnterTokenStream(Toks.data(), Toks.size(),
2797 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
2798 // Drop the current token and bring the first cached one. It's the same token
2799 // as when we entered this function.
2800 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002801
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002802 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00002803 // Parse the type declarator.
2804 DeclSpec DS(AttrFactory);
2805 ParseSpecifierQualifierList(DS);
2806 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2807 ParseDeclarator(DeclaratorInfo);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002808
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002809 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002810 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002811
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002812 if (ParseAs == CompoundLiteral) {
2813 ExprType = CompoundLiteral;
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00002814 TypeResult Ty = ParseTypeName();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002815 return ParseCompoundLiteralExpression(Ty.get(),
2816 Tracker.getOpenLocation(),
2817 Tracker.getCloseLocation());
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002818 }
Mike Stump11289f42009-09-09 15:08:12 +00002819
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002820 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
2821 assert(ParseAs == CastExpr);
2822
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00002823 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002824 return ExprError();
2825
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002826 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002827 if (!Result.isInvalid())
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002828 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
2829 DeclaratorInfo, CastTy,
2830 Tracker.getCloseLocation(), Result.take());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002831 return move(Result);
2832 }
Mike Stump11289f42009-09-09 15:08:12 +00002833
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002834 // Not a compound literal, and not followed by a cast-expression.
2835 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002836
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002837 ExprType = SimpleExpr;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002838 Result = ParseExpression();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002839 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002840 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
2841 Tok.getLocation(), Result.take());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002842
2843 // Match the ')'.
2844 if (Result.isInvalid()) {
2845 SkipUntil(tok::r_paren);
2846 return ExprError();
2847 }
Mike Stump11289f42009-09-09 15:08:12 +00002848
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002849 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002850 return move(Result);
2851}