blob: c029c584ecb3219d679d86f868a457cee4527238 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expression parsing implementation for C++.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner500d3292009-01-29 05:15:15 +000014#include "clang/Parse/ParseDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "clang/Parse/Parser.h"
Douglas Gregorbc61bd82011-01-11 00:33:19 +000016#include "RAIIObjectsForParser.h"
John McCall19510852010-08-20 18:27:03 +000017#include "clang/Sema/DeclSpec.h"
Douglas Gregorae7902c2011-08-04 15:30:47 +000018#include "clang/Sema/Scope.h"
John McCall19510852010-08-20 18:27:03 +000019#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor3f9a0562009-11-03 01:35:08 +000020#include "llvm/Support/ErrorHandling.h"
21
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23
Richard Smithea698b32011-04-14 21:45:45 +000024static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
25 switch (Kind) {
26 case tok::kw_template: return 0;
27 case tok::kw_const_cast: return 1;
28 case tok::kw_dynamic_cast: return 2;
29 case tok::kw_reinterpret_cast: return 3;
30 case tok::kw_static_cast: return 4;
31 default:
David Blaikieb219cfc2011-09-23 05:06:16 +000032 llvm_unreachable("Unknown type for digraph error message.");
Richard Smithea698b32011-04-14 21:45:45 +000033 }
34}
35
36// Are the two tokens adjacent in the same source file?
37static bool AreTokensAdjacent(Preprocessor &PP, Token &First, Token &Second) {
38 SourceManager &SM = PP.getSourceManager();
39 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +000040 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
Richard Smithea698b32011-04-14 21:45:45 +000041 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
42}
43
44// Suggest fixit for "<::" after a cast.
45static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
46 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
47 // Pull '<:' and ':' off token stream.
48 if (!AtDigraph)
49 PP.Lex(DigraphToken);
50 PP.Lex(ColonToken);
51
52 SourceRange Range;
53 Range.setBegin(DigraphToken.getLocation());
54 Range.setEnd(ColonToken.getLocation());
55 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
56 << SelectDigraphErrorMessage(Kind)
57 << FixItHint::CreateReplacement(Range, "< ::");
58
59 // Update token information to reflect their change in token type.
60 ColonToken.setKind(tok::coloncolon);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +000061 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
Richard Smithea698b32011-04-14 21:45:45 +000062 ColonToken.setLength(2);
63 DigraphToken.setKind(tok::less);
64 DigraphToken.setLength(1);
65
66 // Push new tokens back to token stream.
67 PP.EnterToken(ColonToken);
68 if (!AtDigraph)
69 PP.EnterToken(DigraphToken);
70}
71
Richard Trieu950be712011-09-19 19:01:00 +000072// Check for '<::' which should be '< ::' instead of '[:' when following
73// a template name.
74void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
75 bool EnteringContext,
76 IdentifierInfo &II, CXXScopeSpec &SS) {
Richard Trieuc11030e2011-09-20 20:03:50 +000077 if (!Next.is(tok::l_square) || Next.getLength() != 2)
Richard Trieu950be712011-09-19 19:01:00 +000078 return;
79
80 Token SecondToken = GetLookAheadToken(2);
81 if (!SecondToken.is(tok::colon) || !AreTokensAdjacent(PP, Next, SecondToken))
82 return;
83
84 TemplateTy Template;
85 UnqualifiedId TemplateName;
86 TemplateName.setIdentifier(&II, Tok.getLocation());
87 bool MemberOfUnknownSpecialization;
88 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
89 TemplateName, ObjectType, EnteringContext,
90 Template, MemberOfUnknownSpecialization))
91 return;
92
93 FixDigraph(*this, PP, Next, SecondToken, tok::kw_template,
94 /*AtDigraph*/false);
95}
96
Mike Stump1eb44332009-09-09 15:08:12 +000097/// \brief Parse global scope or nested-name-specifier if present.
Douglas Gregor2dd078a2009-09-02 22:59:36 +000098///
99/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
Mike Stump1eb44332009-09-09 15:08:12 +0000100/// may be preceded by '::'). Note that this routine will not parse ::new or
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000101/// ::delete; it will just leave them in the token stream.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000102///
103/// '::'[opt] nested-name-specifier
104/// '::'
105///
106/// nested-name-specifier:
107/// type-name '::'
108/// namespace-name '::'
109/// nested-name-specifier identifier '::'
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000110/// nested-name-specifier 'template'[opt] simple-template-id '::'
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000111///
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000112///
Mike Stump1eb44332009-09-09 15:08:12 +0000113/// \param SS the scope specifier that will be set to the parsed
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000114/// nested-name-specifier (or empty)
115///
Mike Stump1eb44332009-09-09 15:08:12 +0000116/// \param ObjectType if this nested-name-specifier is being parsed following
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000117/// the "." or "->" of a member access expression, this parameter provides the
118/// type of the object whose members are being accessed.
119///
120/// \param EnteringContext whether we will be entering into the context of
121/// the nested-name-specifier after parsing it.
122///
Douglas Gregord4dca082010-02-24 18:44:31 +0000123/// \param MayBePseudoDestructor When non-NULL, points to a flag that
124/// indicates whether this nested-name-specifier may be part of a
125/// pseudo-destructor name. In this case, the flag will be set false
126/// if we don't actually end up parsing a destructor name. Moreorover,
127/// if we do end up determining that we are parsing a destructor name,
128/// the last component of the nested-name-specifier is not parsed as
129/// part of the scope specifier.
130
Douglas Gregorb10cd042010-02-21 18:36:56 +0000131/// member access expression, e.g., the \p T:: in \p p->T::m.
132///
John McCall9ba61662010-02-26 08:45:28 +0000133/// \returns true if there was an error parsing a scope specifier
Douglas Gregor495c35d2009-08-25 22:51:20 +0000134bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
John McCallb3d87482010-08-24 05:47:05 +0000135 ParsedType ObjectType,
Douglas Gregorb10cd042010-02-21 18:36:56 +0000136 bool EnteringContext,
Francois Pichet4147d302011-03-27 19:41:34 +0000137 bool *MayBePseudoDestructor,
138 bool IsTypename) {
Argyrios Kyrtzidis4bdd91c2008-11-26 21:41:52 +0000139 assert(getLang().CPlusPlus &&
Chris Lattner7452c6f2009-01-05 01:24:05 +0000140 "Call sites of this function should be guarded by checking for C++");
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000142 if (Tok.is(tok::annot_cxxscope)) {
Douglas Gregorc34348a2011-02-24 17:54:50 +0000143 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
144 Tok.getAnnotationRange(),
145 SS);
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000146 ConsumeToken();
John McCall9ba61662010-02-26 08:45:28 +0000147 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000148 }
Chris Lattnere607e802009-01-04 21:14:15 +0000149
Douglas Gregor39a8de12009-02-25 19:37:18 +0000150 bool HasScopeSpecifier = false;
151
Chris Lattner5b454732009-01-05 03:55:46 +0000152 if (Tok.is(tok::coloncolon)) {
153 // ::new and ::delete aren't nested-name-specifiers.
154 tok::TokenKind NextKind = NextToken().getKind();
155 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
156 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Chris Lattner55a7cef2009-01-05 00:13:00 +0000158 // '::' - Global scope qualifier.
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000159 if (Actions.ActOnCXXGlobalScopeSpecifier(getCurScope(), ConsumeToken(), SS))
160 return true;
161
Douglas Gregor39a8de12009-02-25 19:37:18 +0000162 HasScopeSpecifier = true;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000163 }
164
Douglas Gregord4dca082010-02-24 18:44:31 +0000165 bool CheckForDestructor = false;
166 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
167 CheckForDestructor = true;
168 *MayBePseudoDestructor = false;
169 }
170
Douglas Gregor39a8de12009-02-25 19:37:18 +0000171 while (true) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000172 if (HasScopeSpecifier) {
173 // C++ [basic.lookup.classref]p5:
174 // If the qualified-id has the form
Douglas Gregor3b6afbb2009-09-09 00:23:06 +0000175 //
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000176 // ::class-name-or-namespace-name::...
Douglas Gregor3b6afbb2009-09-09 00:23:06 +0000177 //
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000178 // the class-name-or-namespace-name is looked up in global scope as a
179 // class-name or namespace-name.
180 //
181 // To implement this, we clear out the object type as soon as we've
182 // seen a leading '::' or part of a nested-name-specifier.
John McCallb3d87482010-08-24 05:47:05 +0000183 ObjectType = ParsedType();
Douglas Gregor81b747b2009-09-17 21:32:03 +0000184
185 if (Tok.is(tok::code_completion)) {
186 // Code completion for a nested-name-specifier, where the code
187 // code completion token follows the '::'.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000188 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
Argyrios Kyrtzidisb6b2b182011-04-23 01:04:12 +0000189 // Include code completion token into the range of the scope otherwise
190 // when we try to annotate the scope tokens the dangling code completion
191 // token will cause assertion in
192 // Preprocessor::AnnotatePreviousCachedTokens.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000193 SS.setEndLoc(Tok.getLocation());
194 cutOffParsing();
195 return true;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000196 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000197 }
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Douglas Gregor39a8de12009-02-25 19:37:18 +0000199 // nested-name-specifier:
Chris Lattner77cf72a2009-06-26 03:47:46 +0000200 // nested-name-specifier 'template'[opt] simple-template-id '::'
201
202 // Parse the optional 'template' keyword, then make sure we have
203 // 'identifier <' after it.
204 if (Tok.is(tok::kw_template)) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000205 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedmaneab975d2009-08-29 04:08:08 +0000206 // nested-name-specifier, since they aren't allowed to start with
207 // 'template'.
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000208 if (!HasScopeSpecifier && !ObjectType)
Eli Friedmaneab975d2009-08-29 04:08:08 +0000209 break;
210
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000211 TentativeParsingAction TPA(*this);
Chris Lattner77cf72a2009-06-26 03:47:46 +0000212 SourceLocation TemplateKWLoc = ConsumeToken();
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000213
214 UnqualifiedId TemplateName;
215 if (Tok.is(tok::identifier)) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000216 // Consume the identifier.
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000217 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000218 ConsumeToken();
219 } else if (Tok.is(tok::kw_operator)) {
220 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000221 TemplateName)) {
222 TPA.Commit();
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000223 break;
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000224 }
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000225
Sean Hunte6252d12009-11-28 08:58:14 +0000226 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
227 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000228 Diag(TemplateName.getSourceRange().getBegin(),
229 diag::err_id_after_template_in_nested_name_spec)
230 << TemplateName.getSourceRange();
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000231 TPA.Commit();
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000232 break;
233 }
234 } else {
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000235 TPA.Revert();
Chris Lattner77cf72a2009-06-26 03:47:46 +0000236 break;
237 }
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000239 // If the next token is not '<', we have a qualified-id that refers
240 // to a template name, such as T::template apply, but is not a
241 // template-id.
242 if (Tok.isNot(tok::less)) {
243 TPA.Revert();
244 break;
245 }
246
247 // Commit to parsing the template-id.
248 TPA.Commit();
Douglas Gregord6ab2322010-06-16 23:00:59 +0000249 TemplateTy Template;
Douglas Gregor23c94db2010-07-02 17:43:08 +0000250 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(getCurScope(),
Douglas Gregord6ab2322010-06-16 23:00:59 +0000251 TemplateKWLoc,
252 SS,
253 TemplateName,
254 ObjectType,
255 EnteringContext,
256 Template)) {
Douglas Gregor059101f2011-03-02 00:47:37 +0000257 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName,
Douglas Gregord6ab2322010-06-16 23:00:59 +0000258 TemplateKWLoc, false))
259 return true;
260 } else
John McCall9ba61662010-02-26 08:45:28 +0000261 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000262
Chris Lattner77cf72a2009-06-26 03:47:46 +0000263 continue;
264 }
Mike Stump1eb44332009-09-09 15:08:12 +0000265
Douglas Gregor39a8de12009-02-25 19:37:18 +0000266 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000267 // We have
Douglas Gregor39a8de12009-02-25 19:37:18 +0000268 //
269 // simple-template-id '::'
270 //
271 // So we need to check whether the simple-template-id is of the
Douglas Gregorc45c2322009-03-31 00:43:58 +0000272 // right kind (it should name a type or be dependent), and then
273 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +0000274 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregord4dca082010-02-24 18:44:31 +0000275 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
276 *MayBePseudoDestructor = true;
John McCall9ba61662010-02-26 08:45:28 +0000277 return false;
Douglas Gregord4dca082010-02-24 18:44:31 +0000278 }
279
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000280 // Consume the template-id token.
281 ConsumeToken();
282
283 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
284 SourceLocation CCLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000286 if (!HasScopeSpecifier)
287 HasScopeSpecifier = true;
288
289 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
290 TemplateId->getTemplateArgs(),
291 TemplateId->NumArgs);
292
293 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
294 /*FIXME:*/SourceLocation(),
295 SS,
296 TemplateId->Template,
297 TemplateId->TemplateNameLoc,
298 TemplateId->LAngleLoc,
299 TemplateArgsPtr,
300 TemplateId->RAngleLoc,
301 CCLoc,
302 EnteringContext)) {
303 SourceLocation StartLoc
304 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
305 : TemplateId->TemplateNameLoc;
306 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner67b9e832009-06-26 03:45:46 +0000307 }
Argyrios Kyrtzidiseccce7e2011-05-03 18:45:38 +0000308
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000309 continue;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000310 }
311
Chris Lattner5c7f7862009-06-26 03:52:38 +0000312
313 // The rest of the nested-name-specifier possibilities start with
314 // tok::identifier.
315 if (Tok.isNot(tok::identifier))
316 break;
317
318 IdentifierInfo &II = *Tok.getIdentifierInfo();
319
320 // nested-name-specifier:
321 // type-name '::'
322 // namespace-name '::'
323 // nested-name-specifier identifier '::'
324 Token Next = NextToken();
Chris Lattner46646492009-12-07 01:36:53 +0000325
326 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
327 // and emit a fixit hint for it.
Douglas Gregorb10cd042010-02-21 18:36:56 +0000328 if (Next.is(tok::colon) && !ColonIsSacred) {
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000329 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
330 Tok.getLocation(),
331 Next.getLocation(), ObjectType,
Douglas Gregorb10cd042010-02-21 18:36:56 +0000332 EnteringContext) &&
333 // If the token after the colon isn't an identifier, it's still an
334 // error, but they probably meant something else strange so don't
335 // recover like this.
336 PP.LookAhead(1).is(tok::identifier)) {
337 Diag(Next, diag::err_unexected_colon_in_nested_name_spec)
Douglas Gregor849b2432010-03-31 17:46:05 +0000338 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregorb10cd042010-02-21 18:36:56 +0000339
340 // Recover as if the user wrote '::'.
341 Next.setKind(tok::coloncolon);
342 }
Chris Lattner46646492009-12-07 01:36:53 +0000343 }
344
Chris Lattner5c7f7862009-06-26 03:52:38 +0000345 if (Next.is(tok::coloncolon)) {
Douglas Gregor77549082010-02-24 21:29:12 +0000346 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Douglas Gregor23c94db2010-07-02 17:43:08 +0000347 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(),
Douglas Gregor77549082010-02-24 21:29:12 +0000348 II, ObjectType)) {
Douglas Gregord4dca082010-02-24 18:44:31 +0000349 *MayBePseudoDestructor = true;
John McCall9ba61662010-02-26 08:45:28 +0000350 return false;
Douglas Gregord4dca082010-02-24 18:44:31 +0000351 }
352
Chris Lattner5c7f7862009-06-26 03:52:38 +0000353 // We have an identifier followed by a '::'. Lookup this name
354 // as the name in a nested-name-specifier.
355 SourceLocation IdLoc = ConsumeToken();
Chris Lattner46646492009-12-07 01:36:53 +0000356 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
357 "NextToken() not working properly!");
Chris Lattner5c7f7862009-06-26 03:52:38 +0000358 SourceLocation CCLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000360 HasScopeSpecifier = true;
361 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
362 ObjectType, EnteringContext, SS))
363 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
364
Chris Lattner5c7f7862009-06-26 03:52:38 +0000365 continue;
366 }
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Richard Trieu950be712011-09-19 19:01:00 +0000368 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smithea698b32011-04-14 21:45:45 +0000369
Chris Lattner5c7f7862009-06-26 03:52:38 +0000370 // nested-name-specifier:
371 // type-name '<'
372 if (Next.is(tok::less)) {
373 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000374 UnqualifiedId TemplateName;
375 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000376 bool MemberOfUnknownSpecialization;
Douglas Gregor23c94db2010-07-02 17:43:08 +0000377 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c153532010-08-06 12:11:11 +0000378 /*hasTemplateKeyword=*/false,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000379 TemplateName,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000380 ObjectType,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000381 EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000382 Template,
383 MemberOfUnknownSpecialization)) {
Chris Lattner5c7f7862009-06-26 03:52:38 +0000384 // We have found a template name, so annotate this this token
385 // with a template-id annotation. We do not permit the
386 // template-id to be translated into a type annotation,
387 // because some clients (e.g., the parsing of class template
388 // specializations) still want to see the original template-id
389 // token.
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000390 ConsumeToken();
Douglas Gregor059101f2011-03-02 00:47:37 +0000391 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName,
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000392 SourceLocation(), false))
John McCall9ba61662010-02-26 08:45:28 +0000393 return true;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000394 continue;
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000395 }
396
397 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4147d302011-03-27 19:41:34 +0000398 (IsTypename || IsTemplateArgumentList(1))) {
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000399 // We have something like t::getAs<T>, where getAs is a
400 // member of an unknown specialization. However, this will only
401 // parse correctly as a template, so suggest the keyword 'template'
402 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4147d302011-03-27 19:41:34 +0000403 unsigned DiagID = diag::err_missing_dependent_template_keyword;
Francois Pichet62ec1f22011-09-17 17:15:52 +0000404 if (getLang().MicrosoftExt)
Francois Pichetcf320c62011-04-22 08:25:24 +0000405 DiagID = diag::warn_missing_dependent_template_keyword;
Francois Pichet4147d302011-03-27 19:41:34 +0000406
407 Diag(Tok.getLocation(), DiagID)
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000408 << II.getName()
409 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
410
Douglas Gregord6ab2322010-06-16 23:00:59 +0000411 if (TemplateNameKind TNK
Douglas Gregor23c94db2010-07-02 17:43:08 +0000412 = Actions.ActOnDependentTemplateName(getCurScope(),
Douglas Gregord6ab2322010-06-16 23:00:59 +0000413 Tok.getLocation(), SS,
414 TemplateName, ObjectType,
415 EnteringContext, Template)) {
416 // Consume the identifier.
417 ConsumeToken();
Douglas Gregor059101f2011-03-02 00:47:37 +0000418 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName,
Douglas Gregord6ab2322010-06-16 23:00:59 +0000419 SourceLocation(), false))
420 return true;
421 }
422 else
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000423 return true;
Douglas Gregord6ab2322010-06-16 23:00:59 +0000424
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000425 continue;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000426 }
427 }
428
Douglas Gregor39a8de12009-02-25 19:37:18 +0000429 // We don't have any tokens that form the beginning of a
430 // nested-name-specifier, so we're done.
431 break;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000432 }
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Douglas Gregord4dca082010-02-24 18:44:31 +0000434 // Even if we didn't see any pieces of a nested-name-specifier, we
435 // still check whether there is a tilde in this position, which
436 // indicates a potential pseudo-destructor.
437 if (CheckForDestructor && Tok.is(tok::tilde))
438 *MayBePseudoDestructor = true;
439
John McCall9ba61662010-02-26 08:45:28 +0000440 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000441}
442
443/// ParseCXXIdExpression - Handle id-expression.
444///
445/// id-expression:
446/// unqualified-id
447/// qualified-id
448///
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000449/// qualified-id:
450/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
451/// '::' identifier
452/// '::' operator-function-id
Douglas Gregoredce4dd2009-06-30 22:34:41 +0000453/// '::' template-id
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000454///
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000455/// NOTE: The standard specifies that, for qualified-id, the parser does not
456/// expect:
457///
458/// '::' conversion-function-id
459/// '::' '~' class-name
460///
461/// This may cause a slight inconsistency on diagnostics:
462///
463/// class C {};
464/// namespace A {}
465/// void f() {
466/// :: A :: ~ C(); // Some Sema error about using destructor with a
467/// // namespace.
468/// :: ~ C(); // Some Parser error like 'unexpected ~'.
469/// }
470///
471/// We simplify the parser a bit and make it work like:
472///
473/// qualified-id:
474/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
475/// '::' unqualified-id
476///
477/// That way Sema can handle and report similar errors for namespaces and the
478/// global scope.
479///
Sebastian Redlebc07d52009-02-03 20:19:35 +0000480/// The isAddressOfOperand parameter indicates that this id-expression is a
481/// direct operand of the address-of operator. This is, besides member contexts,
482/// the only place where a qualified-id naming a non-static class member may
483/// appear.
484///
John McCall60d7b3a2010-08-24 06:29:42 +0000485ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000486 // qualified-id:
487 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
488 // '::' unqualified-id
489 //
490 CXXScopeSpec SS;
John McCallb3d87482010-08-24 05:47:05 +0000491 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000492
493 UnqualifiedId Name;
494 if (ParseUnqualifiedId(SS,
495 /*EnteringContext=*/false,
496 /*AllowDestructorName=*/false,
497 /*AllowConstructorName=*/false,
John McCallb3d87482010-08-24 05:47:05 +0000498 /*ObjectType=*/ ParsedType(),
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000499 Name))
500 return ExprError();
John McCallb681b612009-11-22 02:49:43 +0000501
502 // This is only the direct operand of an & operator if it is not
503 // followed by a postfix-expression suffix.
John McCall9c72c602010-08-27 09:08:28 +0000504 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
505 isAddressOfOperand = false;
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000506
Douglas Gregor23c94db2010-07-02 17:43:08 +0000507 return Actions.ActOnIdExpression(getCurScope(), SS, Name, Tok.is(tok::l_paren),
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000508 isAddressOfOperand);
509
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000510}
511
Douglas Gregorae7902c2011-08-04 15:30:47 +0000512/// ParseLambdaExpression - Parse a C++0x lambda expression.
513///
514/// lambda-expression:
515/// lambda-introducer lambda-declarator[opt] compound-statement
516///
517/// lambda-introducer:
518/// '[' lambda-capture[opt] ']'
519///
520/// lambda-capture:
521/// capture-default
522/// capture-list
523/// capture-default ',' capture-list
524///
525/// capture-default:
526/// '&'
527/// '='
528///
529/// capture-list:
530/// capture
531/// capture-list ',' capture
532///
533/// capture:
534/// identifier
535/// '&' identifier
536/// 'this'
537///
538/// lambda-declarator:
539/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
540/// 'mutable'[opt] exception-specification[opt]
541/// trailing-return-type[opt]
542///
543ExprResult Parser::ParseLambdaExpression() {
544 // Parse lambda-introducer.
545 LambdaIntroducer Intro;
546
547 llvm::Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro));
548 if (DiagID) {
549 Diag(Tok, DiagID.getValue());
550 SkipUntil(tok::r_square);
551 }
552
553 return ParseLambdaExpressionAfterIntroducer(Intro);
554}
555
556/// TryParseLambdaExpression - Use lookahead and potentially tentative
557/// parsing to determine if we are looking at a C++0x lambda expression, and parse
558/// it if we are.
559///
560/// If we are not looking at a lambda expression, returns ExprError().
561ExprResult Parser::TryParseLambdaExpression() {
562 assert(getLang().CPlusPlus0x
563 && Tok.is(tok::l_square)
564 && "Not at the start of a possible lambda expression.");
565
566 const Token Next = NextToken(), After = GetLookAheadToken(2);
567
568 // If lookahead indicates this is a lambda...
569 if (Next.is(tok::r_square) || // []
570 Next.is(tok::equal) || // [=
571 (Next.is(tok::amp) && // [&] or [&,
572 (After.is(tok::r_square) ||
573 After.is(tok::comma))) ||
574 (Next.is(tok::identifier) && // [identifier]
575 After.is(tok::r_square))) {
576 return ParseLambdaExpression();
577 }
578
579 // If lookahead indicates this is an Objective-C message...
580 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
581 return ExprError();
582 }
583
584 LambdaIntroducer Intro;
585 if (TryParseLambdaIntroducer(Intro))
586 return ExprError();
587 return ParseLambdaExpressionAfterIntroducer(Intro);
588}
589
590/// ParseLambdaExpression - Parse a lambda introducer.
591///
592/// Returns a DiagnosticID if it hit something unexpected.
593llvm::Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro) {
594 typedef llvm::Optional<unsigned> DiagResult;
595
596 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
597 Intro.Range.setBegin(ConsumeBracket());
598
599 bool first = true;
600
601 // Parse capture-default.
602 if (Tok.is(tok::amp) &&
603 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
604 Intro.Default = LCD_ByRef;
605 ConsumeToken();
606 first = false;
607 } else if (Tok.is(tok::equal)) {
608 Intro.Default = LCD_ByCopy;
609 ConsumeToken();
610 first = false;
611 }
612
613 while (Tok.isNot(tok::r_square)) {
614 if (!first) {
615 if (Tok.isNot(tok::comma))
616 return DiagResult(diag::err_expected_comma_or_rsquare);
617 ConsumeToken();
618 }
619
620 first = false;
621
622 // Parse capture.
623 LambdaCaptureKind Kind = LCK_ByCopy;
624 SourceLocation Loc;
625 IdentifierInfo* Id = 0;
626
627 if (Tok.is(tok::kw_this)) {
628 Kind = LCK_This;
629 Loc = ConsumeToken();
630 } else {
631 if (Tok.is(tok::amp)) {
632 Kind = LCK_ByRef;
633 ConsumeToken();
634 }
635
636 if (Tok.is(tok::identifier)) {
637 Id = Tok.getIdentifierInfo();
638 Loc = ConsumeToken();
639 } else if (Tok.is(tok::kw_this)) {
640 // FIXME: If we want to suggest a fixit here, will need to return more
641 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
642 // Clear()ed to prevent emission in case of tentative parsing?
643 return DiagResult(diag::err_this_captured_by_reference);
644 } else {
645 return DiagResult(diag::err_expected_capture);
646 }
647 }
648
649 Intro.addCapture(Kind, Loc, Id);
650 }
651
652 Intro.Range.setEnd(MatchRHSPunctuation(tok::r_square,
653 Intro.Range.getBegin()));
654
655 return DiagResult();
656}
657
658/// TryParseLambdaExpression - Tentatively parse a lambda introducer.
659///
660/// Returns true if it hit something unexpected.
661bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
662 TentativeParsingAction PA(*this);
663
664 llvm::Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro));
665
666 if (DiagID) {
667 PA.Revert();
668 return true;
669 }
670
671 PA.Commit();
672 return false;
673}
674
675/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
676/// expression.
677ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
678 LambdaIntroducer &Intro) {
679 // Parse lambda-declarator[opt].
680 DeclSpec DS(AttrFactory);
681 Declarator D(DS, Declarator::PrototypeContext);
682
683 if (Tok.is(tok::l_paren)) {
684 ParseScope PrototypeScope(this,
685 Scope::FunctionPrototypeScope |
686 Scope::DeclScope);
687
688 SourceLocation DeclLoc = ConsumeParen(), DeclEndLoc;
689
690 // Parse parameter-declaration-clause.
691 ParsedAttributes Attr(AttrFactory);
692 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
693 SourceLocation EllipsisLoc;
694
695 if (Tok.isNot(tok::r_paren))
696 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
697
698 DeclEndLoc = MatchRHSPunctuation(tok::r_paren, DeclLoc);
699
700 // Parse 'mutable'[opt].
701 SourceLocation MutableLoc;
702 if (Tok.is(tok::kw_mutable)) {
703 MutableLoc = ConsumeToken();
704 DeclEndLoc = MutableLoc;
705 }
706
707 // Parse exception-specification[opt].
708 ExceptionSpecificationType ESpecType = EST_None;
709 SourceRange ESpecRange;
710 llvm::SmallVector<ParsedType, 2> DynamicExceptions;
711 llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges;
712 ExprResult NoexceptExpr;
713 ESpecType = MaybeParseExceptionSpecification(ESpecRange,
714 DynamicExceptions,
715 DynamicExceptionRanges,
716 NoexceptExpr);
717
718 if (ESpecType != EST_None)
719 DeclEndLoc = ESpecRange.getEnd();
720
721 // Parse attribute-specifier[opt].
722 MaybeParseCXX0XAttributes(Attr, &DeclEndLoc);
723
724 // Parse trailing-return-type[opt].
725 ParsedType TrailingReturnType;
726 if (Tok.is(tok::arrow)) {
727 SourceRange Range;
728 TrailingReturnType = ParseTrailingReturnType(Range).get();
729 if (Range.getEnd().isValid())
730 DeclEndLoc = Range.getEnd();
731 }
732
733 PrototypeScope.Exit();
734
735 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
736 /*isVariadic=*/EllipsisLoc.isValid(),
737 EllipsisLoc,
738 ParamInfo.data(), ParamInfo.size(),
739 DS.getTypeQualifiers(),
740 /*RefQualifierIsLValueRef=*/true,
741 /*RefQualifierLoc=*/SourceLocation(),
742 MutableLoc,
743 ESpecType, ESpecRange.getBegin(),
744 DynamicExceptions.data(),
745 DynamicExceptionRanges.data(),
746 DynamicExceptions.size(),
747 NoexceptExpr.isUsable() ?
748 NoexceptExpr.get() : 0,
749 DeclLoc, DeclEndLoc, D,
750 TrailingReturnType),
751 Attr, DeclEndLoc);
752 }
753
754 // Parse compound-statement.
755 if (Tok.is(tok::l_brace)) {
756 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
757 // it.
758 ParseScope BodyScope(this, Scope::BlockScope | Scope::FnScope |
759 Scope::BreakScope | Scope::ContinueScope |
760 Scope::DeclScope);
761
762 StmtResult Stmt(ParseCompoundStatementBody());
763
764 BodyScope.Exit();
765 } else {
766 Diag(Tok, diag::err_expected_lambda_body);
767 }
768
769 return ExprEmpty();
770}
771
Reid Spencer5f016e22007-07-11 17:01:13 +0000772/// ParseCXXCasts - This handles the various ways to cast expressions to another
773/// type.
774///
775/// postfix-expression: [C++ 5.2p1]
776/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
777/// 'static_cast' '<' type-name '>' '(' expression ')'
778/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
779/// 'const_cast' '<' type-name '>' '(' expression ')'
780///
John McCall60d7b3a2010-08-24 06:29:42 +0000781ExprResult Parser::ParseCXXCasts() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000782 tok::TokenKind Kind = Tok.getKind();
783 const char *CastName = 0; // For error messages
784
785 switch (Kind) {
David Blaikieeb2d1f12011-09-23 20:26:49 +0000786 default: llvm_unreachable("Unknown C++ cast!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 case tok::kw_const_cast: CastName = "const_cast"; break;
788 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
789 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
790 case tok::kw_static_cast: CastName = "static_cast"; break;
791 }
792
793 SourceLocation OpLoc = ConsumeToken();
794 SourceLocation LAngleBracketLoc = Tok.getLocation();
795
Richard Smithea698b32011-04-14 21:45:45 +0000796 // Check for "<::" which is parsed as "[:". If found, fix token stream,
797 // diagnose error, suggest fix, and recover parsing.
798 Token Next = NextToken();
799 if (Tok.is(tok::l_square) && Tok.getLength() == 2 && Next.is(tok::colon) &&
800 AreTokensAdjacent(PP, Tok, Next))
801 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
802
Reid Spencer5f016e22007-07-11 17:01:13 +0000803 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redl20df9b72008-12-11 22:51:44 +0000804 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000805
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000806 // Parse the common declaration-specifiers piece.
807 DeclSpec DS(AttrFactory);
808 ParseSpecifierQualifierList(DS);
809
810 // Parse the abstract-declarator, if present.
811 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
812 ParseDeclarator(DeclaratorInfo);
813
Reid Spencer5f016e22007-07-11 17:01:13 +0000814 SourceLocation RAngleBracketLoc = Tok.getLocation();
815
Chris Lattner1ab3b962008-11-18 07:48:38 +0000816 if (ExpectAndConsume(tok::greater, diag::err_expected_greater))
Sebastian Redl20df9b72008-12-11 22:51:44 +0000817 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<");
Reid Spencer5f016e22007-07-11 17:01:13 +0000818
819 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
820
Argyrios Kyrtzidis21e7ad22009-05-22 10:23:16 +0000821 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, CastName))
822 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000823
John McCall60d7b3a2010-08-24 06:29:42 +0000824 ExprResult Result = ParseExpression();
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Argyrios Kyrtzidis21e7ad22009-05-22 10:23:16 +0000826 // Match the ')'.
Douglas Gregor27591ff2009-11-06 05:48:00 +0000827 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000828
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000829 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregor49badde2008-10-27 19:41:14 +0000830 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000831 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor809070a2009-02-18 17:45:20 +0000832 RAngleBracketLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000833 LParenLoc, Result.take(), RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000834
Sebastian Redl20df9b72008-12-11 22:51:44 +0000835 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000836}
837
Sebastian Redlc42e1182008-11-11 11:37:55 +0000838/// ParseCXXTypeid - This handles the C++ typeid expression.
839///
840/// postfix-expression: [C++ 5.2p1]
841/// 'typeid' '(' expression ')'
842/// 'typeid' '(' type-id ')'
843///
John McCall60d7b3a2010-08-24 06:29:42 +0000844ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc42e1182008-11-11 11:37:55 +0000845 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
846
847 SourceLocation OpLoc = ConsumeToken();
848 SourceLocation LParenLoc = Tok.getLocation();
849 SourceLocation RParenLoc;
850
851 // typeid expressions are always parenthesized.
852 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
853 "typeid"))
Sebastian Redl20df9b72008-12-11 22:51:44 +0000854 return ExprError();
Sebastian Redlc42e1182008-11-11 11:37:55 +0000855
John McCall60d7b3a2010-08-24 06:29:42 +0000856 ExprResult Result;
Sebastian Redlc42e1182008-11-11 11:37:55 +0000857
858 if (isTypeIdInParens()) {
Douglas Gregor809070a2009-02-18 17:45:20 +0000859 TypeResult Ty = ParseTypeName();
Sebastian Redlc42e1182008-11-11 11:37:55 +0000860
861 // Match the ')'.
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000862 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000863
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000864 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redl20df9b72008-12-11 22:51:44 +0000865 return ExprError();
Sebastian Redlc42e1182008-11-11 11:37:55 +0000866
867 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallb3d87482010-08-24 05:47:05 +0000868 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000869 } else {
Douglas Gregore0762c92009-06-19 23:52:42 +0000870 // C++0x [expr.typeid]p3:
Mike Stump1eb44332009-09-09 15:08:12 +0000871 // When typeid is applied to an expression other than an lvalue of a
872 // polymorphic class type [...] The expression is an unevaluated
Douglas Gregore0762c92009-06-19 23:52:42 +0000873 // operand (Clause 5).
874 //
Mike Stump1eb44332009-09-09 15:08:12 +0000875 // Note that we can't tell whether the expression is an lvalue of a
Douglas Gregore0762c92009-06-19 23:52:42 +0000876 // polymorphic class type until after we've parsed the expression, so
Douglas Gregorac7610d2009-06-22 20:57:11 +0000877 // we the expression is potentially potentially evaluated.
878 EnterExpressionEvaluationContext Unevaluated(Actions,
John McCallf312b1e2010-08-26 23:41:50 +0000879 Sema::PotentiallyPotentiallyEvaluated);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000880 Result = ParseExpression();
881
882 // Match the ')'.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000883 if (Result.isInvalid())
Sebastian Redlc42e1182008-11-11 11:37:55 +0000884 SkipUntil(tok::r_paren);
885 else {
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000886 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
887 if (RParenLoc.isInvalid())
888 return ExprError();
Douglas Gregorfadb53b2011-03-12 01:48:56 +0000889
890 // If we are a foo<int> that identifies a single function, resolve it now...
891 Expr* e = Result.get();
892 if (e->getType() == Actions.Context.OverloadTy) {
893 ExprResult er =
894 Actions.ResolveAndFixSingleFunctionTemplateSpecialization(e);
895 if (er.isUsable())
896 Result = er.release();
897 }
Sebastian Redlc42e1182008-11-11 11:37:55 +0000898 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Sebastian Redleffa8d12008-12-10 00:02:53 +0000899 Result.release(), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000900 }
901 }
902
Sebastian Redl20df9b72008-12-11 22:51:44 +0000903 return move(Result);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000904}
905
Francois Pichet01b7c302010-09-08 12:20:18 +0000906/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
907///
908/// '__uuidof' '(' expression ')'
909/// '__uuidof' '(' type-id ')'
910///
911ExprResult Parser::ParseCXXUuidof() {
912 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
913
914 SourceLocation OpLoc = ConsumeToken();
915 SourceLocation LParenLoc = Tok.getLocation();
916 SourceLocation RParenLoc;
917
918 // __uuidof expressions are always parenthesized.
919 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
920 "__uuidof"))
921 return ExprError();
922
923 ExprResult Result;
924
925 if (isTypeIdInParens()) {
926 TypeResult Ty = ParseTypeName();
927
928 // Match the ')'.
929 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
930
931 if (Ty.isInvalid())
932 return ExprError();
933
934 Result = Actions.ActOnCXXUuidof(OpLoc, LParenLoc, /*isType=*/true,
935 Ty.get().getAsOpaquePtr(), RParenLoc);
936 } else {
937 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
938 Result = ParseExpression();
939
940 // Match the ')'.
941 if (Result.isInvalid())
942 SkipUntil(tok::r_paren);
943 else {
944 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
945
946 Result = Actions.ActOnCXXUuidof(OpLoc, LParenLoc, /*isType=*/false,
947 Result.release(), RParenLoc);
948 }
949 }
950
951 return move(Result);
952}
953
Douglas Gregord4dca082010-02-24 18:44:31 +0000954/// \brief Parse a C++ pseudo-destructor expression after the base,
955/// . or -> operator, and nested-name-specifier have already been
956/// parsed.
957///
958/// postfix-expression: [C++ 5.2]
959/// postfix-expression . pseudo-destructor-name
960/// postfix-expression -> pseudo-destructor-name
961///
962/// pseudo-destructor-name:
963/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
964/// ::[opt] nested-name-specifier template simple-template-id ::
965/// ~type-name
966/// ::[opt] nested-name-specifier[opt] ~type-name
967///
John McCall60d7b3a2010-08-24 06:29:42 +0000968ExprResult
Douglas Gregord4dca082010-02-24 18:44:31 +0000969Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
970 tok::TokenKind OpKind,
971 CXXScopeSpec &SS,
John McCallb3d87482010-08-24 05:47:05 +0000972 ParsedType ObjectType) {
Douglas Gregord4dca082010-02-24 18:44:31 +0000973 // We're parsing either a pseudo-destructor-name or a dependent
974 // member access that has the same form as a
975 // pseudo-destructor-name. We parse both in the same way and let
976 // the action model sort them out.
977 //
978 // Note that the ::[opt] nested-name-specifier[opt] has already
979 // been parsed, and if there was a simple-template-id, it has
980 // been coalesced into a template-id annotation token.
981 UnqualifiedId FirstTypeName;
982 SourceLocation CCLoc;
983 if (Tok.is(tok::identifier)) {
984 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
985 ConsumeToken();
986 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
987 CCLoc = ConsumeToken();
988 } else if (Tok.is(tok::annot_template_id)) {
989 FirstTypeName.setTemplateId(
990 (TemplateIdAnnotation *)Tok.getAnnotationValue());
991 ConsumeToken();
992 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
993 CCLoc = ConsumeToken();
994 } else {
995 FirstTypeName.setIdentifier(0, SourceLocation());
996 }
997
998 // Parse the tilde.
999 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1000 SourceLocation TildeLoc = ConsumeToken();
1001 if (!Tok.is(tok::identifier)) {
1002 Diag(Tok, diag::err_destructor_tilde_identifier);
1003 return ExprError();
1004 }
1005
1006 // Parse the second type.
1007 UnqualifiedId SecondTypeName;
1008 IdentifierInfo *Name = Tok.getIdentifierInfo();
1009 SourceLocation NameLoc = ConsumeToken();
1010 SecondTypeName.setIdentifier(Name, NameLoc);
1011
1012 // If there is a '<', the second type name is a template-id. Parse
1013 // it as such.
1014 if (Tok.is(tok::less) &&
1015 ParseUnqualifiedIdTemplateId(SS, Name, NameLoc, false, ObjectType,
Douglas Gregor0278e122010-05-05 05:58:24 +00001016 SecondTypeName, /*AssumeTemplateName=*/true,
1017 /*TemplateKWLoc*/SourceLocation()))
Douglas Gregord4dca082010-02-24 18:44:31 +00001018 return ExprError();
1019
John McCall9ae2f072010-08-23 23:25:46 +00001020 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1021 OpLoc, OpKind,
Douglas Gregord4dca082010-02-24 18:44:31 +00001022 SS, FirstTypeName, CCLoc,
1023 TildeLoc, SecondTypeName,
1024 Tok.is(tok::l_paren));
1025}
1026
Reid Spencer5f016e22007-07-11 17:01:13 +00001027/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1028///
1029/// boolean-literal: [C++ 2.13.5]
1030/// 'true'
1031/// 'false'
John McCall60d7b3a2010-08-24 06:29:42 +00001032ExprResult Parser::ParseCXXBoolLiteral() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001033 tok::TokenKind Kind = Tok.getKind();
Sebastian Redlf53597f2009-03-15 17:47:39 +00001034 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001035}
Chris Lattner50dd2892008-02-26 00:51:44 +00001036
1037/// ParseThrowExpression - This handles the C++ throw expression.
1038///
1039/// throw-expression: [C++ 15]
1040/// 'throw' assignment-expression[opt]
John McCall60d7b3a2010-08-24 06:29:42 +00001041ExprResult Parser::ParseThrowExpression() {
Chris Lattner50dd2892008-02-26 00:51:44 +00001042 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattner50dd2892008-02-26 00:51:44 +00001043 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redl20df9b72008-12-11 22:51:44 +00001044
Chris Lattner2a2819a2008-04-06 06:02:23 +00001045 // If the current token isn't the start of an assignment-expression,
1046 // then the expression is not present. This handles things like:
1047 // "C ? throw : (void)42", which is crazy but legal.
1048 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1049 case tok::semi:
1050 case tok::r_paren:
1051 case tok::r_square:
1052 case tok::r_brace:
1053 case tok::colon:
1054 case tok::comma:
Douglas Gregorbca01b42011-07-06 22:04:06 +00001055 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, 0);
Chris Lattner50dd2892008-02-26 00:51:44 +00001056
Chris Lattner2a2819a2008-04-06 06:02:23 +00001057 default:
John McCall60d7b3a2010-08-24 06:29:42 +00001058 ExprResult Expr(ParseAssignmentExpression());
Sebastian Redl20df9b72008-12-11 22:51:44 +00001059 if (Expr.isInvalid()) return move(Expr);
Douglas Gregorbca01b42011-07-06 22:04:06 +00001060 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.take());
Chris Lattner2a2819a2008-04-06 06:02:23 +00001061 }
Chris Lattner50dd2892008-02-26 00:51:44 +00001062}
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +00001063
1064/// ParseCXXThis - This handles the C++ 'this' pointer.
1065///
1066/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1067/// a non-lvalue expression whose value is the address of the object for which
1068/// the function is called.
John McCall60d7b3a2010-08-24 06:29:42 +00001069ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +00001070 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1071 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redlf53597f2009-03-15 17:47:39 +00001072 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +00001073}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001074
1075/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1076/// Can be interpreted either as function-style casting ("int(x)")
1077/// or class type construction ("ClassType(x,y,z)")
1078/// or creation of a value-initialized type ("int()").
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001079/// See [C++ 5.2.3].
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001080///
1081/// postfix-expression: [C++ 5.2p1]
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001082/// simple-type-specifier '(' expression-list[opt] ')'
1083/// [C++0x] simple-type-specifier braced-init-list
1084/// typename-specifier '(' expression-list[opt] ')'
1085/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001086///
John McCall60d7b3a2010-08-24 06:29:42 +00001087ExprResult
Sebastian Redl20df9b72008-12-11 22:51:44 +00001088Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001089 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
John McCallb3d87482010-08-24 05:47:05 +00001090 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001091
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001092 assert((Tok.is(tok::l_paren) ||
1093 (getLang().CPlusPlus0x && Tok.is(tok::l_brace)))
1094 && "Expected '(' or '{'!");
Douglas Gregorbc61bd82011-01-11 00:33:19 +00001095
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001096 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001097
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001098 // FIXME: Convert to a proper type construct expression.
1099 return ParseBraceInitializer();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001100
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001101 } else {
1102 GreaterThanIsOperatorScope G(GreaterThanIsOperator, true);
1103
1104 SourceLocation LParenLoc = ConsumeParen();
1105
1106 ExprVector Exprs(Actions);
1107 CommaLocsTy CommaLocs;
1108
1109 if (Tok.isNot(tok::r_paren)) {
1110 if (ParseExpressionList(Exprs, CommaLocs)) {
1111 SkipUntil(tok::r_paren);
1112 return ExprError();
1113 }
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001114 }
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001115
1116 // Match the ')'.
1117 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1118
1119 // TypeRep could be null, if it references an invalid typedef.
1120 if (!TypeRep)
1121 return ExprError();
1122
1123 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1124 "Unexpected number of commas!");
1125 return Actions.ActOnCXXTypeConstructExpr(TypeRep, LParenLoc, move_arg(Exprs),
1126 RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001127 }
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001128}
1129
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001130/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001131///
1132/// condition:
1133/// expression
1134/// type-specifier-seq declarator '=' assignment-expression
1135/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1136/// '=' assignment-expression
1137///
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001138/// \param ExprResult if the condition was parsed as an expression, the
1139/// parsed expression.
1140///
1141/// \param DeclResult if the condition was parsed as a declaration, the
1142/// parsed declaration.
1143///
Douglas Gregor586596f2010-05-06 17:25:47 +00001144/// \param Loc The location of the start of the statement that requires this
1145/// condition, e.g., the "for" in a for loop.
1146///
1147/// \param ConvertToBoolean Whether the condition expression should be
1148/// converted to a boolean value.
1149///
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001150/// \returns true if there was a parsing, false otherwise.
John McCall60d7b3a2010-08-24 06:29:42 +00001151bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1152 Decl *&DeclOut,
Douglas Gregor586596f2010-05-06 17:25:47 +00001153 SourceLocation Loc,
1154 bool ConvertToBoolean) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001155 if (Tok.is(tok::code_completion)) {
John McCallf312b1e2010-08-26 23:41:50 +00001156 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001157 cutOffParsing();
1158 return true;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001159 }
1160
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001161 if (!isCXXConditionDeclaration()) {
Douglas Gregor586596f2010-05-06 17:25:47 +00001162 // Parse the expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001163 ExprOut = ParseExpression(); // expression
1164 DeclOut = 0;
1165 if (ExprOut.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001166 return true;
1167
1168 // If required, convert to a boolean value.
1169 if (ConvertToBoolean)
John McCall60d7b3a2010-08-24 06:29:42 +00001170 ExprOut
1171 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1172 return ExprOut.isInvalid();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001173 }
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001174
1175 // type-specifier-seq
John McCall0b7e6782011-03-24 11:26:52 +00001176 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001177 ParseSpecifierQualifierList(DS);
1178
1179 // declarator
1180 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1181 ParseDeclarator(DeclaratorInfo);
1182
1183 // simple-asm-expr[opt]
1184 if (Tok.is(tok::kw_asm)) {
Sebastian Redlab197ba2009-02-09 18:23:29 +00001185 SourceLocation Loc;
John McCall60d7b3a2010-08-24 06:29:42 +00001186 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001187 if (AsmLabel.isInvalid()) {
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001188 SkipUntil(tok::semi);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001189 return true;
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001190 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001191 DeclaratorInfo.setAsmLabel(AsmLabel.release());
Sebastian Redlab197ba2009-02-09 18:23:29 +00001192 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001193 }
1194
1195 // If attributes are present, parse them.
John McCall7f040a92010-12-24 02:08:15 +00001196 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001197
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001198 // Type-check the declaration itself.
John McCall60d7b3a2010-08-24 06:29:42 +00001199 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall7f040a92010-12-24 02:08:15 +00001200 DeclaratorInfo);
John McCall60d7b3a2010-08-24 06:29:42 +00001201 DeclOut = Dcl.get();
1202 ExprOut = ExprError();
Argyrios Kyrtzidisa6eb5f82010-10-08 02:39:23 +00001203
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001204 // '=' assignment-expression
Argyrios Kyrtzidisa6eb5f82010-10-08 02:39:23 +00001205 if (isTokenEqualOrMistypedEqualEqual(
1206 diag::err_invalid_equalequal_after_declarator)) {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001207 ConsumeToken();
John McCall60d7b3a2010-08-24 06:29:42 +00001208 ExprResult AssignExpr(ParseAssignmentExpression());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001209 if (!AssignExpr.isInvalid())
Richard Smith34b41d92011-02-20 03:19:35 +00001210 Actions.AddInitializerToDecl(DeclOut, AssignExpr.take(), false,
1211 DS.getTypeSpecType() == DeclSpec::TST_auto);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001212 } else {
1213 // FIXME: C++0x allows a braced-init-list
1214 Diag(Tok, diag::err_expected_equal_after_declarator);
1215 }
1216
Douglas Gregor586596f2010-05-06 17:25:47 +00001217 // FIXME: Build a reference to this declaration? Convert it to bool?
1218 // (This is currently handled by Sema).
Richard Smith483b9f32011-02-21 20:05:19 +00001219
1220 Actions.FinalizeDeclaration(DeclOut);
Douglas Gregor586596f2010-05-06 17:25:47 +00001221
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001222 return false;
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001223}
1224
Douglas Gregor6aa14d82010-04-21 22:36:40 +00001225/// \brief Determine whether the current token starts a C++
1226/// simple-type-specifier.
1227bool Parser::isCXXSimpleTypeSpecifier() const {
1228 switch (Tok.getKind()) {
1229 case tok::annot_typename:
1230 case tok::kw_short:
1231 case tok::kw_long:
Francois Pichet338d7f72011-04-28 01:59:37 +00001232 case tok::kw___int64:
Douglas Gregor6aa14d82010-04-21 22:36:40 +00001233 case tok::kw_signed:
1234 case tok::kw_unsigned:
1235 case tok::kw_void:
1236 case tok::kw_char:
1237 case tok::kw_int:
1238 case tok::kw_float:
1239 case tok::kw_double:
1240 case tok::kw_wchar_t:
1241 case tok::kw_char16_t:
1242 case tok::kw_char32_t:
1243 case tok::kw_bool:
Douglas Gregord9d75e52011-04-27 05:41:15 +00001244 case tok::kw_decltype:
Douglas Gregor6aa14d82010-04-21 22:36:40 +00001245 case tok::kw_typeof:
Sean Huntdb5d44b2011-05-19 05:37:45 +00001246 case tok::kw___underlying_type:
Douglas Gregor6aa14d82010-04-21 22:36:40 +00001247 return true;
1248
1249 default:
1250 break;
1251 }
1252
1253 return false;
1254}
1255
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001256/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1257/// This should only be called when the current token is known to be part of
1258/// simple-type-specifier.
1259///
1260/// simple-type-specifier:
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001261/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001262/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1263/// char
1264/// wchar_t
1265/// bool
1266/// short
1267/// int
1268/// long
1269/// signed
1270/// unsigned
1271/// float
1272/// double
1273/// void
1274/// [GNU] typeof-specifier
1275/// [C++0x] auto [TODO]
1276///
1277/// type-name:
1278/// class-name
1279/// enum-name
1280/// typedef-name
1281///
1282void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1283 DS.SetRangeStart(Tok.getLocation());
1284 const char *PrevSpec;
John McCallfec54012009-08-03 20:12:06 +00001285 unsigned DiagID;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001286 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001288 switch (Tok.getKind()) {
Chris Lattner55a7cef2009-01-05 00:13:00 +00001289 case tok::identifier: // foo::bar
1290 case tok::coloncolon: // ::foo::bar
David Blaikieb219cfc2011-09-23 05:06:16 +00001291 llvm_unreachable("Annotation token should already be formed!");
Mike Stump1eb44332009-09-09 15:08:12 +00001292 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00001293 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner55a7cef2009-01-05 00:13:00 +00001294
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001295 // type-name
Chris Lattnerb31757b2009-01-06 05:06:21 +00001296 case tok::annot_typename: {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001297 if (getTypeAnnotation(Tok))
1298 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1299 getTypeAnnotation(Tok));
1300 else
1301 DS.SetTypeSpecError();
Douglas Gregor9bd1d8d2010-10-21 23:17:00 +00001302
1303 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1304 ConsumeToken();
1305
1306 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1307 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1308 // Objective-C interface. If we don't have Objective-C or a '<', this is
1309 // just a normal reference to a typedef name.
1310 if (Tok.is(tok::less) && getLang().ObjC1)
1311 ParseObjCProtocolQualifiers(DS);
1312
1313 DS.Finish(Diags, PP);
1314 return;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001315 }
Mike Stump1eb44332009-09-09 15:08:12 +00001316
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001317 // builtin types
1318 case tok::kw_short:
John McCallfec54012009-08-03 20:12:06 +00001319 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001320 break;
1321 case tok::kw_long:
John McCallfec54012009-08-03 20:12:06 +00001322 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001323 break;
Francois Pichet338d7f72011-04-28 01:59:37 +00001324 case tok::kw___int64:
1325 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID);
1326 break;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001327 case tok::kw_signed:
John McCallfec54012009-08-03 20:12:06 +00001328 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001329 break;
1330 case tok::kw_unsigned:
John McCallfec54012009-08-03 20:12:06 +00001331 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001332 break;
1333 case tok::kw_void:
John McCallfec54012009-08-03 20:12:06 +00001334 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001335 break;
1336 case tok::kw_char:
John McCallfec54012009-08-03 20:12:06 +00001337 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001338 break;
1339 case tok::kw_int:
John McCallfec54012009-08-03 20:12:06 +00001340 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001341 break;
1342 case tok::kw_float:
John McCallfec54012009-08-03 20:12:06 +00001343 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001344 break;
1345 case tok::kw_double:
John McCallfec54012009-08-03 20:12:06 +00001346 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001347 break;
1348 case tok::kw_wchar_t:
John McCallfec54012009-08-03 20:12:06 +00001349 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001350 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001351 case tok::kw_char16_t:
John McCallfec54012009-08-03 20:12:06 +00001352 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001353 break;
1354 case tok::kw_char32_t:
John McCallfec54012009-08-03 20:12:06 +00001355 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001356 break;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001357 case tok::kw_bool:
John McCallfec54012009-08-03 20:12:06 +00001358 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001359 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Douglas Gregor6aa14d82010-04-21 22:36:40 +00001361 // FIXME: C++0x decltype support.
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001362 // GNU typeof support.
1363 case tok::kw_typeof:
1364 ParseTypeofSpecifier(DS);
Douglas Gregor9b3064b2009-04-01 22:41:11 +00001365 DS.Finish(Diags, PP);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001366 return;
1367 }
Chris Lattnerb31757b2009-01-06 05:06:21 +00001368 if (Tok.is(tok::annot_typename))
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001369 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1370 else
1371 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001372 ConsumeToken();
Douglas Gregor9b3064b2009-04-01 22:41:11 +00001373 DS.Finish(Diags, PP);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001374}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001375
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001376/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1377/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1378/// e.g., "const short int". Note that the DeclSpec is *not* finished
1379/// by parsing the type-specifier-seq, because these sequences are
1380/// typically followed by some form of declarator. Returns true and
1381/// emits diagnostics if this is not a type-specifier-seq, false
1382/// otherwise.
1383///
1384/// type-specifier-seq: [C++ 8.1]
1385/// type-specifier type-specifier-seq[opt]
1386///
1387bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1388 DS.SetRangeStart(Tok.getLocation());
1389 const char *PrevSpec = 0;
John McCallfec54012009-08-03 20:12:06 +00001390 unsigned DiagID;
1391 bool isInvalid = 0;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001392
1393 // Parse one or more of the type specifiers.
Sebastian Redld9bafa72010-02-03 21:21:43 +00001394 if (!ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1395 ParsedTemplateInfo(), /*SuppressDeclarations*/true)) {
Nick Lewycky9fa8e562010-11-03 17:52:57 +00001396 Diag(Tok, diag::err_expected_type);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001397 return true;
1398 }
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Sebastian Redld9bafa72010-02-03 21:21:43 +00001400 while (ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1401 ParsedTemplateInfo(), /*SuppressDeclarations*/true))
1402 {}
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001403
Douglas Gregor396a9f22010-02-24 23:13:13 +00001404 DS.Finish(Diags, PP);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001405 return false;
1406}
1407
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001408/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1409/// some form.
1410///
1411/// This routine is invoked when a '<' is encountered after an identifier or
1412/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1413/// whether the unqualified-id is actually a template-id. This routine will
1414/// then parse the template arguments and form the appropriate template-id to
1415/// return to the caller.
1416///
1417/// \param SS the nested-name-specifier that precedes this template-id, if
1418/// we're actually parsing a qualified-id.
1419///
1420/// \param Name for constructor and destructor names, this is the actual
1421/// identifier that may be a template-name.
1422///
1423/// \param NameLoc the location of the class-name in a constructor or
1424/// destructor.
1425///
1426/// \param EnteringContext whether we're entering the scope of the
1427/// nested-name-specifier.
1428///
Douglas Gregor46df8cc2009-11-03 21:24:04 +00001429/// \param ObjectType if this unqualified-id occurs within a member access
1430/// expression, the type of the base object whose member is being accessed.
1431///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001432/// \param Id as input, describes the template-name or operator-function-id
1433/// that precedes the '<'. If template arguments were parsed successfully,
1434/// will be updated with the template-id.
1435///
Douglas Gregord4dca082010-02-24 18:44:31 +00001436/// \param AssumeTemplateId When true, this routine will assume that the name
1437/// refers to a template without performing name lookup to verify.
1438///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001439/// \returns true if a parse error occurred, false otherwise.
1440bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
1441 IdentifierInfo *Name,
1442 SourceLocation NameLoc,
1443 bool EnteringContext,
John McCallb3d87482010-08-24 05:47:05 +00001444 ParsedType ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00001445 UnqualifiedId &Id,
Douglas Gregor0278e122010-05-05 05:58:24 +00001446 bool AssumeTemplateId,
1447 SourceLocation TemplateKWLoc) {
1448 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1449 "Expected '<' to finish parsing a template-id");
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001450
1451 TemplateTy Template;
1452 TemplateNameKind TNK = TNK_Non_template;
1453 switch (Id.getKind()) {
1454 case UnqualifiedId::IK_Identifier:
Douglas Gregor014e88d2009-11-03 23:16:33 +00001455 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunte6252d12009-11-28 08:58:14 +00001456 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregord4dca082010-02-24 18:44:31 +00001457 if (AssumeTemplateId) {
Douglas Gregor23c94db2010-07-02 17:43:08 +00001458 TNK = Actions.ActOnDependentTemplateName(getCurScope(), TemplateKWLoc, SS,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001459 Id, ObjectType, EnteringContext,
1460 Template);
1461 if (TNK == TNK_Non_template)
1462 return true;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001463 } else {
1464 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001465 TNK = Actions.isTemplateName(getCurScope(), SS,
1466 TemplateKWLoc.isValid(), Id,
1467 ObjectType, EnteringContext, Template,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001468 MemberOfUnknownSpecialization);
1469
1470 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1471 ObjectType && IsTemplateArgumentList()) {
1472 // We have something like t->getAs<T>(), where getAs is a
1473 // member of an unknown specialization. However, this will only
1474 // parse correctly as a template, so suggest the keyword 'template'
1475 // before 'getAs' and treat this as a dependent template name.
1476 std::string Name;
1477 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1478 Name = Id.Identifier->getName();
1479 else {
1480 Name = "operator ";
1481 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1482 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1483 else
1484 Name += Id.Identifier->getName();
1485 }
1486 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1487 << Name
1488 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Douglas Gregor23c94db2010-07-02 17:43:08 +00001489 TNK = Actions.ActOnDependentTemplateName(getCurScope(), TemplateKWLoc,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001490 SS, Id, ObjectType,
1491 EnteringContext, Template);
1492 if (TNK == TNK_Non_template)
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001493 return true;
1494 }
1495 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001496 break;
1497
Douglas Gregor014e88d2009-11-03 23:16:33 +00001498 case UnqualifiedId::IK_ConstructorName: {
1499 UnqualifiedId TemplateName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001500 bool MemberOfUnknownSpecialization;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001501 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c153532010-08-06 12:11:11 +00001502 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1503 TemplateName, ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001504 EnteringContext, Template,
1505 MemberOfUnknownSpecialization);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001506 break;
1507 }
1508
Douglas Gregor014e88d2009-11-03 23:16:33 +00001509 case UnqualifiedId::IK_DestructorName: {
1510 UnqualifiedId TemplateName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001511 bool MemberOfUnknownSpecialization;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001512 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001513 if (ObjectType) {
Douglas Gregor23c94db2010-07-02 17:43:08 +00001514 TNK = Actions.ActOnDependentTemplateName(getCurScope(), TemplateKWLoc, SS,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001515 TemplateName, ObjectType,
1516 EnteringContext, Template);
1517 if (TNK == TNK_Non_template)
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001518 return true;
1519 } else {
Abramo Bagnara7c153532010-08-06 12:11:11 +00001520 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1521 TemplateName, ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001522 EnteringContext, Template,
1523 MemberOfUnknownSpecialization);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001524
John McCallb3d87482010-08-24 05:47:05 +00001525 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregor124b8782010-02-16 19:09:40 +00001526 Diag(NameLoc, diag::err_destructor_template_id)
1527 << Name << SS.getRange();
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001528 return true;
1529 }
1530 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001531 break;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001532 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001533
1534 default:
1535 return false;
1536 }
1537
1538 if (TNK == TNK_Non_template)
1539 return false;
1540
1541 // Parse the enclosed template argument list.
1542 SourceLocation LAngleLoc, RAngleLoc;
1543 TemplateArgList TemplateArgs;
Douglas Gregor0278e122010-05-05 05:58:24 +00001544 if (Tok.is(tok::less) &&
1545 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
Douglas Gregor059101f2011-03-02 00:47:37 +00001546 SS, true, LAngleLoc,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001547 TemplateArgs,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001548 RAngleLoc))
1549 return true;
1550
1551 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
Sean Hunte6252d12009-11-28 08:58:14 +00001552 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1553 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001554 // Form a parsed representation of the template-id to be stored in the
1555 // UnqualifiedId.
1556 TemplateIdAnnotation *TemplateId
1557 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
1558
1559 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
1560 TemplateId->Name = Id.Identifier;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001561 TemplateId->Operator = OO_None;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001562 TemplateId->TemplateNameLoc = Id.StartLocation;
1563 } else {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001564 TemplateId->Name = 0;
1565 TemplateId->Operator = Id.OperatorFunctionId.Operator;
1566 TemplateId->TemplateNameLoc = Id.StartLocation;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001567 }
1568
Douglas Gregor059101f2011-03-02 00:47:37 +00001569 TemplateId->SS = SS;
John McCall2b5289b2010-08-23 07:28:44 +00001570 TemplateId->Template = Template;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001571 TemplateId->Kind = TNK;
1572 TemplateId->LAngleLoc = LAngleLoc;
1573 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregor314b97f2009-11-10 19:49:08 +00001574 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001575 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
Douglas Gregor314b97f2009-11-10 19:49:08 +00001576 Arg != ArgEnd; ++Arg)
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001577 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001578
1579 Id.setTemplateId(TemplateId);
1580 return false;
1581 }
1582
1583 // Bundle the template arguments together.
1584 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001585 TemplateArgs.size());
1586
1587 // Constructor and destructor names.
John McCallf312b1e2010-08-26 23:41:50 +00001588 TypeResult Type
Douglas Gregor059101f2011-03-02 00:47:37 +00001589 = Actions.ActOnTemplateIdType(SS, Template, NameLoc,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001590 LAngleLoc, TemplateArgsPtr,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001591 RAngleLoc);
1592 if (Type.isInvalid())
1593 return true;
1594
1595 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
1596 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
1597 else
1598 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
1599
1600 return false;
1601}
1602
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001603/// \brief Parse an operator-function-id or conversion-function-id as part
1604/// of a C++ unqualified-id.
1605///
1606/// This routine is responsible only for parsing the operator-function-id or
1607/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001608///
1609/// \code
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001610/// operator-function-id: [C++ 13.5]
1611/// 'operator' operator
1612///
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001613/// operator: one of
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001614/// new delete new[] delete[]
1615/// + - * / % ^ & | ~
1616/// ! = < > += -= *= /= %=
1617/// ^= &= |= << >> >>= <<= == !=
1618/// <= >= && || ++ -- , ->* ->
1619/// () []
1620///
1621/// conversion-function-id: [C++ 12.3.2]
1622/// operator conversion-type-id
1623///
1624/// conversion-type-id:
1625/// type-specifier-seq conversion-declarator[opt]
1626///
1627/// conversion-declarator:
1628/// ptr-operator conversion-declarator[opt]
1629/// \endcode
1630///
1631/// \param The nested-name-specifier that preceded this unqualified-id. If
1632/// non-empty, then we are parsing the unqualified-id of a qualified-id.
1633///
1634/// \param EnteringContext whether we are entering the scope of the
1635/// nested-name-specifier.
1636///
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001637/// \param ObjectType if this unqualified-id occurs within a member access
1638/// expression, the type of the base object whose member is being accessed.
1639///
1640/// \param Result on a successful parse, contains the parsed unqualified-id.
1641///
1642/// \returns true if parsing fails, false otherwise.
1643bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallb3d87482010-08-24 05:47:05 +00001644 ParsedType ObjectType,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001645 UnqualifiedId &Result) {
1646 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
1647
1648 // Consume the 'operator' keyword.
1649 SourceLocation KeywordLoc = ConsumeToken();
1650
1651 // Determine what kind of operator name we have.
1652 unsigned SymbolIdx = 0;
1653 SourceLocation SymbolLocations[3];
1654 OverloadedOperatorKind Op = OO_None;
1655 switch (Tok.getKind()) {
1656 case tok::kw_new:
1657 case tok::kw_delete: {
1658 bool isNew = Tok.getKind() == tok::kw_new;
1659 // Consume the 'new' or 'delete'.
1660 SymbolLocations[SymbolIdx++] = ConsumeToken();
1661 if (Tok.is(tok::l_square)) {
1662 // Consume the '['.
1663 SourceLocation LBracketLoc = ConsumeBracket();
1664 // Consume the ']'.
1665 SourceLocation RBracketLoc = MatchRHSPunctuation(tok::r_square,
1666 LBracketLoc);
1667 if (RBracketLoc.isInvalid())
1668 return true;
1669
1670 SymbolLocations[SymbolIdx++] = LBracketLoc;
1671 SymbolLocations[SymbolIdx++] = RBracketLoc;
1672 Op = isNew? OO_Array_New : OO_Array_Delete;
1673 } else {
1674 Op = isNew? OO_New : OO_Delete;
1675 }
1676 break;
1677 }
1678
1679#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1680 case tok::Token: \
1681 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
1682 Op = OO_##Name; \
1683 break;
1684#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
1685#include "clang/Basic/OperatorKinds.def"
1686
1687 case tok::l_paren: {
1688 // Consume the '('.
1689 SourceLocation LParenLoc = ConsumeParen();
1690 // Consume the ')'.
1691 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren,
1692 LParenLoc);
1693 if (RParenLoc.isInvalid())
1694 return true;
1695
1696 SymbolLocations[SymbolIdx++] = LParenLoc;
1697 SymbolLocations[SymbolIdx++] = RParenLoc;
1698 Op = OO_Call;
1699 break;
1700 }
1701
1702 case tok::l_square: {
1703 // Consume the '['.
1704 SourceLocation LBracketLoc = ConsumeBracket();
1705 // Consume the ']'.
1706 SourceLocation RBracketLoc = MatchRHSPunctuation(tok::r_square,
1707 LBracketLoc);
1708 if (RBracketLoc.isInvalid())
1709 return true;
1710
1711 SymbolLocations[SymbolIdx++] = LBracketLoc;
1712 SymbolLocations[SymbolIdx++] = RBracketLoc;
1713 Op = OO_Subscript;
1714 break;
1715 }
1716
1717 case tok::code_completion: {
1718 // Code completion for the operator name.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001719 Actions.CodeCompleteOperatorName(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001720 cutOffParsing();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001721 // Don't try to parse any further.
1722 return true;
1723 }
1724
1725 default:
1726 break;
1727 }
1728
1729 if (Op != OO_None) {
1730 // We have parsed an operator-function-id.
1731 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
1732 return false;
1733 }
Sean Hunt0486d742009-11-28 04:44:28 +00001734
1735 // Parse a literal-operator-id.
1736 //
1737 // literal-operator-id: [C++0x 13.5.8]
1738 // operator "" identifier
1739
1740 if (getLang().CPlusPlus0x && Tok.is(tok::string_literal)) {
1741 if (Tok.getLength() != 2)
1742 Diag(Tok.getLocation(), diag::err_operator_string_not_empty);
1743 ConsumeStringToken();
1744
1745 if (Tok.isNot(tok::identifier)) {
1746 Diag(Tok.getLocation(), diag::err_expected_ident);
1747 return true;
1748 }
1749
1750 IdentifierInfo *II = Tok.getIdentifierInfo();
1751 Result.setLiteralOperatorId(II, KeywordLoc, ConsumeToken());
Sean Hunt3e518bd2009-11-29 07:34:05 +00001752 return false;
Sean Hunt0486d742009-11-28 04:44:28 +00001753 }
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001754
1755 // Parse a conversion-function-id.
1756 //
1757 // conversion-function-id: [C++ 12.3.2]
1758 // operator conversion-type-id
1759 //
1760 // conversion-type-id:
1761 // type-specifier-seq conversion-declarator[opt]
1762 //
1763 // conversion-declarator:
1764 // ptr-operator conversion-declarator[opt]
1765
1766 // Parse the type-specifier-seq.
John McCall0b7e6782011-03-24 11:26:52 +00001767 DeclSpec DS(AttrFactory);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +00001768 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001769 return true;
1770
1771 // Parse the conversion-declarator, which is merely a sequence of
1772 // ptr-operators.
1773 Declarator D(DS, Declarator::TypeNameContext);
1774 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
1775
1776 // Finish up the type.
John McCallf312b1e2010-08-26 23:41:50 +00001777 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001778 if (Ty.isInvalid())
1779 return true;
1780
1781 // Note that this is a conversion-function-id.
1782 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
1783 D.getSourceRange().getEnd());
1784 return false;
1785}
1786
1787/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
1788/// name of an entity.
1789///
1790/// \code
1791/// unqualified-id: [C++ expr.prim.general]
1792/// identifier
1793/// operator-function-id
1794/// conversion-function-id
1795/// [C++0x] literal-operator-id [TODO]
1796/// ~ class-name
1797/// template-id
1798///
1799/// \endcode
1800///
1801/// \param The nested-name-specifier that preceded this unqualified-id. If
1802/// non-empty, then we are parsing the unqualified-id of a qualified-id.
1803///
1804/// \param EnteringContext whether we are entering the scope of the
1805/// nested-name-specifier.
1806///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001807/// \param AllowDestructorName whether we allow parsing of a destructor name.
1808///
1809/// \param AllowConstructorName whether we allow parsing a constructor name.
1810///
Douglas Gregor46df8cc2009-11-03 21:24:04 +00001811/// \param ObjectType if this unqualified-id occurs within a member access
1812/// expression, the type of the base object whose member is being accessed.
1813///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001814/// \param Result on a successful parse, contains the parsed unqualified-id.
1815///
1816/// \returns true if parsing fails, false otherwise.
1817bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
1818 bool AllowDestructorName,
1819 bool AllowConstructorName,
John McCallb3d87482010-08-24 05:47:05 +00001820 ParsedType ObjectType,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001821 UnqualifiedId &Result) {
Douglas Gregor0278e122010-05-05 05:58:24 +00001822
1823 // Handle 'A::template B'. This is for template-ids which have not
1824 // already been annotated by ParseOptionalCXXScopeSpecifier().
1825 bool TemplateSpecified = false;
1826 SourceLocation TemplateKWLoc;
1827 if (getLang().CPlusPlus && Tok.is(tok::kw_template) &&
1828 (ObjectType || SS.isSet())) {
1829 TemplateSpecified = true;
1830 TemplateKWLoc = ConsumeToken();
1831 }
1832
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001833 // unqualified-id:
1834 // identifier
1835 // template-id (when it hasn't already been annotated)
1836 if (Tok.is(tok::identifier)) {
1837 // Consume the identifier.
1838 IdentifierInfo *Id = Tok.getIdentifierInfo();
1839 SourceLocation IdLoc = ConsumeToken();
1840
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001841 if (!getLang().CPlusPlus) {
1842 // If we're not in C++, only identifiers matter. Record the
1843 // identifier and return.
1844 Result.setIdentifier(Id, IdLoc);
1845 return false;
1846 }
1847
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001848 if (AllowConstructorName &&
Douglas Gregor23c94db2010-07-02 17:43:08 +00001849 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001850 // We have parsed a constructor name.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001851 Result.setConstructorName(Actions.getTypeName(*Id, IdLoc, getCurScope(),
Douglas Gregor9e876872011-03-01 18:12:44 +00001852 &SS, false, false,
1853 ParsedType(),
1854 /*NonTrivialTypeSourceInfo=*/true),
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001855 IdLoc, IdLoc);
1856 } else {
1857 // We have parsed an identifier.
1858 Result.setIdentifier(Id, IdLoc);
1859 }
1860
1861 // If the next token is a '<', we may have a template.
Douglas Gregor0278e122010-05-05 05:58:24 +00001862 if (TemplateSpecified || Tok.is(tok::less))
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001863 return ParseUnqualifiedIdTemplateId(SS, Id, IdLoc, EnteringContext,
Douglas Gregor0278e122010-05-05 05:58:24 +00001864 ObjectType, Result,
1865 TemplateSpecified, TemplateKWLoc);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001866
1867 return false;
1868 }
1869
1870 // unqualified-id:
1871 // template-id (already parsed and annotated)
1872 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +00001873 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001874
1875 // If the template-name names the current class, then this is a constructor
1876 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor23c94db2010-07-02 17:43:08 +00001877 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001878 if (SS.isSet()) {
1879 // C++ [class.qual]p2 specifies that a qualified template-name
1880 // is taken as the constructor name where a constructor can be
1881 // declared. Thus, the template arguments are extraneous, so
1882 // complain about them and remove them entirely.
1883 Diag(TemplateId->TemplateNameLoc,
1884 diag::err_out_of_line_constructor_template_id)
1885 << TemplateId->Name
Douglas Gregor849b2432010-03-31 17:46:05 +00001886 << FixItHint::CreateRemoval(
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001887 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
1888 Result.setConstructorName(Actions.getTypeName(*TemplateId->Name,
1889 TemplateId->TemplateNameLoc,
Douglas Gregor23c94db2010-07-02 17:43:08 +00001890 getCurScope(),
Douglas Gregor9e876872011-03-01 18:12:44 +00001891 &SS, false, false,
1892 ParsedType(),
1893 /*NontrivialTypeSourceInfo=*/true),
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001894 TemplateId->TemplateNameLoc,
1895 TemplateId->RAngleLoc);
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001896 ConsumeToken();
1897 return false;
1898 }
1899
1900 Result.setConstructorTemplateId(TemplateId);
1901 ConsumeToken();
1902 return false;
1903 }
1904
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001905 // We have already parsed a template-id; consume the annotation token as
1906 // our unqualified-id.
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001907 Result.setTemplateId(TemplateId);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001908 ConsumeToken();
1909 return false;
1910 }
1911
1912 // unqualified-id:
1913 // operator-function-id
1914 // conversion-function-id
1915 if (Tok.is(tok::kw_operator)) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001916 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001917 return true;
1918
Sean Hunte6252d12009-11-28 08:58:14 +00001919 // If we have an operator-function-id or a literal-operator-id and the next
1920 // token is a '<', we may have a
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001921 //
1922 // template-id:
1923 // operator-function-id < template-argument-list[opt] >
Sean Hunte6252d12009-11-28 08:58:14 +00001924 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1925 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
Douglas Gregor0278e122010-05-05 05:58:24 +00001926 (TemplateSpecified || Tok.is(tok::less)))
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001927 return ParseUnqualifiedIdTemplateId(SS, 0, SourceLocation(),
1928 EnteringContext, ObjectType,
Douglas Gregor0278e122010-05-05 05:58:24 +00001929 Result,
1930 TemplateSpecified, TemplateKWLoc);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001931
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001932 return false;
1933 }
1934
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001935 if (getLang().CPlusPlus &&
1936 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001937 // C++ [expr.unary.op]p10:
1938 // There is an ambiguity in the unary-expression ~X(), where X is a
1939 // class-name. The ambiguity is resolved in favor of treating ~ as a
1940 // unary complement rather than treating ~X as referring to a destructor.
1941
1942 // Parse the '~'.
1943 SourceLocation TildeLoc = ConsumeToken();
1944
1945 // Parse the class-name.
1946 if (Tok.isNot(tok::identifier)) {
Douglas Gregor124b8782010-02-16 19:09:40 +00001947 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001948 return true;
1949 }
1950
1951 // Parse the class-name (or template-name in a simple-template-id).
1952 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
1953 SourceLocation ClassNameLoc = ConsumeToken();
1954
Douglas Gregor0278e122010-05-05 05:58:24 +00001955 if (TemplateSpecified || Tok.is(tok::less)) {
John McCallb3d87482010-08-24 05:47:05 +00001956 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001957 return ParseUnqualifiedIdTemplateId(SS, ClassName, ClassNameLoc,
Douglas Gregor0278e122010-05-05 05:58:24 +00001958 EnteringContext, ObjectType, Result,
1959 TemplateSpecified, TemplateKWLoc);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001960 }
1961
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001962 // Note that this is a destructor name.
John McCallb3d87482010-08-24 05:47:05 +00001963 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
1964 ClassNameLoc, getCurScope(),
1965 SS, ObjectType,
1966 EnteringContext);
Douglas Gregor124b8782010-02-16 19:09:40 +00001967 if (!Ty)
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001968 return true;
Douglas Gregor124b8782010-02-16 19:09:40 +00001969
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001970 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001971 return false;
1972 }
1973
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001974 Diag(Tok, diag::err_expected_unqualified_id)
1975 << getLang().CPlusPlus;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001976 return true;
1977}
1978
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001979/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
1980/// memory in a typesafe manner and call constructors.
Mike Stump1eb44332009-09-09 15:08:12 +00001981///
Chris Lattner59232d32009-01-04 21:25:24 +00001982/// This method is called to parse the new expression after the optional :: has
1983/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
1984/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001985///
1986/// new-expression:
1987/// '::'[opt] 'new' new-placement[opt] new-type-id
1988/// new-initializer[opt]
1989/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
1990/// new-initializer[opt]
1991///
1992/// new-placement:
1993/// '(' expression-list ')'
1994///
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001995/// new-type-id:
1996/// type-specifier-seq new-declarator[opt]
Douglas Gregor893e1cc2011-04-15 19:40:02 +00001997/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001998///
1999/// new-declarator:
2000/// ptr-operator new-declarator[opt]
2001/// direct-new-declarator
2002///
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002003/// new-initializer:
2004/// '(' expression-list[opt] ')'
Sebastian Redldbef1bb2011-06-05 12:23:16 +00002005/// [C++0x] braced-init-list
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002006///
John McCall60d7b3a2010-08-24 06:29:42 +00002007ExprResult
Chris Lattner59232d32009-01-04 21:25:24 +00002008Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2009 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2010 ConsumeToken(); // Consume 'new'
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002011
2012 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2013 // second form of new-expression. It can't be a new-type-id.
2014
Sebastian Redla55e52c2008-11-25 22:21:31 +00002015 ExprVector PlacementArgs(Actions);
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002016 SourceLocation PlacementLParen, PlacementRParen;
2017
Douglas Gregor4bd40312010-07-13 15:54:32 +00002018 SourceRange TypeIdParens;
John McCall0b7e6782011-03-24 11:26:52 +00002019 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00002020 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002021 if (Tok.is(tok::l_paren)) {
2022 // If it turns out to be a placement, we change the type location.
2023 PlacementLParen = ConsumeParen();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002024 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2025 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002026 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002027 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002028
2029 PlacementRParen = MatchRHSPunctuation(tok::r_paren, PlacementLParen);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002030 if (PlacementRParen.isInvalid()) {
2031 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002032 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002033 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002034
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002035 if (PlacementArgs.empty()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002036 // Reset the placement locations. There was no placement.
Douglas Gregor4bd40312010-07-13 15:54:32 +00002037 TypeIdParens = SourceRange(PlacementLParen, PlacementRParen);
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002038 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002039 } else {
2040 // We still need the type.
2041 if (Tok.is(tok::l_paren)) {
Douglas Gregor4bd40312010-07-13 15:54:32 +00002042 TypeIdParens.setBegin(ConsumeParen());
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002043 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002044 ParseSpecifierQualifierList(DS);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002045 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002046 ParseDeclarator(DeclaratorInfo);
Douglas Gregor4bd40312010-07-13 15:54:32 +00002047 TypeIdParens.setEnd(MatchRHSPunctuation(tok::r_paren,
2048 TypeIdParens.getBegin()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002049 } else {
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002050 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002051 if (ParseCXXTypeSpecifierSeq(DS))
2052 DeclaratorInfo.setInvalidType(true);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002053 else {
2054 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002055 ParseDeclaratorInternal(DeclaratorInfo,
2056 &Parser::ParseDirectNewDeclarator);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002057 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002058 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002059 }
2060 } else {
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002061 // A new-type-id is a simplified type-id, where essentially the
2062 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002063 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002064 if (ParseCXXTypeSpecifierSeq(DS))
2065 DeclaratorInfo.setInvalidType(true);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002066 else {
2067 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002068 ParseDeclaratorInternal(DeclaratorInfo,
2069 &Parser::ParseDirectNewDeclarator);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002070 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002071 }
Chris Lattnereaaebc72009-04-25 08:06:05 +00002072 if (DeclaratorInfo.isInvalidType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002073 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002074 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002075 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002076
Sebastian Redla55e52c2008-11-25 22:21:31 +00002077 ExprVector ConstructorArgs(Actions);
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002078 SourceLocation ConstructorLParen, ConstructorRParen;
2079
2080 if (Tok.is(tok::l_paren)) {
2081 ConstructorLParen = ConsumeParen();
2082 if (Tok.isNot(tok::r_paren)) {
2083 CommaLocsTy CommaLocs;
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002084 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
2085 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002086 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002087 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002088 }
2089 ConstructorRParen = MatchRHSPunctuation(tok::r_paren, ConstructorLParen);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002090 if (ConstructorRParen.isInvalid()) {
2091 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002092 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002093 }
Sebastian Redldbef1bb2011-06-05 12:23:16 +00002094 } else if (Tok.is(tok::l_brace)) {
2095 // FIXME: Have to communicate the init-list to ActOnCXXNew.
2096 ParseBraceInitializer();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002097 }
2098
Sebastian Redlf53597f2009-03-15 17:47:39 +00002099 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2100 move_arg(PlacementArgs), PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +00002101 TypeIdParens, DeclaratorInfo, ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +00002102 move_arg(ConstructorArgs), ConstructorRParen);
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002103}
2104
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002105/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2106/// passed to ParseDeclaratorInternal.
2107///
2108/// direct-new-declarator:
2109/// '[' expression ']'
2110/// direct-new-declarator '[' constant-expression ']'
2111///
Chris Lattner59232d32009-01-04 21:25:24 +00002112void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002113 // Parse the array dimensions.
2114 bool first = true;
2115 while (Tok.is(tok::l_square)) {
2116 SourceLocation LLoc = ConsumeBracket();
John McCall60d7b3a2010-08-24 06:29:42 +00002117 ExprResult Size(first ? ParseExpression()
Sebastian Redl2f7ece72008-12-11 21:36:32 +00002118 : ParseConstantExpression());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002119 if (Size.isInvalid()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002120 // Recover
2121 SkipUntil(tok::r_square);
2122 return;
2123 }
2124 first = false;
2125
Sebastian Redlab197ba2009-02-09 18:23:29 +00002126 SourceLocation RLoc = MatchRHSPunctuation(tok::r_square, LLoc);
John McCall0b7e6782011-03-24 11:26:52 +00002127
2128 ParsedAttributes attrs(AttrFactory);
2129 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall7f040a92010-12-24 02:08:15 +00002130 /*static=*/false, /*star=*/false,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002131 Size.release(), LLoc, RLoc),
John McCall0b7e6782011-03-24 11:26:52 +00002132 attrs, RLoc);
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002133
Sebastian Redlab197ba2009-02-09 18:23:29 +00002134 if (RLoc.isInvalid())
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002135 return;
2136 }
2137}
2138
2139/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2140/// This ambiguity appears in the syntax of the C++ new operator.
2141///
2142/// new-expression:
2143/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2144/// new-initializer[opt]
2145///
2146/// new-placement:
2147/// '(' expression-list ')'
2148///
John McCallca0408f2010-08-23 06:44:23 +00002149bool Parser::ParseExpressionListOrTypeId(
Chris Lattner5f9e2722011-07-23 10:55:15 +00002150 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner59232d32009-01-04 21:25:24 +00002151 Declarator &D) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002152 // The '(' was already consumed.
2153 if (isTypeIdInParens()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002154 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlab197ba2009-02-09 18:23:29 +00002155 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002156 ParseDeclarator(D);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002157 return D.isInvalidType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002158 }
2159
2160 // It's not a type, it has to be an expression list.
2161 // Discard the comma locations - ActOnCXXNew has enough parameters.
2162 CommaLocsTy CommaLocs;
2163 return ParseExpressionList(PlacementArgs, CommaLocs);
2164}
2165
2166/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2167/// to free memory allocated by new.
2168///
Chris Lattner59232d32009-01-04 21:25:24 +00002169/// This method is called to parse the 'delete' expression after the optional
2170/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2171/// and "Start" is its location. Otherwise, "Start" is the location of the
2172/// 'delete' token.
2173///
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002174/// delete-expression:
2175/// '::'[opt] 'delete' cast-expression
2176/// '::'[opt] 'delete' '[' ']' cast-expression
John McCall60d7b3a2010-08-24 06:29:42 +00002177ExprResult
Chris Lattner59232d32009-01-04 21:25:24 +00002178Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2179 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2180 ConsumeToken(); // Consume 'delete'
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002181
2182 // Array delete?
2183 bool ArrayDelete = false;
2184 if (Tok.is(tok::l_square)) {
2185 ArrayDelete = true;
2186 SourceLocation LHS = ConsumeBracket();
2187 SourceLocation RHS = MatchRHSPunctuation(tok::r_square, LHS);
2188 if (RHS.isInvalid())
Sebastian Redl20df9b72008-12-11 22:51:44 +00002189 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002190 }
2191
John McCall60d7b3a2010-08-24 06:29:42 +00002192 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002193 if (Operand.isInvalid())
Sebastian Redl20df9b72008-12-11 22:51:44 +00002194 return move(Operand);
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002195
John McCall9ae2f072010-08-23 23:25:46 +00002196 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take());
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002197}
Sebastian Redl64b45f72009-01-05 20:52:13 +00002198
Mike Stump1eb44332009-09-09 15:08:12 +00002199static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002200 switch(kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002201 default: llvm_unreachable("Not a known unary type trait.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002202 case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002203 case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor;
John Wiegley20c0da72011-04-27 23:09:49 +00002204 case tok::kw___has_nothrow_copy: return UTT_HasNothrowCopy;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002205 case tok::kw___has_trivial_assign: return UTT_HasTrivialAssign;
Sean Hunt023df372011-05-09 18:22:59 +00002206 case tok::kw___has_trivial_constructor:
2207 return UTT_HasTrivialDefaultConstructor;
John Wiegley20c0da72011-04-27 23:09:49 +00002208 case tok::kw___has_trivial_copy: return UTT_HasTrivialCopy;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002209 case tok::kw___has_trivial_destructor: return UTT_HasTrivialDestructor;
2210 case tok::kw___has_virtual_destructor: return UTT_HasVirtualDestructor;
2211 case tok::kw___is_abstract: return UTT_IsAbstract;
John Wiegley20c0da72011-04-27 23:09:49 +00002212 case tok::kw___is_arithmetic: return UTT_IsArithmetic;
2213 case tok::kw___is_array: return UTT_IsArray;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002214 case tok::kw___is_class: return UTT_IsClass;
John Wiegley20c0da72011-04-27 23:09:49 +00002215 case tok::kw___is_complete_type: return UTT_IsCompleteType;
2216 case tok::kw___is_compound: return UTT_IsCompound;
2217 case tok::kw___is_const: return UTT_IsConst;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002218 case tok::kw___is_empty: return UTT_IsEmpty;
2219 case tok::kw___is_enum: return UTT_IsEnum;
John Wiegley20c0da72011-04-27 23:09:49 +00002220 case tok::kw___is_floating_point: return UTT_IsFloatingPoint;
2221 case tok::kw___is_function: return UTT_IsFunction;
2222 case tok::kw___is_fundamental: return UTT_IsFundamental;
2223 case tok::kw___is_integral: return UTT_IsIntegral;
John Wiegley20c0da72011-04-27 23:09:49 +00002224 case tok::kw___is_lvalue_reference: return UTT_IsLvalueReference;
2225 case tok::kw___is_member_function_pointer: return UTT_IsMemberFunctionPointer;
2226 case tok::kw___is_member_object_pointer: return UTT_IsMemberObjectPointer;
2227 case tok::kw___is_member_pointer: return UTT_IsMemberPointer;
2228 case tok::kw___is_object: return UTT_IsObject;
Chandler Carruth4e61ddd2011-04-23 10:47:20 +00002229 case tok::kw___is_literal: return UTT_IsLiteral;
Chandler Carruth38402812011-04-24 02:49:28 +00002230 case tok::kw___is_literal_type: return UTT_IsLiteral;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002231 case tok::kw___is_pod: return UTT_IsPOD;
John Wiegley20c0da72011-04-27 23:09:49 +00002232 case tok::kw___is_pointer: return UTT_IsPointer;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002233 case tok::kw___is_polymorphic: return UTT_IsPolymorphic;
John Wiegley20c0da72011-04-27 23:09:49 +00002234 case tok::kw___is_reference: return UTT_IsReference;
John Wiegley20c0da72011-04-27 23:09:49 +00002235 case tok::kw___is_rvalue_reference: return UTT_IsRvalueReference;
2236 case tok::kw___is_scalar: return UTT_IsScalar;
2237 case tok::kw___is_signed: return UTT_IsSigned;
2238 case tok::kw___is_standard_layout: return UTT_IsStandardLayout;
2239 case tok::kw___is_trivial: return UTT_IsTrivial;
Sean Huntfeb375d2011-05-13 00:31:07 +00002240 case tok::kw___is_trivially_copyable: return UTT_IsTriviallyCopyable;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002241 case tok::kw___is_union: return UTT_IsUnion;
John Wiegley20c0da72011-04-27 23:09:49 +00002242 case tok::kw___is_unsigned: return UTT_IsUnsigned;
2243 case tok::kw___is_void: return UTT_IsVoid;
2244 case tok::kw___is_volatile: return UTT_IsVolatile;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002245 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002246}
2247
2248static BinaryTypeTrait BinaryTypeTraitFromTokKind(tok::TokenKind kind) {
2249 switch(kind) {
Francois Pichet38c2b732010-12-07 00:55:57 +00002250 default: llvm_unreachable("Not a known binary type trait");
Francois Pichetf1872372010-12-08 22:35:30 +00002251 case tok::kw___is_base_of: return BTT_IsBaseOf;
John Wiegley20c0da72011-04-27 23:09:49 +00002252 case tok::kw___is_convertible: return BTT_IsConvertible;
2253 case tok::kw___is_same: return BTT_IsSame;
Francois Pichetf1872372010-12-08 22:35:30 +00002254 case tok::kw___builtin_types_compatible_p: return BTT_TypeCompatible;
Douglas Gregor9f361132011-01-27 20:28:01 +00002255 case tok::kw___is_convertible_to: return BTT_IsConvertibleTo;
Francois Pichet6ad6f282010-12-07 00:08:36 +00002256 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002257}
2258
John Wiegley21ff2e52011-04-28 00:16:57 +00002259static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2260 switch(kind) {
2261 default: llvm_unreachable("Not a known binary type trait");
2262 case tok::kw___array_rank: return ATT_ArrayRank;
2263 case tok::kw___array_extent: return ATT_ArrayExtent;
2264 }
2265}
2266
John Wiegley55262202011-04-25 06:54:41 +00002267static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2268 switch(kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002269 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegley55262202011-04-25 06:54:41 +00002270 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2271 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2272 }
2273}
2274
Sebastian Redl64b45f72009-01-05 20:52:13 +00002275/// ParseUnaryTypeTrait - Parse the built-in unary type-trait
2276/// pseudo-functions that allow implementation of the TR1/C++0x type traits
2277/// templates.
2278///
2279/// primary-expression:
2280/// [GNU] unary-type-trait '(' type-id ')'
2281///
John McCall60d7b3a2010-08-24 06:29:42 +00002282ExprResult Parser::ParseUnaryTypeTrait() {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002283 UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind());
2284 SourceLocation Loc = ConsumeToken();
2285
2286 SourceLocation LParen = Tok.getLocation();
2287 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
2288 return ExprError();
2289
2290 // FIXME: Error reporting absolutely sucks! If the this fails to parse a type
2291 // there will be cryptic errors about mismatched parentheses and missing
2292 // specifiers.
Douglas Gregor809070a2009-02-18 17:45:20 +00002293 TypeResult Ty = ParseTypeName();
Sebastian Redl64b45f72009-01-05 20:52:13 +00002294
2295 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen);
2296
Douglas Gregor809070a2009-02-18 17:45:20 +00002297 if (Ty.isInvalid())
2298 return ExprError();
2299
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002300 return Actions.ActOnUnaryTypeTrait(UTT, Loc, Ty.get(), RParen);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002301}
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002302
Francois Pichet6ad6f282010-12-07 00:08:36 +00002303/// ParseBinaryTypeTrait - Parse the built-in binary type-trait
2304/// pseudo-functions that allow implementation of the TR1/C++0x type traits
2305/// templates.
2306///
2307/// primary-expression:
2308/// [GNU] binary-type-trait '(' type-id ',' type-id ')'
2309///
2310ExprResult Parser::ParseBinaryTypeTrait() {
2311 BinaryTypeTrait BTT = BinaryTypeTraitFromTokKind(Tok.getKind());
2312 SourceLocation Loc = ConsumeToken();
2313
2314 SourceLocation LParen = Tok.getLocation();
2315 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
2316 return ExprError();
2317
2318 TypeResult LhsTy = ParseTypeName();
2319 if (LhsTy.isInvalid()) {
2320 SkipUntil(tok::r_paren);
2321 return ExprError();
2322 }
2323
2324 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2325 SkipUntil(tok::r_paren);
2326 return ExprError();
2327 }
2328
2329 TypeResult RhsTy = ParseTypeName();
2330 if (RhsTy.isInvalid()) {
2331 SkipUntil(tok::r_paren);
2332 return ExprError();
2333 }
2334
2335 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen);
2336
2337 return Actions.ActOnBinaryTypeTrait(BTT, Loc, LhsTy.get(), RhsTy.get(), RParen);
2338}
2339
John Wiegley21ff2e52011-04-28 00:16:57 +00002340/// ParseArrayTypeTrait - Parse the built-in array type-trait
2341/// pseudo-functions.
2342///
2343/// primary-expression:
2344/// [Embarcadero] '__array_rank' '(' type-id ')'
2345/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2346///
2347ExprResult Parser::ParseArrayTypeTrait() {
2348 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2349 SourceLocation Loc = ConsumeToken();
2350
2351 SourceLocation LParen = Tok.getLocation();
2352 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
2353 return ExprError();
2354
2355 TypeResult Ty = ParseTypeName();
2356 if (Ty.isInvalid()) {
2357 SkipUntil(tok::comma);
2358 SkipUntil(tok::r_paren);
2359 return ExprError();
2360 }
2361
2362 switch (ATT) {
2363 case ATT_ArrayRank: {
2364 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen);
2365 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), NULL, RParen);
2366 }
2367 case ATT_ArrayExtent: {
2368 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2369 SkipUntil(tok::r_paren);
2370 return ExprError();
2371 }
2372
2373 ExprResult DimExpr = ParseExpression();
2374 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen);
2375
2376 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(), RParen);
2377 }
2378 default:
2379 break;
2380 }
2381 return ExprError();
2382}
2383
John Wiegley55262202011-04-25 06:54:41 +00002384/// ParseExpressionTrait - Parse built-in expression-trait
2385/// pseudo-functions like __is_lvalue_expr( xxx ).
2386///
2387/// primary-expression:
2388/// [Embarcadero] expression-trait '(' expression ')'
2389///
2390ExprResult Parser::ParseExpressionTrait() {
2391 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2392 SourceLocation Loc = ConsumeToken();
2393
2394 SourceLocation LParen = Tok.getLocation();
2395 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
2396 return ExprError();
2397
2398 ExprResult Expr = ParseExpression();
2399
2400 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen);
2401
2402 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(), RParen);
2403}
2404
2405
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002406/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2407/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2408/// based on the context past the parens.
John McCall60d7b3a2010-08-24 06:29:42 +00002409ExprResult
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002410Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallb3d87482010-08-24 05:47:05 +00002411 ParsedType &CastTy,
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002412 SourceLocation LParenLoc,
2413 SourceLocation &RParenLoc) {
2414 assert(getLang().CPlusPlus && "Should only be called for C++!");
2415 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2416 assert(isTypeIdInParens() && "Not a type-id!");
2417
John McCall60d7b3a2010-08-24 06:29:42 +00002418 ExprResult Result(true);
John McCallb3d87482010-08-24 05:47:05 +00002419 CastTy = ParsedType();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002420
2421 // We need to disambiguate a very ugly part of the C++ syntax:
2422 //
2423 // (T())x; - type-id
2424 // (T())*x; - type-id
2425 // (T())/x; - expression
2426 // (T()); - expression
2427 //
2428 // The bad news is that we cannot use the specialized tentative parser, since
2429 // it can only verify that the thing inside the parens can be parsed as
2430 // type-id, it is not useful for determining the context past the parens.
2431 //
2432 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidisa558a892009-05-22 15:12:46 +00002433 // making any unnecessary Action calls.
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002434 //
2435 // It uses a scheme similar to parsing inline methods. The parenthesized
2436 // tokens are cached, the context that follows is determined (possibly by
2437 // parsing a cast-expression), and then we re-introduce the cached tokens
2438 // into the token stream and parse them appropriately.
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002439
Mike Stump1eb44332009-09-09 15:08:12 +00002440 ParenParseOption ParseAs;
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002441 CachedTokens Toks;
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002442
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002443 // Store the tokens of the parentheses. We will parse them after we determine
2444 // the context that follows them.
Argyrios Kyrtzidis14b91622010-04-23 21:20:12 +00002445 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002446 // We didn't find the ')' we expected.
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002447 MatchRHSPunctuation(tok::r_paren, LParenLoc);
2448 return ExprError();
2449 }
2450
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002451 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002452 ParseAs = CompoundLiteral;
2453 } else {
2454 bool NotCastExpr;
Eli Friedmanb53f08a2009-05-25 19:41:42 +00002455 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
2456 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
2457 NotCastExpr = true;
2458 } else {
2459 // Try parsing the cast-expression that may follow.
2460 // If it is not a cast-expression, NotCastExpr will be true and no token
2461 // will be consumed.
2462 Result = ParseCastExpression(false/*isUnaryExpression*/,
2463 false/*isAddressofOperand*/,
John McCallb3d87482010-08-24 05:47:05 +00002464 NotCastExpr,
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00002465 // type-id has priority.
2466 true/*isTypeCast*/);
Eli Friedmanb53f08a2009-05-25 19:41:42 +00002467 }
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002468
2469 // If we parsed a cast-expression, it's really a type-id, otherwise it's
2470 // an expression.
2471 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002472 }
2473
Mike Stump1eb44332009-09-09 15:08:12 +00002474 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002475 Toks.push_back(Tok);
2476 // Re-enter the stored parenthesized tokens into the token stream, so we may
2477 // parse them now.
2478 PP.EnterTokenStream(Toks.data(), Toks.size(),
2479 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
2480 // Drop the current token and bring the first cached one. It's the same token
2481 // as when we entered this function.
2482 ConsumeAnyToken();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002483
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002484 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00002485 // Parse the type declarator.
2486 DeclSpec DS(AttrFactory);
2487 ParseSpecifierQualifierList(DS);
2488 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2489 ParseDeclarator(DeclaratorInfo);
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002490
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002491 // Match the ')'.
2492 if (Tok.is(tok::r_paren))
2493 RParenLoc = ConsumeParen();
2494 else
2495 MatchRHSPunctuation(tok::r_paren, LParenLoc);
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002496
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002497 if (ParseAs == CompoundLiteral) {
2498 ExprType = CompoundLiteral;
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00002499 TypeResult Ty = ParseTypeName();
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002500 return ParseCompoundLiteralExpression(Ty.get(), LParenLoc, RParenLoc);
2501 }
Mike Stump1eb44332009-09-09 15:08:12 +00002502
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002503 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
2504 assert(ParseAs == CastExpr);
2505
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00002506 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002507 return ExprError();
2508
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002509 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002510 if (!Result.isInvalid())
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00002511 Result = Actions.ActOnCastExpr(getCurScope(), LParenLoc,
2512 DeclaratorInfo, CastTy,
2513 RParenLoc, Result.take());
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002514 return move(Result);
2515 }
Mike Stump1eb44332009-09-09 15:08:12 +00002516
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002517 // Not a compound literal, and not followed by a cast-expression.
2518 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002519
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002520 ExprType = SimpleExpr;
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002521 Result = ParseExpression();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002522 if (!Result.isInvalid() && Tok.is(tok::r_paren))
John McCall9ae2f072010-08-23 23:25:46 +00002523 Result = Actions.ActOnParenExpr(LParenLoc, Tok.getLocation(), Result.take());
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002524
2525 // Match the ')'.
2526 if (Result.isInvalid()) {
2527 SkipUntil(tok::r_paren);
2528 return ExprError();
2529 }
Mike Stump1eb44332009-09-09 15:08:12 +00002530
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002531 if (Tok.is(tok::r_paren))
2532 RParenLoc = ConsumeParen();
2533 else
2534 MatchRHSPunctuation(tok::r_paren, LParenLoc);
2535
2536 return move(Result);
2537}