blob: 2be44a4e77a0f984e471bcf4f2ef542735650147 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expression parsing implementation for C++.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner545f39e2009-01-29 05:15:15 +000014#include "clang/Parse/ParseDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "clang/Parse/Parser.h"
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +000016#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017using namespace clang;
18
Chris Lattnerd706dc82009-01-06 06:59:53 +000019/// ParseOptionalCXXScopeSpecifier - Parse global scope or
20/// nested-name-specifier if present. Returns true if a nested-name-specifier
21/// was parsed from the token stream. Note that this routine will not parse
22/// ::new or ::delete, it will just leave them in the token stream.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000023///
24/// '::'[opt] nested-name-specifier
25/// '::'
26///
27/// nested-name-specifier:
28/// type-name '::'
29/// namespace-name '::'
30/// nested-name-specifier identifier '::'
31/// nested-name-specifier 'template'[opt] simple-template-id '::' [TODO]
32///
Chris Lattnerd706dc82009-01-06 06:59:53 +000033bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS) {
Argiris Kirtzidis91c80dc2008-11-26 21:41:52 +000034 assert(getLang().CPlusPlus &&
Chris Lattner8376d2e2009-01-05 01:24:05 +000035 "Call sites of this function should be guarded by checking for C++");
Argiris Kirtzidis91c80dc2008-11-26 21:41:52 +000036
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000037 if (Tok.is(tok::annot_cxxscope)) {
Douglas Gregor041e9292009-03-26 23:56:24 +000038 SS.setScopeRep(Tok.getAnnotationValue());
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000039 SS.setRange(Tok.getAnnotationRange());
40 ConsumeToken();
Argiris Kirtzidis91c80dc2008-11-26 21:41:52 +000041 return true;
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000042 }
Chris Lattner99113932009-01-04 21:14:15 +000043
Douglas Gregor0c281a82009-02-25 19:37:18 +000044 bool HasScopeSpecifier = false;
45
Chris Lattner94a15bd2009-01-05 03:55:46 +000046 if (Tok.is(tok::coloncolon)) {
47 // ::new and ::delete aren't nested-name-specifiers.
48 tok::TokenKind NextKind = NextToken().getKind();
49 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
50 return false;
Chris Lattner2c301452009-01-05 00:13:00 +000051
Chris Lattner2c301452009-01-05 00:13:00 +000052 // '::' - Global scope qualifier.
Chris Lattner094f9a82009-01-05 02:07:19 +000053 SourceLocation CCLoc = ConsumeToken();
Chris Lattner094f9a82009-01-05 02:07:19 +000054 SS.setBeginLoc(CCLoc);
Douglas Gregor041e9292009-03-26 23:56:24 +000055 SS.setScopeRep(Actions.ActOnCXXGlobalScopeSpecifier(CurScope, CCLoc));
Chris Lattner094f9a82009-01-05 02:07:19 +000056 SS.setEndLoc(CCLoc);
Douglas Gregor0c281a82009-02-25 19:37:18 +000057 HasScopeSpecifier = true;
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000058 }
59
Douglas Gregor0c281a82009-02-25 19:37:18 +000060 while (true) {
61 // nested-name-specifier:
62 // type-name '::'
63 // namespace-name '::'
64 // nested-name-specifier identifier '::'
65 if (Tok.is(tok::identifier) && NextToken().is(tok::coloncolon)) {
66 // We have an identifier followed by a '::'. Lookup this name
67 // as the name in a nested-name-specifier.
68 IdentifierInfo *II = Tok.getIdentifierInfo();
69 SourceLocation IdLoc = ConsumeToken();
70 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
71 SourceLocation CCLoc = ConsumeToken();
72
73 if (!HasScopeSpecifier) {
74 SS.setBeginLoc(IdLoc);
75 HasScopeSpecifier = true;
76 }
77
78 if (SS.isInvalid())
79 continue;
80
Douglas Gregor041e9292009-03-26 23:56:24 +000081 SS.setScopeRep(
Douglas Gregor0c281a82009-02-25 19:37:18 +000082 Actions.ActOnCXXNestedNameSpecifier(CurScope, SS, IdLoc, CCLoc, *II));
83 SS.setEndLoc(CCLoc);
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000084 continue;
Douglas Gregor0c281a82009-02-25 19:37:18 +000085 }
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000086
Douglas Gregor0c281a82009-02-25 19:37:18 +000087 // nested-name-specifier:
88 // type-name '::'
89 // nested-name-specifier 'template'[opt] simple-template-id '::'
90 if ((Tok.is(tok::identifier) && NextToken().is(tok::less)) ||
91 Tok.is(tok::kw_template)) {
92 // Parse the optional 'template' keyword, then make sure we have
93 // 'identifier <' after it.
Douglas Gregor0c281a82009-02-25 19:37:18 +000094 if (Tok.is(tok::kw_template)) {
Douglas Gregoraabb8502009-03-31 00:43:58 +000095 SourceLocation TemplateKWLoc = ConsumeToken();
Douglas Gregor0c281a82009-02-25 19:37:18 +000096
97 if (Tok.isNot(tok::identifier)) {
98 Diag(Tok.getLocation(),
99 diag::err_id_after_template_in_nested_name_spec)
100 << SourceRange(TemplateKWLoc);
101 break;
102 }
103
104 if (NextToken().isNot(tok::less)) {
105 Diag(NextToken().getLocation(),
106 diag::err_less_after_template_name_in_nested_name_spec)
107 << Tok.getIdentifierInfo()->getName()
108 << SourceRange(TemplateKWLoc, Tok.getLocation());
109 break;
110 }
Douglas Gregoraabb8502009-03-31 00:43:58 +0000111
112 TemplateTy Template
113 = Actions.ActOnDependentTemplateName(TemplateKWLoc,
114 *Tok.getIdentifierInfo(),
115 Tok.getLocation(),
116 SS);
117 AnnotateTemplateIdToken(Template, TNK_Dependent_template_name,
118 &SS, TemplateKWLoc, false);
119 continue;
Douglas Gregor0c281a82009-02-25 19:37:18 +0000120 }
121
Douglas Gregordd13e842009-03-30 22:58:21 +0000122 TemplateTy Template;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000123 TemplateNameKind TNK = Actions.isTemplateName(*Tok.getIdentifierInfo(),
124 CurScope, Template, &SS);
Douglas Gregor0c281a82009-02-25 19:37:18 +0000125 if (TNK) {
126 // We have found a template name, so annotate this this token
127 // with a template-id annotation. We do not permit the
128 // template-id to be translated into a type annotation,
129 // because some clients (e.g., the parsing of class template
130 // specializations) still want to see the original template-id
131 // token.
Douglas Gregoraabb8502009-03-31 00:43:58 +0000132 AnnotateTemplateIdToken(Template, TNK, &SS, SourceLocation(), false);
Douglas Gregor0c281a82009-02-25 19:37:18 +0000133 continue;
134 }
135 }
136
137 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
138 // We have
139 //
140 // simple-template-id '::'
141 //
142 // So we need to check whether the simple-template-id is of the
Douglas Gregoraabb8502009-03-31 00:43:58 +0000143 // right kind (it should name a type or be dependent), and then
144 // convert it into a type within the nested-name-specifier.
Douglas Gregor0c281a82009-02-25 19:37:18 +0000145 TemplateIdAnnotation *TemplateId
146 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
147
Douglas Gregoraabb8502009-03-31 00:43:58 +0000148 if (TemplateId->Kind == TNK_Type_template ||
149 TemplateId->Kind == TNK_Dependent_template_name) {
Douglas Gregord7cb0372009-04-01 21:51:26 +0000150 AnnotateTemplateIdTokenAsType(&SS);
Douglas Gregor96b6df92009-05-14 00:28:11 +0000151 SS.setScopeRep(0);
Douglas Gregor0c281a82009-02-25 19:37:18 +0000152
153 assert(Tok.is(tok::annot_typename) &&
154 "AnnotateTemplateIdTokenAsType isn't working");
Douglas Gregor0c281a82009-02-25 19:37:18 +0000155 Token TypeToken = Tok;
156 ConsumeToken();
157 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
158 SourceLocation CCLoc = ConsumeToken();
159
160 if (!HasScopeSpecifier) {
161 SS.setBeginLoc(TypeToken.getLocation());
162 HasScopeSpecifier = true;
163 }
Douglas Gregord7cb0372009-04-01 21:51:26 +0000164
165 if (TypeToken.getAnnotationValue())
166 SS.setScopeRep(
167 Actions.ActOnCXXNestedNameSpecifier(CurScope, SS,
168 TypeToken.getAnnotationValue(),
169 TypeToken.getAnnotationRange(),
170 CCLoc));
171 else
172 SS.setScopeRep(0);
Douglas Gregor0c281a82009-02-25 19:37:18 +0000173 SS.setEndLoc(CCLoc);
174 continue;
175 } else
Douglas Gregoraabb8502009-03-31 00:43:58 +0000176 assert(false && "FIXME: Only type template names supported here");
Douglas Gregor0c281a82009-02-25 19:37:18 +0000177 }
178
179 // We don't have any tokens that form the beginning of a
180 // nested-name-specifier, so we're done.
181 break;
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000182 }
Douglas Gregor0c281a82009-02-25 19:37:18 +0000183
184 return HasScopeSpecifier;
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000185}
186
187/// ParseCXXIdExpression - Handle id-expression.
188///
189/// id-expression:
190/// unqualified-id
191/// qualified-id
192///
193/// unqualified-id:
194/// identifier
195/// operator-function-id
196/// conversion-function-id [TODO]
197/// '~' class-name [TODO]
198/// template-id [TODO]
199///
200/// qualified-id:
201/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
202/// '::' identifier
203/// '::' operator-function-id
204/// '::' template-id [TODO]
205///
206/// nested-name-specifier:
207/// type-name '::'
208/// namespace-name '::'
209/// nested-name-specifier identifier '::'
210/// nested-name-specifier 'template'[opt] simple-template-id '::' [TODO]
211///
212/// NOTE: The standard specifies that, for qualified-id, the parser does not
213/// expect:
214///
215/// '::' conversion-function-id
216/// '::' '~' class-name
217///
218/// This may cause a slight inconsistency on diagnostics:
219///
220/// class C {};
221/// namespace A {}
222/// void f() {
223/// :: A :: ~ C(); // Some Sema error about using destructor with a
224/// // namespace.
225/// :: ~ C(); // Some Parser error like 'unexpected ~'.
226/// }
227///
228/// We simplify the parser a bit and make it work like:
229///
230/// qualified-id:
231/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
232/// '::' unqualified-id
233///
234/// That way Sema can handle and report similar errors for namespaces and the
235/// global scope.
236///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000237/// The isAddressOfOperand parameter indicates that this id-expression is a
238/// direct operand of the address-of operator. This is, besides member contexts,
239/// the only place where a qualified-id naming a non-static class member may
240/// appear.
241///
242Parser::OwningExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000243 // qualified-id:
244 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
245 // '::' unqualified-id
246 //
247 CXXScopeSpec SS;
Chris Lattnerd706dc82009-01-06 06:59:53 +0000248 ParseOptionalCXXScopeSpecifier(SS);
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000249
250 // unqualified-id:
251 // identifier
252 // operator-function-id
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000253 // conversion-function-id
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000254 // '~' class-name [TODO]
255 // template-id [TODO]
256 //
257 switch (Tok.getKind()) {
258 default:
Sebastian Redl39d4f022008-12-11 22:51:44 +0000259 return ExprError(Diag(Tok, diag::err_expected_unqualified_id));
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000260
261 case tok::identifier: {
262 // Consume the identifier so that we can see if it is followed by a '('.
263 IdentifierInfo &II = *Tok.getIdentifierInfo();
264 SourceLocation L = ConsumeToken();
Sebastian Redl0c9da212009-02-03 20:19:35 +0000265 return Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren),
266 &SS, isAddressOfOperand);
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000267 }
268
269 case tok::kw_operator: {
270 SourceLocation OperatorLoc = Tok.getLocation();
Chris Lattner8376d2e2009-01-05 01:24:05 +0000271 if (OverloadedOperatorKind Op = TryParseOperatorFunctionId())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000272 return Actions.ActOnCXXOperatorFunctionIdExpr(
Sebastian Redl0c9da212009-02-03 20:19:35 +0000273 CurScope, OperatorLoc, Op, Tok.is(tok::l_paren), SS,
274 isAddressOfOperand);
Chris Lattner8376d2e2009-01-05 01:24:05 +0000275 if (TypeTy *Type = ParseConversionFunctionId())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000276 return Actions.ActOnCXXConversionFunctionExpr(CurScope, OperatorLoc, Type,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000277 Tok.is(tok::l_paren), SS,
278 isAddressOfOperand);
Sebastian Redl39d4f022008-12-11 22:51:44 +0000279
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000280 // We already complained about a bad conversion-function-id,
281 // above.
Sebastian Redl39d4f022008-12-11 22:51:44 +0000282 return ExprError();
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000283 }
284
285 } // switch.
286
287 assert(0 && "The switch was supposed to take care everything.");
288}
289
Chris Lattner4b009652007-07-25 00:24:17 +0000290/// ParseCXXCasts - This handles the various ways to cast expressions to another
291/// type.
292///
293/// postfix-expression: [C++ 5.2p1]
294/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
295/// 'static_cast' '<' type-name '>' '(' expression ')'
296/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
297/// 'const_cast' '<' type-name '>' '(' expression ')'
298///
Sebastian Redl39d4f022008-12-11 22:51:44 +0000299Parser::OwningExprResult Parser::ParseCXXCasts() {
Chris Lattner4b009652007-07-25 00:24:17 +0000300 tok::TokenKind Kind = Tok.getKind();
301 const char *CastName = 0; // For error messages
302
303 switch (Kind) {
304 default: assert(0 && "Unknown C++ cast!"); abort();
305 case tok::kw_const_cast: CastName = "const_cast"; break;
306 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
307 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
308 case tok::kw_static_cast: CastName = "static_cast"; break;
309 }
310
311 SourceLocation OpLoc = ConsumeToken();
312 SourceLocation LAngleBracketLoc = Tok.getLocation();
313
314 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redl39d4f022008-12-11 22:51:44 +0000315 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000316
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000317 TypeResult CastTy = ParseTypeName();
Chris Lattner4b009652007-07-25 00:24:17 +0000318 SourceLocation RAngleBracketLoc = Tok.getLocation();
319
Chris Lattnerf006a222008-11-18 07:48:38 +0000320 if (ExpectAndConsume(tok::greater, diag::err_expected_greater))
Sebastian Redl39d4f022008-12-11 22:51:44 +0000321 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<");
Chris Lattner4b009652007-07-25 00:24:17 +0000322
323 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
324
Argiris Kirtzidisd61a2f72009-05-22 10:23:16 +0000325 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, CastName))
326 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000327
Argiris Kirtzidisd61a2f72009-05-22 10:23:16 +0000328 OwningExprResult Result = ParseExpression();
329
330 // Match the ')'.
331 if (Result.isInvalid())
332 SkipUntil(tok::r_paren);
333
334 if (Tok.is(tok::r_paren))
335 RParenLoc = ConsumeParen();
336 else
337 MatchRHSPunctuation(tok::r_paren, LParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000338
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000339 if (!Result.isInvalid() && !CastTy.isInvalid())
Douglas Gregor21a04f32008-10-27 19:41:14 +0000340 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000341 LAngleBracketLoc, CastTy.get(),
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000342 RAngleBracketLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000343 LParenLoc, move(Result), RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000344
Sebastian Redl39d4f022008-12-11 22:51:44 +0000345 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +0000346}
347
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000348/// ParseCXXTypeid - This handles the C++ typeid expression.
349///
350/// postfix-expression: [C++ 5.2p1]
351/// 'typeid' '(' expression ')'
352/// 'typeid' '(' type-id ')'
353///
Sebastian Redl39d4f022008-12-11 22:51:44 +0000354Parser::OwningExprResult Parser::ParseCXXTypeid() {
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000355 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
356
357 SourceLocation OpLoc = ConsumeToken();
358 SourceLocation LParenLoc = Tok.getLocation();
359 SourceLocation RParenLoc;
360
361 // typeid expressions are always parenthesized.
362 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
363 "typeid"))
Sebastian Redl39d4f022008-12-11 22:51:44 +0000364 return ExprError();
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000365
Sebastian Redl62261042008-12-09 20:22:58 +0000366 OwningExprResult Result(Actions);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000367
368 if (isTypeIdInParens()) {
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000369 TypeResult Ty = ParseTypeName();
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000370
371 // Match the ')'.
372 MatchRHSPunctuation(tok::r_paren, LParenLoc);
373
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000374 if (Ty.isInvalid())
Sebastian Redl39d4f022008-12-11 22:51:44 +0000375 return ExprError();
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000376
377 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000378 Ty.get(), RParenLoc);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000379 } else {
Douglas Gregor98189262009-06-19 23:52:42 +0000380 // C++0x [expr.typeid]p3:
381 // When typeid is applied to an expression other than an lvalue of a
382 // polymorphic class type [...] The expression is an unevaluated
383 // operand (Clause 5).
384 //
385 // Note that we can't tell whether the expression is an lvalue of a
386 // polymorphic class type until after we've parsed the expression, so
Douglas Gregora8b2fbf2009-06-22 20:57:11 +0000387 // we the expression is potentially potentially evaluated.
388 EnterExpressionEvaluationContext Unevaluated(Actions,
389 Action::PotentiallyPotentiallyEvaluated);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000390 Result = ParseExpression();
391
392 // Match the ')'.
Sebastian Redlbb4dae72008-12-09 13:15:23 +0000393 if (Result.isInvalid())
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000394 SkipUntil(tok::r_paren);
395 else {
396 MatchRHSPunctuation(tok::r_paren, LParenLoc);
397
398 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Sebastian Redl6f1ee232008-12-10 00:02:53 +0000399 Result.release(), RParenLoc);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000400 }
401 }
402
Sebastian Redl39d4f022008-12-11 22:51:44 +0000403 return move(Result);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000404}
405
Chris Lattner4b009652007-07-25 00:24:17 +0000406/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
407///
408/// boolean-literal: [C++ 2.13.5]
409/// 'true'
410/// 'false'
Sebastian Redl39d4f022008-12-11 22:51:44 +0000411Parser::OwningExprResult Parser::ParseCXXBoolLiteral() {
Chris Lattner4b009652007-07-25 00:24:17 +0000412 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000413 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Chris Lattner4b009652007-07-25 00:24:17 +0000414}
Chris Lattnera7447ba2008-02-26 00:51:44 +0000415
416/// ParseThrowExpression - This handles the C++ throw expression.
417///
418/// throw-expression: [C++ 15]
419/// 'throw' assignment-expression[opt]
Sebastian Redl39d4f022008-12-11 22:51:44 +0000420Parser::OwningExprResult Parser::ParseThrowExpression() {
Chris Lattnera7447ba2008-02-26 00:51:44 +0000421 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnera7447ba2008-02-26 00:51:44 +0000422 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redl39d4f022008-12-11 22:51:44 +0000423
Chris Lattner6b8842d2008-04-06 06:02:23 +0000424 // If the current token isn't the start of an assignment-expression,
425 // then the expression is not present. This handles things like:
426 // "C ? throw : (void)42", which is crazy but legal.
427 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
428 case tok::semi:
429 case tok::r_paren:
430 case tok::r_square:
431 case tok::r_brace:
432 case tok::colon:
433 case tok::comma:
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000434 return Actions.ActOnCXXThrow(ThrowLoc, ExprArg(Actions));
Chris Lattnera7447ba2008-02-26 00:51:44 +0000435
Chris Lattner6b8842d2008-04-06 06:02:23 +0000436 default:
Sebastian Redl14ca7412008-12-11 21:36:32 +0000437 OwningExprResult Expr(ParseAssignmentExpression());
Sebastian Redl39d4f022008-12-11 22:51:44 +0000438 if (Expr.isInvalid()) return move(Expr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000439 return Actions.ActOnCXXThrow(ThrowLoc, move(Expr));
Chris Lattner6b8842d2008-04-06 06:02:23 +0000440 }
Chris Lattnera7447ba2008-02-26 00:51:44 +0000441}
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000442
443/// ParseCXXThis - This handles the C++ 'this' pointer.
444///
445/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
446/// a non-lvalue expression whose value is the address of the object for which
447/// the function is called.
Sebastian Redl39d4f022008-12-11 22:51:44 +0000448Parser::OwningExprResult Parser::ParseCXXThis() {
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000449 assert(Tok.is(tok::kw_this) && "Not 'this'!");
450 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000451 return Actions.ActOnCXXThis(ThisLoc);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000452}
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000453
454/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
455/// Can be interpreted either as function-style casting ("int(x)")
456/// or class type construction ("ClassType(x,y,z)")
457/// or creation of a value-initialized type ("int()").
458///
459/// postfix-expression: [C++ 5.2p1]
460/// simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
461/// typename-specifier '(' expression-list[opt] ')' [TODO]
462///
Sebastian Redl39d4f022008-12-11 22:51:44 +0000463Parser::OwningExprResult
464Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000465 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
Douglas Gregor10a18fc2009-01-26 22:44:13 +0000466 TypeTy *TypeRep = Actions.ActOnTypeName(CurScope, DeclaratorInfo).get();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000467
468 assert(Tok.is(tok::l_paren) && "Expected '('!");
469 SourceLocation LParenLoc = ConsumeParen();
470
Sebastian Redl6008ac32008-11-25 22:21:31 +0000471 ExprVector Exprs(Actions);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000472 CommaLocsTy CommaLocs;
473
474 if (Tok.isNot(tok::r_paren)) {
475 if (ParseExpressionList(Exprs, CommaLocs)) {
476 SkipUntil(tok::r_paren);
Sebastian Redl39d4f022008-12-11 22:51:44 +0000477 return ExprError();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000478 }
479 }
480
481 // Match the ')'.
482 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
483
484 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
485 "Unexpected number of commas!");
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000486 return Actions.ActOnCXXTypeConstructExpr(DS.getSourceRange(), TypeRep,
487 LParenLoc, move_arg(Exprs),
Jay Foad9e6bef42009-05-21 09:52:38 +0000488 CommaLocs.data(), RParenLoc);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000489}
490
Argiris Kirtzidis873f2782008-09-09 20:38:47 +0000491/// ParseCXXCondition - if/switch/while/for condition expression.
492///
493/// condition:
494/// expression
495/// type-specifier-seq declarator '=' assignment-expression
496/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
497/// '=' assignment-expression
498///
Sebastian Redl14ca7412008-12-11 21:36:32 +0000499Parser::OwningExprResult Parser::ParseCXXCondition() {
Argiris Kirtzidis88527fb2008-10-05 15:03:47 +0000500 if (!isCXXConditionDeclaration())
Argiris Kirtzidis873f2782008-09-09 20:38:47 +0000501 return ParseExpression(); // expression
502
503 SourceLocation StartLoc = Tok.getLocation();
504
505 // type-specifier-seq
506 DeclSpec DS;
507 ParseSpecifierQualifierList(DS);
508
509 // declarator
510 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
511 ParseDeclarator(DeclaratorInfo);
512
513 // simple-asm-expr[opt]
514 if (Tok.is(tok::kw_asm)) {
Sebastian Redl0c986032009-02-09 18:23:29 +0000515 SourceLocation Loc;
516 OwningExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redlbb4dae72008-12-09 13:15:23 +0000517 if (AsmLabel.isInvalid()) {
Argiris Kirtzidis873f2782008-09-09 20:38:47 +0000518 SkipUntil(tok::semi);
Sebastian Redl14ca7412008-12-11 21:36:32 +0000519 return ExprError();
Argiris Kirtzidis873f2782008-09-09 20:38:47 +0000520 }
Sebastian Redl6f1ee232008-12-10 00:02:53 +0000521 DeclaratorInfo.setAsmLabel(AsmLabel.release());
Sebastian Redl0c986032009-02-09 18:23:29 +0000522 DeclaratorInfo.SetRangeEnd(Loc);
Argiris Kirtzidis873f2782008-09-09 20:38:47 +0000523 }
524
525 // If attributes are present, parse them.
Sebastian Redl0c986032009-02-09 18:23:29 +0000526 if (Tok.is(tok::kw___attribute)) {
527 SourceLocation Loc;
528 AttributeList *AttrList = ParseAttributes(&Loc);
529 DeclaratorInfo.AddAttributes(AttrList, Loc);
530 }
Argiris Kirtzidis873f2782008-09-09 20:38:47 +0000531
532 // '=' assignment-expression
533 if (Tok.isNot(tok::equal))
Sebastian Redl14ca7412008-12-11 21:36:32 +0000534 return ExprError(Diag(Tok, diag::err_expected_equal_after_declarator));
Argiris Kirtzidis873f2782008-09-09 20:38:47 +0000535 SourceLocation EqualLoc = ConsumeToken();
Sebastian Redl14ca7412008-12-11 21:36:32 +0000536 OwningExprResult AssignExpr(ParseAssignmentExpression());
Sebastian Redlbb4dae72008-12-09 13:15:23 +0000537 if (AssignExpr.isInvalid())
Sebastian Redl14ca7412008-12-11 21:36:32 +0000538 return ExprError();
539
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000540 return Actions.ActOnCXXConditionDeclarationExpr(CurScope, StartLoc,
541 DeclaratorInfo,EqualLoc,
542 move(AssignExpr));
Argiris Kirtzidis873f2782008-09-09 20:38:47 +0000543}
544
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000545/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
546/// This should only be called when the current token is known to be part of
547/// simple-type-specifier.
548///
549/// simple-type-specifier:
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000550/// '::'[opt] nested-name-specifier[opt] type-name
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000551/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
552/// char
553/// wchar_t
554/// bool
555/// short
556/// int
557/// long
558/// signed
559/// unsigned
560/// float
561/// double
562/// void
563/// [GNU] typeof-specifier
564/// [C++0x] auto [TODO]
565///
566/// type-name:
567/// class-name
568/// enum-name
569/// typedef-name
570///
571void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
572 DS.SetRangeStart(Tok.getLocation());
573 const char *PrevSpec;
574 SourceLocation Loc = Tok.getLocation();
575
576 switch (Tok.getKind()) {
Chris Lattner2c301452009-01-05 00:13:00 +0000577 case tok::identifier: // foo::bar
578 case tok::coloncolon: // ::foo::bar
579 assert(0 && "Annotation token should already be formed!");
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000580 default:
581 assert(0 && "Not a simple-type-specifier token!");
582 abort();
Chris Lattner2c301452009-01-05 00:13:00 +0000583
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000584 // type-name
Chris Lattner5d7eace2009-01-06 05:06:21 +0000585 case tok::annot_typename: {
Douglas Gregora60c62e2009-02-09 15:09:02 +0000586 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000587 Tok.getAnnotationValue());
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000588 break;
589 }
590
591 // builtin types
592 case tok::kw_short:
593 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec);
594 break;
595 case tok::kw_long:
596 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec);
597 break;
598 case tok::kw_signed:
599 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec);
600 break;
601 case tok::kw_unsigned:
602 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec);
603 break;
604 case tok::kw_void:
605 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec);
606 break;
607 case tok::kw_char:
608 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec);
609 break;
610 case tok::kw_int:
611 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec);
612 break;
613 case tok::kw_float:
614 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec);
615 break;
616 case tok::kw_double:
617 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec);
618 break;
619 case tok::kw_wchar_t:
620 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec);
621 break;
622 case tok::kw_bool:
623 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec);
624 break;
625
626 // GNU typeof support.
627 case tok::kw_typeof:
628 ParseTypeofSpecifier(DS);
Douglas Gregor1ba5cb32009-04-01 22:41:11 +0000629 DS.Finish(Diags, PP);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000630 return;
631 }
Chris Lattner5d7eace2009-01-06 05:06:21 +0000632 if (Tok.is(tok::annot_typename))
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000633 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
634 else
635 DS.SetRangeEnd(Tok.getLocation());
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000636 ConsumeToken();
Douglas Gregor1ba5cb32009-04-01 22:41:11 +0000637 DS.Finish(Diags, PP);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000638}
Douglas Gregore60e5d32008-11-06 22:13:31 +0000639
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000640/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
641/// [dcl.name]), which is a non-empty sequence of type-specifiers,
642/// e.g., "const short int". Note that the DeclSpec is *not* finished
643/// by parsing the type-specifier-seq, because these sequences are
644/// typically followed by some form of declarator. Returns true and
645/// emits diagnostics if this is not a type-specifier-seq, false
646/// otherwise.
647///
648/// type-specifier-seq: [C++ 8.1]
649/// type-specifier type-specifier-seq[opt]
650///
651bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
652 DS.SetRangeStart(Tok.getLocation());
653 const char *PrevSpec = 0;
654 int isInvalid = 0;
655
656 // Parse one or more of the type specifiers.
Chris Lattnerd706dc82009-01-06 06:59:53 +0000657 if (!ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec)) {
Chris Lattnerf006a222008-11-18 07:48:38 +0000658 Diag(Tok, diag::err_operator_missing_type_specifier);
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000659 return true;
660 }
Chris Lattnerd706dc82009-01-06 06:59:53 +0000661
Ted Kremenek34034d72009-01-06 19:17:58 +0000662 while (ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec)) ;
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000663
664 return false;
665}
666
Douglas Gregor682a8cf2008-11-17 16:14:12 +0000667/// TryParseOperatorFunctionId - Attempts to parse a C++ overloaded
Douglas Gregore60e5d32008-11-06 22:13:31 +0000668/// operator name (C++ [over.oper]). If successful, returns the
669/// predefined identifier that corresponds to that overloaded
670/// operator. Otherwise, returns NULL and does not consume any tokens.
671///
672/// operator-function-id: [C++ 13.5]
673/// 'operator' operator
674///
675/// operator: one of
676/// new delete new[] delete[]
677/// + - * / % ^ & | ~
678/// ! = < > += -= *= /= %=
679/// ^= &= |= << >> >>= <<= == !=
680/// <= >= && || ++ -- , ->* ->
681/// () []
Sebastian Redl0c986032009-02-09 18:23:29 +0000682OverloadedOperatorKind
683Parser::TryParseOperatorFunctionId(SourceLocation *EndLoc) {
Argiris Kirtzidisa9d57b62008-11-07 15:54:02 +0000684 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
Sebastian Redl0c986032009-02-09 18:23:29 +0000685 SourceLocation Loc;
Douglas Gregore60e5d32008-11-06 22:13:31 +0000686
687 OverloadedOperatorKind Op = OO_None;
688 switch (NextToken().getKind()) {
689 case tok::kw_new:
690 ConsumeToken(); // 'operator'
Sebastian Redl0c986032009-02-09 18:23:29 +0000691 Loc = ConsumeToken(); // 'new'
Douglas Gregore60e5d32008-11-06 22:13:31 +0000692 if (Tok.is(tok::l_square)) {
693 ConsumeBracket(); // '['
Sebastian Redl0c986032009-02-09 18:23:29 +0000694 Loc = Tok.getLocation();
Douglas Gregore60e5d32008-11-06 22:13:31 +0000695 ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); // ']'
696 Op = OO_Array_New;
697 } else {
698 Op = OO_New;
699 }
Sebastian Redl0c986032009-02-09 18:23:29 +0000700 if (EndLoc)
701 *EndLoc = Loc;
Douglas Gregor96a32dd2008-11-18 14:39:36 +0000702 return Op;
Douglas Gregore60e5d32008-11-06 22:13:31 +0000703
704 case tok::kw_delete:
705 ConsumeToken(); // 'operator'
Sebastian Redl0c986032009-02-09 18:23:29 +0000706 Loc = ConsumeToken(); // 'delete'
Douglas Gregore60e5d32008-11-06 22:13:31 +0000707 if (Tok.is(tok::l_square)) {
708 ConsumeBracket(); // '['
Sebastian Redl0c986032009-02-09 18:23:29 +0000709 Loc = Tok.getLocation();
Douglas Gregore60e5d32008-11-06 22:13:31 +0000710 ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); // ']'
711 Op = OO_Array_Delete;
712 } else {
713 Op = OO_Delete;
714 }
Sebastian Redl0c986032009-02-09 18:23:29 +0000715 if (EndLoc)
716 *EndLoc = Loc;
Douglas Gregor96a32dd2008-11-18 14:39:36 +0000717 return Op;
Douglas Gregore60e5d32008-11-06 22:13:31 +0000718
Douglas Gregor9c6210b2008-11-10 13:38:07 +0000719#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
Douglas Gregore60e5d32008-11-06 22:13:31 +0000720 case tok::Token: Op = OO_##Name; break;
Douglas Gregor9c6210b2008-11-10 13:38:07 +0000721#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
Douglas Gregore60e5d32008-11-06 22:13:31 +0000722#include "clang/Basic/OperatorKinds.def"
723
724 case tok::l_paren:
725 ConsumeToken(); // 'operator'
726 ConsumeParen(); // '('
Sebastian Redl0c986032009-02-09 18:23:29 +0000727 Loc = Tok.getLocation();
Douglas Gregore60e5d32008-11-06 22:13:31 +0000728 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); // ')'
Sebastian Redl0c986032009-02-09 18:23:29 +0000729 if (EndLoc)
730 *EndLoc = Loc;
Douglas Gregor96a32dd2008-11-18 14:39:36 +0000731 return OO_Call;
Douglas Gregore60e5d32008-11-06 22:13:31 +0000732
733 case tok::l_square:
734 ConsumeToken(); // 'operator'
735 ConsumeBracket(); // '['
Sebastian Redl0c986032009-02-09 18:23:29 +0000736 Loc = Tok.getLocation();
Douglas Gregore60e5d32008-11-06 22:13:31 +0000737 ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); // ']'
Sebastian Redl0c986032009-02-09 18:23:29 +0000738 if (EndLoc)
739 *EndLoc = Loc;
Douglas Gregor96a32dd2008-11-18 14:39:36 +0000740 return OO_Subscript;
Douglas Gregore60e5d32008-11-06 22:13:31 +0000741
742 default:
Douglas Gregor96a32dd2008-11-18 14:39:36 +0000743 return OO_None;
Douglas Gregore60e5d32008-11-06 22:13:31 +0000744 }
745
Douglas Gregor682a8cf2008-11-17 16:14:12 +0000746 ConsumeToken(); // 'operator'
Sebastian Redl0c986032009-02-09 18:23:29 +0000747 Loc = ConsumeAnyToken(); // the operator itself
748 if (EndLoc)
749 *EndLoc = Loc;
Douglas Gregor96a32dd2008-11-18 14:39:36 +0000750 return Op;
Douglas Gregore60e5d32008-11-06 22:13:31 +0000751}
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000752
753/// ParseConversionFunctionId - Parse a C++ conversion-function-id,
754/// which expresses the name of a user-defined conversion operator
755/// (C++ [class.conv.fct]p1). Returns the type that this operator is
756/// specifying a conversion for, or NULL if there was an error.
757///
758/// conversion-function-id: [C++ 12.3.2]
759/// operator conversion-type-id
760///
761/// conversion-type-id:
762/// type-specifier-seq conversion-declarator[opt]
763///
764/// conversion-declarator:
765/// ptr-operator conversion-declarator[opt]
Sebastian Redl0c986032009-02-09 18:23:29 +0000766Parser::TypeTy *Parser::ParseConversionFunctionId(SourceLocation *EndLoc) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000767 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
768 ConsumeToken(); // 'operator'
769
770 // Parse the type-specifier-seq.
771 DeclSpec DS;
772 if (ParseCXXTypeSpecifierSeq(DS))
773 return 0;
774
775 // Parse the conversion-declarator, which is merely a sequence of
776 // ptr-operators.
777 Declarator D(DS, Declarator::TypeNameContext);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000778 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
Sebastian Redl0c986032009-02-09 18:23:29 +0000779 if (EndLoc)
780 *EndLoc = D.getSourceRange().getEnd();
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000781
782 // Finish up the type.
783 Action::TypeResult Result = Actions.ActOnTypeName(CurScope, D);
Douglas Gregor10a18fc2009-01-26 22:44:13 +0000784 if (Result.isInvalid())
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000785 return 0;
786 else
Douglas Gregor10a18fc2009-01-26 22:44:13 +0000787 return Result.get();
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000788}
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000789
790/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
791/// memory in a typesafe manner and call constructors.
Chris Lattnere7de3612009-01-04 21:25:24 +0000792///
793/// This method is called to parse the new expression after the optional :: has
794/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
795/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000796///
797/// new-expression:
798/// '::'[opt] 'new' new-placement[opt] new-type-id
799/// new-initializer[opt]
800/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
801/// new-initializer[opt]
802///
803/// new-placement:
804/// '(' expression-list ')'
805///
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000806/// new-type-id:
807/// type-specifier-seq new-declarator[opt]
808///
809/// new-declarator:
810/// ptr-operator new-declarator[opt]
811/// direct-new-declarator
812///
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000813/// new-initializer:
814/// '(' expression-list[opt] ')'
815/// [C++0x] braced-init-list [TODO]
816///
Chris Lattnere7de3612009-01-04 21:25:24 +0000817Parser::OwningExprResult
818Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
819 assert(Tok.is(tok::kw_new) && "expected 'new' token");
820 ConsumeToken(); // Consume 'new'
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000821
822 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
823 // second form of new-expression. It can't be a new-type-id.
824
Sebastian Redl6008ac32008-11-25 22:21:31 +0000825 ExprVector PlacementArgs(Actions);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000826 SourceLocation PlacementLParen, PlacementRParen;
827
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000828 bool ParenTypeId;
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000829 DeclSpec DS;
830 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000831 if (Tok.is(tok::l_paren)) {
832 // If it turns out to be a placement, we change the type location.
833 PlacementLParen = ConsumeParen();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000834 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
835 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl39d4f022008-12-11 22:51:44 +0000836 return ExprError();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000837 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000838
839 PlacementRParen = MatchRHSPunctuation(tok::r_paren, PlacementLParen);
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000840 if (PlacementRParen.isInvalid()) {
841 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl39d4f022008-12-11 22:51:44 +0000842 return ExprError();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000843 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000844
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000845 if (PlacementArgs.empty()) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000846 // Reset the placement locations. There was no placement.
847 PlacementLParen = PlacementRParen = SourceLocation();
848 ParenTypeId = true;
849 } else {
850 // We still need the type.
851 if (Tok.is(tok::l_paren)) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000852 SourceLocation LParen = ConsumeParen();
853 ParseSpecifierQualifierList(DS);
Sebastian Redl0c986032009-02-09 18:23:29 +0000854 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000855 ParseDeclarator(DeclaratorInfo);
856 MatchRHSPunctuation(tok::r_paren, LParen);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000857 ParenTypeId = true;
858 } else {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000859 if (ParseCXXTypeSpecifierSeq(DS))
860 DeclaratorInfo.setInvalidType(true);
Sebastian Redl0c986032009-02-09 18:23:29 +0000861 else {
862 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000863 ParseDeclaratorInternal(DeclaratorInfo,
864 &Parser::ParseDirectNewDeclarator);
Sebastian Redl0c986032009-02-09 18:23:29 +0000865 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000866 ParenTypeId = false;
867 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000868 }
869 } else {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000870 // A new-type-id is a simplified type-id, where essentially the
871 // direct-declarator is replaced by a direct-new-declarator.
872 if (ParseCXXTypeSpecifierSeq(DS))
873 DeclaratorInfo.setInvalidType(true);
Sebastian Redl0c986032009-02-09 18:23:29 +0000874 else {
875 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000876 ParseDeclaratorInternal(DeclaratorInfo,
877 &Parser::ParseDirectNewDeclarator);
Sebastian Redl0c986032009-02-09 18:23:29 +0000878 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000879 ParenTypeId = false;
880 }
Chris Lattner34c61332009-04-25 08:06:05 +0000881 if (DeclaratorInfo.isInvalidType()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000882 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl39d4f022008-12-11 22:51:44 +0000883 return ExprError();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000884 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000885
Sebastian Redl6008ac32008-11-25 22:21:31 +0000886 ExprVector ConstructorArgs(Actions);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000887 SourceLocation ConstructorLParen, ConstructorRParen;
888
889 if (Tok.is(tok::l_paren)) {
890 ConstructorLParen = ConsumeParen();
891 if (Tok.isNot(tok::r_paren)) {
892 CommaLocsTy CommaLocs;
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000893 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
894 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl39d4f022008-12-11 22:51:44 +0000895 return ExprError();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000896 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000897 }
898 ConstructorRParen = MatchRHSPunctuation(tok::r_paren, ConstructorLParen);
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000899 if (ConstructorRParen.isInvalid()) {
900 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl39d4f022008-12-11 22:51:44 +0000901 return ExprError();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000902 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000903 }
904
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000905 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
906 move_arg(PlacementArgs), PlacementRParen,
907 ParenTypeId, DeclaratorInfo, ConstructorLParen,
908 move_arg(ConstructorArgs), ConstructorRParen);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000909}
910
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000911/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
912/// passed to ParseDeclaratorInternal.
913///
914/// direct-new-declarator:
915/// '[' expression ']'
916/// direct-new-declarator '[' constant-expression ']'
917///
Chris Lattnere7de3612009-01-04 21:25:24 +0000918void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000919 // Parse the array dimensions.
920 bool first = true;
921 while (Tok.is(tok::l_square)) {
922 SourceLocation LLoc = ConsumeBracket();
Sebastian Redl14ca7412008-12-11 21:36:32 +0000923 OwningExprResult Size(first ? ParseExpression()
924 : ParseConstantExpression());
Sebastian Redlbb4dae72008-12-09 13:15:23 +0000925 if (Size.isInvalid()) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000926 // Recover
927 SkipUntil(tok::r_square);
928 return;
929 }
930 first = false;
931
Sebastian Redl0c986032009-02-09 18:23:29 +0000932 SourceLocation RLoc = MatchRHSPunctuation(tok::r_square, LLoc);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000933 D.AddTypeInfo(DeclaratorChunk::getArray(0, /*static=*/false, /*star=*/false,
Sebastian Redl0c986032009-02-09 18:23:29 +0000934 Size.release(), LLoc),
935 RLoc);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000936
Sebastian Redl0c986032009-02-09 18:23:29 +0000937 if (RLoc.isInvalid())
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000938 return;
939 }
940}
941
942/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
943/// This ambiguity appears in the syntax of the C++ new operator.
944///
945/// new-expression:
946/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
947/// new-initializer[opt]
948///
949/// new-placement:
950/// '(' expression-list ')'
951///
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000952bool Parser::ParseExpressionListOrTypeId(ExprListTy &PlacementArgs,
Chris Lattnere7de3612009-01-04 21:25:24 +0000953 Declarator &D) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000954 // The '(' was already consumed.
955 if (isTypeIdInParens()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000956 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redl0c986032009-02-09 18:23:29 +0000957 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000958 ParseDeclarator(D);
Chris Lattner34c61332009-04-25 08:06:05 +0000959 return D.isInvalidType();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000960 }
961
962 // It's not a type, it has to be an expression list.
963 // Discard the comma locations - ActOnCXXNew has enough parameters.
964 CommaLocsTy CommaLocs;
965 return ParseExpressionList(PlacementArgs, CommaLocs);
966}
967
968/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
969/// to free memory allocated by new.
970///
Chris Lattnere7de3612009-01-04 21:25:24 +0000971/// This method is called to parse the 'delete' expression after the optional
972/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
973/// and "Start" is its location. Otherwise, "Start" is the location of the
974/// 'delete' token.
975///
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000976/// delete-expression:
977/// '::'[opt] 'delete' cast-expression
978/// '::'[opt] 'delete' '[' ']' cast-expression
Chris Lattnere7de3612009-01-04 21:25:24 +0000979Parser::OwningExprResult
980Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
981 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
982 ConsumeToken(); // Consume 'delete'
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000983
984 // Array delete?
985 bool ArrayDelete = false;
986 if (Tok.is(tok::l_square)) {
987 ArrayDelete = true;
988 SourceLocation LHS = ConsumeBracket();
989 SourceLocation RHS = MatchRHSPunctuation(tok::r_square, LHS);
990 if (RHS.isInvalid())
Sebastian Redl39d4f022008-12-11 22:51:44 +0000991 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000992 }
993
Sebastian Redl14ca7412008-12-11 21:36:32 +0000994 OwningExprResult Operand(ParseCastExpression(false));
Sebastian Redlbb4dae72008-12-09 13:15:23 +0000995 if (Operand.isInvalid())
Sebastian Redl39d4f022008-12-11 22:51:44 +0000996 return move(Operand);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000997
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000998 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, move(Operand));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000999}
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001000
1001static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind)
1002{
1003 switch(kind) {
1004 default: assert(false && "Not a known unary type trait.");
1005 case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign;
1006 case tok::kw___has_nothrow_copy: return UTT_HasNothrowCopy;
1007 case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor;
1008 case tok::kw___has_trivial_assign: return UTT_HasTrivialAssign;
1009 case tok::kw___has_trivial_copy: return UTT_HasTrivialCopy;
1010 case tok::kw___has_trivial_constructor: return UTT_HasTrivialConstructor;
1011 case tok::kw___has_trivial_destructor: return UTT_HasTrivialDestructor;
1012 case tok::kw___has_virtual_destructor: return UTT_HasVirtualDestructor;
1013 case tok::kw___is_abstract: return UTT_IsAbstract;
1014 case tok::kw___is_class: return UTT_IsClass;
1015 case tok::kw___is_empty: return UTT_IsEmpty;
1016 case tok::kw___is_enum: return UTT_IsEnum;
1017 case tok::kw___is_pod: return UTT_IsPOD;
1018 case tok::kw___is_polymorphic: return UTT_IsPolymorphic;
1019 case tok::kw___is_union: return UTT_IsUnion;
1020 }
1021}
1022
1023/// ParseUnaryTypeTrait - Parse the built-in unary type-trait
1024/// pseudo-functions that allow implementation of the TR1/C++0x type traits
1025/// templates.
1026///
1027/// primary-expression:
1028/// [GNU] unary-type-trait '(' type-id ')'
1029///
1030Parser::OwningExprResult Parser::ParseUnaryTypeTrait()
1031{
1032 UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind());
1033 SourceLocation Loc = ConsumeToken();
1034
1035 SourceLocation LParen = Tok.getLocation();
1036 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
1037 return ExprError();
1038
1039 // FIXME: Error reporting absolutely sucks! If the this fails to parse a type
1040 // there will be cryptic errors about mismatched parentheses and missing
1041 // specifiers.
Douglas Gregor6c0f4062009-02-18 17:45:20 +00001042 TypeResult Ty = ParseTypeName();
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001043
1044 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen);
1045
Douglas Gregor6c0f4062009-02-18 17:45:20 +00001046 if (Ty.isInvalid())
1047 return ExprError();
1048
1049 return Actions.ActOnUnaryTypeTrait(UTT, Loc, LParen, Ty.get(), RParen);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001050}
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001051
1052/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
1053/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
1054/// based on the context past the parens.
1055Parser::OwningExprResult
1056Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
1057 TypeTy *&CastTy,
1058 SourceLocation LParenLoc,
1059 SourceLocation &RParenLoc) {
1060 assert(getLang().CPlusPlus && "Should only be called for C++!");
1061 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
1062 assert(isTypeIdInParens() && "Not a type-id!");
1063
1064 OwningExprResult Result(Actions, true);
1065 CastTy = 0;
1066
1067 // We need to disambiguate a very ugly part of the C++ syntax:
1068 //
1069 // (T())x; - type-id
1070 // (T())*x; - type-id
1071 // (T())/x; - expression
1072 // (T()); - expression
1073 //
1074 // The bad news is that we cannot use the specialized tentative parser, since
1075 // it can only verify that the thing inside the parens can be parsed as
1076 // type-id, it is not useful for determining the context past the parens.
1077 //
1078 // The good news is that the parser can disambiguate this part without
Argiris Kirtzidisdd9cbe12009-05-22 15:12:46 +00001079 // making any unnecessary Action calls.
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001080 //
1081 // It uses a scheme similar to parsing inline methods. The parenthesized
1082 // tokens are cached, the context that follows is determined (possibly by
1083 // parsing a cast-expression), and then we re-introduce the cached tokens
1084 // into the token stream and parse them appropriately.
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001085
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001086 ParenParseOption ParseAs;
1087 CachedTokens Toks;
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001088
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001089 // Store the tokens of the parentheses. We will parse them after we determine
1090 // the context that follows them.
1091 if (!ConsumeAndStoreUntil(tok::r_paren, tok::unknown, Toks, tok::semi)) {
1092 // We didn't find the ')' we expected.
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001093 MatchRHSPunctuation(tok::r_paren, LParenLoc);
1094 return ExprError();
1095 }
1096
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001097 if (Tok.is(tok::l_brace)) {
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001098 ParseAs = CompoundLiteral;
1099 } else {
1100 bool NotCastExpr;
Eli Friedmane4595942009-05-25 19:41:42 +00001101 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
1102 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
1103 NotCastExpr = true;
1104 } else {
1105 // Try parsing the cast-expression that may follow.
1106 // If it is not a cast-expression, NotCastExpr will be true and no token
1107 // will be consumed.
1108 Result = ParseCastExpression(false/*isUnaryExpression*/,
1109 false/*isAddressofOperand*/,
1110 NotCastExpr);
1111 }
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001112
1113 // If we parsed a cast-expression, it's really a type-id, otherwise it's
1114 // an expression.
1115 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001116 }
1117
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001118 // The current token should go after the cached tokens.
1119 Toks.push_back(Tok);
1120 // Re-enter the stored parenthesized tokens into the token stream, so we may
1121 // parse them now.
1122 PP.EnterTokenStream(Toks.data(), Toks.size(),
1123 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
1124 // Drop the current token and bring the first cached one. It's the same token
1125 // as when we entered this function.
1126 ConsumeAnyToken();
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001127
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001128 if (ParseAs >= CompoundLiteral) {
1129 TypeResult Ty = ParseTypeName();
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001130
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001131 // Match the ')'.
1132 if (Tok.is(tok::r_paren))
1133 RParenLoc = ConsumeParen();
1134 else
1135 MatchRHSPunctuation(tok::r_paren, LParenLoc);
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001136
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001137 if (ParseAs == CompoundLiteral) {
1138 ExprType = CompoundLiteral;
1139 return ParseCompoundLiteralExpression(Ty.get(), LParenLoc, RParenLoc);
1140 }
1141
1142 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
1143 assert(ParseAs == CastExpr);
1144
1145 if (Ty.isInvalid())
1146 return ExprError();
1147
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001148 CastTy = Ty.get();
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001149
1150 // Result is what ParseCastExpression returned earlier.
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001151 if (!Result.isInvalid())
1152 Result = Actions.ActOnCastExpr(LParenLoc, CastTy, RParenLoc,move(Result));
1153 return move(Result);
1154 }
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001155
1156 // Not a compound literal, and not followed by a cast-expression.
1157 assert(ParseAs == SimpleExpr);
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001158
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001159 ExprType = SimpleExpr;
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001160 Result = ParseExpression();
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001161 if (!Result.isInvalid() && Tok.is(tok::r_paren))
1162 Result = Actions.ActOnParenExpr(LParenLoc, Tok.getLocation(), move(Result));
1163
1164 // Match the ')'.
1165 if (Result.isInvalid()) {
1166 SkipUntil(tok::r_paren);
1167 return ExprError();
1168 }
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001169
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001170 if (Tok.is(tok::r_paren))
1171 RParenLoc = ConsumeParen();
1172 else
1173 MatchRHSPunctuation(tok::r_paren, LParenLoc);
1174
1175 return move(Result);
1176}