blob: 68101fcdf4ea7c9fcc41cc409a5257b2b71b00ff [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:
Chris Lattner8e48daa2009-06-26 03:47:46 +000062 // nested-name-specifier 'template'[opt] simple-template-id '::'
63
64 // Parse the optional 'template' keyword, then make sure we have
65 // 'identifier <' after it.
66 if (Tok.is(tok::kw_template)) {
67 SourceLocation TemplateKWLoc = ConsumeToken();
68
69 if (Tok.isNot(tok::identifier)) {
70 Diag(Tok.getLocation(),
71 diag::err_id_after_template_in_nested_name_spec)
72 << SourceRange(TemplateKWLoc);
73 break;
74 }
75
76 if (NextToken().isNot(tok::less)) {
77 Diag(NextToken().getLocation(),
78 diag::err_less_after_template_name_in_nested_name_spec)
79 << Tok.getIdentifierInfo()->getName()
80 << SourceRange(TemplateKWLoc, Tok.getLocation());
81 break;
82 }
83
84 TemplateTy Template
85 = Actions.ActOnDependentTemplateName(TemplateKWLoc,
86 *Tok.getIdentifierInfo(),
87 Tok.getLocation(), SS);
Chris Lattner8eabc062009-06-26 04:27:47 +000088 if (AnnotateTemplateIdToken(Template, TNK_Dependent_template_name,
89 &SS, TemplateKWLoc, false))
90 break;
91
Chris Lattner8e48daa2009-06-26 03:47:46 +000092 continue;
93 }
94
Douglas Gregor0c281a82009-02-25 19:37:18 +000095 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
96 // We have
97 //
98 // simple-template-id '::'
99 //
100 // So we need to check whether the simple-template-id is of the
Douglas Gregoraabb8502009-03-31 00:43:58 +0000101 // right kind (it should name a type or be dependent), and then
102 // convert it into a type within the nested-name-specifier.
Douglas Gregor0c281a82009-02-25 19:37:18 +0000103 TemplateIdAnnotation *TemplateId
104 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
105
Douglas Gregoraabb8502009-03-31 00:43:58 +0000106 if (TemplateId->Kind == TNK_Type_template ||
107 TemplateId->Kind == TNK_Dependent_template_name) {
Douglas Gregord7cb0372009-04-01 21:51:26 +0000108 AnnotateTemplateIdTokenAsType(&SS);
Douglas Gregor96b6df92009-05-14 00:28:11 +0000109 SS.setScopeRep(0);
Douglas Gregor0c281a82009-02-25 19:37:18 +0000110
111 assert(Tok.is(tok::annot_typename) &&
112 "AnnotateTemplateIdTokenAsType isn't working");
Douglas Gregor0c281a82009-02-25 19:37:18 +0000113 Token TypeToken = Tok;
114 ConsumeToken();
115 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
116 SourceLocation CCLoc = ConsumeToken();
117
118 if (!HasScopeSpecifier) {
119 SS.setBeginLoc(TypeToken.getLocation());
120 HasScopeSpecifier = true;
121 }
Douglas Gregord7cb0372009-04-01 21:51:26 +0000122
123 if (TypeToken.getAnnotationValue())
124 SS.setScopeRep(
125 Actions.ActOnCXXNestedNameSpecifier(CurScope, SS,
126 TypeToken.getAnnotationValue(),
127 TypeToken.getAnnotationRange(),
128 CCLoc));
129 else
130 SS.setScopeRep(0);
Douglas Gregor0c281a82009-02-25 19:37:18 +0000131 SS.setEndLoc(CCLoc);
132 continue;
Chris Lattnerd25310c2009-06-26 03:45:46 +0000133 }
134
135 assert(false && "FIXME: Only type template names supported here");
Douglas Gregor0c281a82009-02-25 19:37:18 +0000136 }
137
Chris Lattnera934c392009-06-26 03:52:38 +0000138
139 // The rest of the nested-name-specifier possibilities start with
140 // tok::identifier.
141 if (Tok.isNot(tok::identifier))
142 break;
143
144 IdentifierInfo &II = *Tok.getIdentifierInfo();
145
146 // nested-name-specifier:
147 // type-name '::'
148 // namespace-name '::'
149 // nested-name-specifier identifier '::'
150 Token Next = NextToken();
151 if (Next.is(tok::coloncolon)) {
152 // We have an identifier followed by a '::'. Lookup this name
153 // as the name in a nested-name-specifier.
154 SourceLocation IdLoc = ConsumeToken();
155 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
156 SourceLocation CCLoc = ConsumeToken();
157
158 if (!HasScopeSpecifier) {
159 SS.setBeginLoc(IdLoc);
160 HasScopeSpecifier = true;
161 }
162
163 if (SS.isInvalid())
164 continue;
165
166 SS.setScopeRep(
167 Actions.ActOnCXXNestedNameSpecifier(CurScope, SS, IdLoc, CCLoc, II));
168 SS.setEndLoc(CCLoc);
169 continue;
170 }
171
172 // nested-name-specifier:
173 // type-name '<'
174 if (Next.is(tok::less)) {
175 TemplateTy Template;
176 if (TemplateNameKind TNK = Actions.isTemplateName(II, CurScope,
177 Template, &SS)) {
178 // We have found a template name, so annotate this this token
179 // with a template-id annotation. We do not permit the
180 // template-id to be translated into a type annotation,
181 // because some clients (e.g., the parsing of class template
182 // specializations) still want to see the original template-id
183 // token.
Chris Lattner8eabc062009-06-26 04:27:47 +0000184 if (AnnotateTemplateIdToken(Template, TNK, &SS, SourceLocation(),
185 false))
186 break;
Chris Lattnera934c392009-06-26 03:52:38 +0000187 continue;
188 }
189 }
190
Douglas Gregor0c281a82009-02-25 19:37:18 +0000191 // We don't have any tokens that form the beginning of a
192 // nested-name-specifier, so we're done.
193 break;
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000194 }
Douglas Gregor0c281a82009-02-25 19:37:18 +0000195
196 return HasScopeSpecifier;
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000197}
198
199/// ParseCXXIdExpression - Handle id-expression.
200///
201/// id-expression:
202/// unqualified-id
203/// qualified-id
204///
205/// unqualified-id:
206/// identifier
207/// operator-function-id
208/// conversion-function-id [TODO]
209/// '~' class-name [TODO]
Douglas Gregor28857752009-06-30 22:34:41 +0000210/// template-id
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000211///
212/// qualified-id:
213/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
214/// '::' identifier
215/// '::' operator-function-id
Douglas Gregor28857752009-06-30 22:34:41 +0000216/// '::' template-id
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000217///
218/// nested-name-specifier:
219/// type-name '::'
220/// namespace-name '::'
221/// nested-name-specifier identifier '::'
222/// nested-name-specifier 'template'[opt] simple-template-id '::' [TODO]
223///
224/// NOTE: The standard specifies that, for qualified-id, the parser does not
225/// expect:
226///
227/// '::' conversion-function-id
228/// '::' '~' class-name
229///
230/// This may cause a slight inconsistency on diagnostics:
231///
232/// class C {};
233/// namespace A {}
234/// void f() {
235/// :: A :: ~ C(); // Some Sema error about using destructor with a
236/// // namespace.
237/// :: ~ C(); // Some Parser error like 'unexpected ~'.
238/// }
239///
240/// We simplify the parser a bit and make it work like:
241///
242/// qualified-id:
243/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
244/// '::' unqualified-id
245///
246/// That way Sema can handle and report similar errors for namespaces and the
247/// global scope.
248///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000249/// The isAddressOfOperand parameter indicates that this id-expression is a
250/// direct operand of the address-of operator. This is, besides member contexts,
251/// the only place where a qualified-id naming a non-static class member may
252/// appear.
253///
254Parser::OwningExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000255 // qualified-id:
256 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
257 // '::' unqualified-id
258 //
259 CXXScopeSpec SS;
Chris Lattnerd706dc82009-01-06 06:59:53 +0000260 ParseOptionalCXXScopeSpecifier(SS);
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000261
262 // unqualified-id:
263 // identifier
264 // operator-function-id
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000265 // conversion-function-id
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000266 // '~' class-name [TODO]
Douglas Gregor28857752009-06-30 22:34:41 +0000267 // template-id
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000268 //
269 switch (Tok.getKind()) {
270 default:
Sebastian Redl39d4f022008-12-11 22:51:44 +0000271 return ExprError(Diag(Tok, diag::err_expected_unqualified_id));
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000272
273 case tok::identifier: {
274 // Consume the identifier so that we can see if it is followed by a '('.
275 IdentifierInfo &II = *Tok.getIdentifierInfo();
276 SourceLocation L = ConsumeToken();
Sebastian Redl0c9da212009-02-03 20:19:35 +0000277 return Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren),
278 &SS, isAddressOfOperand);
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000279 }
280
281 case tok::kw_operator: {
282 SourceLocation OperatorLoc = Tok.getLocation();
Chris Lattner8376d2e2009-01-05 01:24:05 +0000283 if (OverloadedOperatorKind Op = TryParseOperatorFunctionId())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000284 return Actions.ActOnCXXOperatorFunctionIdExpr(
Sebastian Redl0c9da212009-02-03 20:19:35 +0000285 CurScope, OperatorLoc, Op, Tok.is(tok::l_paren), SS,
286 isAddressOfOperand);
Chris Lattner8376d2e2009-01-05 01:24:05 +0000287 if (TypeTy *Type = ParseConversionFunctionId())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000288 return Actions.ActOnCXXConversionFunctionExpr(CurScope, OperatorLoc, Type,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000289 Tok.is(tok::l_paren), SS,
290 isAddressOfOperand);
Sebastian Redl39d4f022008-12-11 22:51:44 +0000291
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000292 // We already complained about a bad conversion-function-id,
293 // above.
Sebastian Redl39d4f022008-12-11 22:51:44 +0000294 return ExprError();
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000295 }
296
Douglas Gregor28857752009-06-30 22:34:41 +0000297 case tok::annot_template_id: {
298 TemplateIdAnnotation *TemplateId
299 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
300 assert((TemplateId->Kind == TNK_Function_template ||
301 TemplateId->Kind == TNK_Dependent_template_name) &&
302 "A template type name is not an ID expression");
303
304 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
305 TemplateId->getTemplateArgs(),
306 TemplateId->getTemplateArgIsType(),
307 TemplateId->NumArgs);
308
309 OwningExprResult Result
310 = Actions.ActOnTemplateIdExpr(TemplateTy::make(TemplateId->Template),
311 TemplateId->TemplateNameLoc,
312 TemplateId->LAngleLoc,
313 TemplateArgsPtr,
314 TemplateId->getTemplateArgLocations(),
315 TemplateId->RAngleLoc);
316 ConsumeToken(); // Consume the template-id token
317 return move(Result);
318 }
319
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000320 } // switch.
321
322 assert(0 && "The switch was supposed to take care everything.");
323}
324
Chris Lattner4b009652007-07-25 00:24:17 +0000325/// ParseCXXCasts - This handles the various ways to cast expressions to another
326/// type.
327///
328/// postfix-expression: [C++ 5.2p1]
329/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
330/// 'static_cast' '<' type-name '>' '(' expression ')'
331/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
332/// 'const_cast' '<' type-name '>' '(' expression ')'
333///
Sebastian Redl39d4f022008-12-11 22:51:44 +0000334Parser::OwningExprResult Parser::ParseCXXCasts() {
Chris Lattner4b009652007-07-25 00:24:17 +0000335 tok::TokenKind Kind = Tok.getKind();
336 const char *CastName = 0; // For error messages
337
338 switch (Kind) {
339 default: assert(0 && "Unknown C++ cast!"); abort();
340 case tok::kw_const_cast: CastName = "const_cast"; break;
341 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
342 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
343 case tok::kw_static_cast: CastName = "static_cast"; break;
344 }
345
346 SourceLocation OpLoc = ConsumeToken();
347 SourceLocation LAngleBracketLoc = Tok.getLocation();
348
349 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redl39d4f022008-12-11 22:51:44 +0000350 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000351
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000352 TypeResult CastTy = ParseTypeName();
Chris Lattner4b009652007-07-25 00:24:17 +0000353 SourceLocation RAngleBracketLoc = Tok.getLocation();
354
Chris Lattnerf006a222008-11-18 07:48:38 +0000355 if (ExpectAndConsume(tok::greater, diag::err_expected_greater))
Sebastian Redl39d4f022008-12-11 22:51:44 +0000356 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<");
Chris Lattner4b009652007-07-25 00:24:17 +0000357
358 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
359
Argiris Kirtzidisd61a2f72009-05-22 10:23:16 +0000360 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, CastName))
361 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000362
Argiris Kirtzidisd61a2f72009-05-22 10:23:16 +0000363 OwningExprResult Result = ParseExpression();
364
365 // Match the ')'.
366 if (Result.isInvalid())
367 SkipUntil(tok::r_paren);
368
369 if (Tok.is(tok::r_paren))
370 RParenLoc = ConsumeParen();
371 else
372 MatchRHSPunctuation(tok::r_paren, LParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000373
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000374 if (!Result.isInvalid() && !CastTy.isInvalid())
Douglas Gregor21a04f32008-10-27 19:41:14 +0000375 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000376 LAngleBracketLoc, CastTy.get(),
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000377 RAngleBracketLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000378 LParenLoc, move(Result), RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000379
Sebastian Redl39d4f022008-12-11 22:51:44 +0000380 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +0000381}
382
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000383/// ParseCXXTypeid - This handles the C++ typeid expression.
384///
385/// postfix-expression: [C++ 5.2p1]
386/// 'typeid' '(' expression ')'
387/// 'typeid' '(' type-id ')'
388///
Sebastian Redl39d4f022008-12-11 22:51:44 +0000389Parser::OwningExprResult Parser::ParseCXXTypeid() {
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000390 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
391
392 SourceLocation OpLoc = ConsumeToken();
393 SourceLocation LParenLoc = Tok.getLocation();
394 SourceLocation RParenLoc;
395
396 // typeid expressions are always parenthesized.
397 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
398 "typeid"))
Sebastian Redl39d4f022008-12-11 22:51:44 +0000399 return ExprError();
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000400
Sebastian Redl62261042008-12-09 20:22:58 +0000401 OwningExprResult Result(Actions);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000402
403 if (isTypeIdInParens()) {
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000404 TypeResult Ty = ParseTypeName();
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000405
406 // Match the ')'.
407 MatchRHSPunctuation(tok::r_paren, LParenLoc);
408
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000409 if (Ty.isInvalid())
Sebastian Redl39d4f022008-12-11 22:51:44 +0000410 return ExprError();
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000411
412 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000413 Ty.get(), RParenLoc);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000414 } else {
Douglas Gregor98189262009-06-19 23:52:42 +0000415 // C++0x [expr.typeid]p3:
416 // When typeid is applied to an expression other than an lvalue of a
417 // polymorphic class type [...] The expression is an unevaluated
418 // operand (Clause 5).
419 //
420 // Note that we can't tell whether the expression is an lvalue of a
421 // polymorphic class type until after we've parsed the expression, so
Douglas Gregora8b2fbf2009-06-22 20:57:11 +0000422 // we the expression is potentially potentially evaluated.
423 EnterExpressionEvaluationContext Unevaluated(Actions,
424 Action::PotentiallyPotentiallyEvaluated);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000425 Result = ParseExpression();
426
427 // Match the ')'.
Sebastian Redlbb4dae72008-12-09 13:15:23 +0000428 if (Result.isInvalid())
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000429 SkipUntil(tok::r_paren);
430 else {
431 MatchRHSPunctuation(tok::r_paren, LParenLoc);
432
433 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Sebastian Redl6f1ee232008-12-10 00:02:53 +0000434 Result.release(), RParenLoc);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000435 }
436 }
437
Sebastian Redl39d4f022008-12-11 22:51:44 +0000438 return move(Result);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000439}
440
Chris Lattner4b009652007-07-25 00:24:17 +0000441/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
442///
443/// boolean-literal: [C++ 2.13.5]
444/// 'true'
445/// 'false'
Sebastian Redl39d4f022008-12-11 22:51:44 +0000446Parser::OwningExprResult Parser::ParseCXXBoolLiteral() {
Chris Lattner4b009652007-07-25 00:24:17 +0000447 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000448 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Chris Lattner4b009652007-07-25 00:24:17 +0000449}
Chris Lattnera7447ba2008-02-26 00:51:44 +0000450
451/// ParseThrowExpression - This handles the C++ throw expression.
452///
453/// throw-expression: [C++ 15]
454/// 'throw' assignment-expression[opt]
Sebastian Redl39d4f022008-12-11 22:51:44 +0000455Parser::OwningExprResult Parser::ParseThrowExpression() {
Chris Lattnera7447ba2008-02-26 00:51:44 +0000456 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnera7447ba2008-02-26 00:51:44 +0000457 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redl39d4f022008-12-11 22:51:44 +0000458
Chris Lattner6b8842d2008-04-06 06:02:23 +0000459 // If the current token isn't the start of an assignment-expression,
460 // then the expression is not present. This handles things like:
461 // "C ? throw : (void)42", which is crazy but legal.
462 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
463 case tok::semi:
464 case tok::r_paren:
465 case tok::r_square:
466 case tok::r_brace:
467 case tok::colon:
468 case tok::comma:
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000469 return Actions.ActOnCXXThrow(ThrowLoc, ExprArg(Actions));
Chris Lattnera7447ba2008-02-26 00:51:44 +0000470
Chris Lattner6b8842d2008-04-06 06:02:23 +0000471 default:
Sebastian Redl14ca7412008-12-11 21:36:32 +0000472 OwningExprResult Expr(ParseAssignmentExpression());
Sebastian Redl39d4f022008-12-11 22:51:44 +0000473 if (Expr.isInvalid()) return move(Expr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000474 return Actions.ActOnCXXThrow(ThrowLoc, move(Expr));
Chris Lattner6b8842d2008-04-06 06:02:23 +0000475 }
Chris Lattnera7447ba2008-02-26 00:51:44 +0000476}
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000477
478/// ParseCXXThis - This handles the C++ 'this' pointer.
479///
480/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
481/// a non-lvalue expression whose value is the address of the object for which
482/// the function is called.
Sebastian Redl39d4f022008-12-11 22:51:44 +0000483Parser::OwningExprResult Parser::ParseCXXThis() {
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000484 assert(Tok.is(tok::kw_this) && "Not 'this'!");
485 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000486 return Actions.ActOnCXXThis(ThisLoc);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000487}
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000488
489/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
490/// Can be interpreted either as function-style casting ("int(x)")
491/// or class type construction ("ClassType(x,y,z)")
492/// or creation of a value-initialized type ("int()").
493///
494/// postfix-expression: [C++ 5.2p1]
495/// simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
496/// typename-specifier '(' expression-list[opt] ')' [TODO]
497///
Sebastian Redl39d4f022008-12-11 22:51:44 +0000498Parser::OwningExprResult
499Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000500 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
Douglas Gregor10a18fc2009-01-26 22:44:13 +0000501 TypeTy *TypeRep = Actions.ActOnTypeName(CurScope, DeclaratorInfo).get();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000502
503 assert(Tok.is(tok::l_paren) && "Expected '('!");
504 SourceLocation LParenLoc = ConsumeParen();
505
Sebastian Redl6008ac32008-11-25 22:21:31 +0000506 ExprVector Exprs(Actions);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000507 CommaLocsTy CommaLocs;
508
509 if (Tok.isNot(tok::r_paren)) {
510 if (ParseExpressionList(Exprs, CommaLocs)) {
511 SkipUntil(tok::r_paren);
Sebastian Redl39d4f022008-12-11 22:51:44 +0000512 return ExprError();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000513 }
514 }
515
516 // Match the ')'.
517 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
518
519 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
520 "Unexpected number of commas!");
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000521 return Actions.ActOnCXXTypeConstructExpr(DS.getSourceRange(), TypeRep,
522 LParenLoc, move_arg(Exprs),
Jay Foad9e6bef42009-05-21 09:52:38 +0000523 CommaLocs.data(), RParenLoc);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000524}
525
Argiris Kirtzidis873f2782008-09-09 20:38:47 +0000526/// ParseCXXCondition - if/switch/while/for condition expression.
527///
528/// condition:
529/// expression
530/// type-specifier-seq declarator '=' assignment-expression
531/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
532/// '=' assignment-expression
533///
Sebastian Redl14ca7412008-12-11 21:36:32 +0000534Parser::OwningExprResult Parser::ParseCXXCondition() {
Argiris Kirtzidis88527fb2008-10-05 15:03:47 +0000535 if (!isCXXConditionDeclaration())
Argiris Kirtzidis873f2782008-09-09 20:38:47 +0000536 return ParseExpression(); // expression
537
538 SourceLocation StartLoc = Tok.getLocation();
539
540 // type-specifier-seq
541 DeclSpec DS;
542 ParseSpecifierQualifierList(DS);
543
544 // declarator
545 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
546 ParseDeclarator(DeclaratorInfo);
547
548 // simple-asm-expr[opt]
549 if (Tok.is(tok::kw_asm)) {
Sebastian Redl0c986032009-02-09 18:23:29 +0000550 SourceLocation Loc;
551 OwningExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redlbb4dae72008-12-09 13:15:23 +0000552 if (AsmLabel.isInvalid()) {
Argiris Kirtzidis873f2782008-09-09 20:38:47 +0000553 SkipUntil(tok::semi);
Sebastian Redl14ca7412008-12-11 21:36:32 +0000554 return ExprError();
Argiris Kirtzidis873f2782008-09-09 20:38:47 +0000555 }
Sebastian Redl6f1ee232008-12-10 00:02:53 +0000556 DeclaratorInfo.setAsmLabel(AsmLabel.release());
Sebastian Redl0c986032009-02-09 18:23:29 +0000557 DeclaratorInfo.SetRangeEnd(Loc);
Argiris Kirtzidis873f2782008-09-09 20:38:47 +0000558 }
559
560 // If attributes are present, parse them.
Sebastian Redl0c986032009-02-09 18:23:29 +0000561 if (Tok.is(tok::kw___attribute)) {
562 SourceLocation Loc;
563 AttributeList *AttrList = ParseAttributes(&Loc);
564 DeclaratorInfo.AddAttributes(AttrList, Loc);
565 }
Argiris Kirtzidis873f2782008-09-09 20:38:47 +0000566
567 // '=' assignment-expression
568 if (Tok.isNot(tok::equal))
Sebastian Redl14ca7412008-12-11 21:36:32 +0000569 return ExprError(Diag(Tok, diag::err_expected_equal_after_declarator));
Argiris Kirtzidis873f2782008-09-09 20:38:47 +0000570 SourceLocation EqualLoc = ConsumeToken();
Sebastian Redl14ca7412008-12-11 21:36:32 +0000571 OwningExprResult AssignExpr(ParseAssignmentExpression());
Sebastian Redlbb4dae72008-12-09 13:15:23 +0000572 if (AssignExpr.isInvalid())
Sebastian Redl14ca7412008-12-11 21:36:32 +0000573 return ExprError();
574
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000575 return Actions.ActOnCXXConditionDeclarationExpr(CurScope, StartLoc,
576 DeclaratorInfo,EqualLoc,
577 move(AssignExpr));
Argiris Kirtzidis873f2782008-09-09 20:38:47 +0000578}
579
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000580/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
581/// This should only be called when the current token is known to be part of
582/// simple-type-specifier.
583///
584/// simple-type-specifier:
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000585/// '::'[opt] nested-name-specifier[opt] type-name
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000586/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
587/// char
588/// wchar_t
589/// bool
590/// short
591/// int
592/// long
593/// signed
594/// unsigned
595/// float
596/// double
597/// void
598/// [GNU] typeof-specifier
599/// [C++0x] auto [TODO]
600///
601/// type-name:
602/// class-name
603/// enum-name
604/// typedef-name
605///
606void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
607 DS.SetRangeStart(Tok.getLocation());
608 const char *PrevSpec;
609 SourceLocation Loc = Tok.getLocation();
610
611 switch (Tok.getKind()) {
Chris Lattner2c301452009-01-05 00:13:00 +0000612 case tok::identifier: // foo::bar
613 case tok::coloncolon: // ::foo::bar
614 assert(0 && "Annotation token should already be formed!");
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000615 default:
616 assert(0 && "Not a simple-type-specifier token!");
617 abort();
Chris Lattner2c301452009-01-05 00:13:00 +0000618
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000619 // type-name
Chris Lattner5d7eace2009-01-06 05:06:21 +0000620 case tok::annot_typename: {
Douglas Gregora60c62e2009-02-09 15:09:02 +0000621 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000622 Tok.getAnnotationValue());
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000623 break;
624 }
625
626 // builtin types
627 case tok::kw_short:
628 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec);
629 break;
630 case tok::kw_long:
631 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec);
632 break;
633 case tok::kw_signed:
634 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec);
635 break;
636 case tok::kw_unsigned:
637 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec);
638 break;
639 case tok::kw_void:
640 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec);
641 break;
642 case tok::kw_char:
643 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec);
644 break;
645 case tok::kw_int:
646 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec);
647 break;
648 case tok::kw_float:
649 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec);
650 break;
651 case tok::kw_double:
652 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec);
653 break;
654 case tok::kw_wchar_t:
655 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec);
656 break;
Alisdair Meredith2bcacb62009-07-14 06:30:34 +0000657 case tok::kw_char16_t:
658 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec);
659 break;
660 case tok::kw_char32_t:
661 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec);
662 break;
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000663 case tok::kw_bool:
664 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec);
665 break;
666
667 // GNU typeof support.
668 case tok::kw_typeof:
669 ParseTypeofSpecifier(DS);
Douglas Gregor1ba5cb32009-04-01 22:41:11 +0000670 DS.Finish(Diags, PP);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000671 return;
672 }
Chris Lattner5d7eace2009-01-06 05:06:21 +0000673 if (Tok.is(tok::annot_typename))
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000674 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
675 else
676 DS.SetRangeEnd(Tok.getLocation());
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000677 ConsumeToken();
Douglas Gregor1ba5cb32009-04-01 22:41:11 +0000678 DS.Finish(Diags, PP);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000679}
Douglas Gregore60e5d32008-11-06 22:13:31 +0000680
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000681/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
682/// [dcl.name]), which is a non-empty sequence of type-specifiers,
683/// e.g., "const short int". Note that the DeclSpec is *not* finished
684/// by parsing the type-specifier-seq, because these sequences are
685/// typically followed by some form of declarator. Returns true and
686/// emits diagnostics if this is not a type-specifier-seq, false
687/// otherwise.
688///
689/// type-specifier-seq: [C++ 8.1]
690/// type-specifier type-specifier-seq[opt]
691///
692bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
693 DS.SetRangeStart(Tok.getLocation());
694 const char *PrevSpec = 0;
695 int isInvalid = 0;
696
697 // Parse one or more of the type specifiers.
Chris Lattnerd706dc82009-01-06 06:59:53 +0000698 if (!ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec)) {
Chris Lattnerf006a222008-11-18 07:48:38 +0000699 Diag(Tok, diag::err_operator_missing_type_specifier);
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000700 return true;
701 }
Chris Lattnerd706dc82009-01-06 06:59:53 +0000702
Ted Kremenek34034d72009-01-06 19:17:58 +0000703 while (ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec)) ;
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000704
705 return false;
706}
707
Douglas Gregor682a8cf2008-11-17 16:14:12 +0000708/// TryParseOperatorFunctionId - Attempts to parse a C++ overloaded
Douglas Gregore60e5d32008-11-06 22:13:31 +0000709/// operator name (C++ [over.oper]). If successful, returns the
710/// predefined identifier that corresponds to that overloaded
711/// operator. Otherwise, returns NULL and does not consume any tokens.
712///
713/// operator-function-id: [C++ 13.5]
714/// 'operator' operator
715///
716/// operator: one of
717/// new delete new[] delete[]
718/// + - * / % ^ & | ~
719/// ! = < > += -= *= /= %=
720/// ^= &= |= << >> >>= <<= == !=
721/// <= >= && || ++ -- , ->* ->
722/// () []
Sebastian Redl0c986032009-02-09 18:23:29 +0000723OverloadedOperatorKind
724Parser::TryParseOperatorFunctionId(SourceLocation *EndLoc) {
Argiris Kirtzidisa9d57b62008-11-07 15:54:02 +0000725 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
Sebastian Redl0c986032009-02-09 18:23:29 +0000726 SourceLocation Loc;
Douglas Gregore60e5d32008-11-06 22:13:31 +0000727
728 OverloadedOperatorKind Op = OO_None;
729 switch (NextToken().getKind()) {
730 case tok::kw_new:
731 ConsumeToken(); // 'operator'
Sebastian Redl0c986032009-02-09 18:23:29 +0000732 Loc = ConsumeToken(); // 'new'
Douglas Gregore60e5d32008-11-06 22:13:31 +0000733 if (Tok.is(tok::l_square)) {
734 ConsumeBracket(); // '['
Sebastian Redl0c986032009-02-09 18:23:29 +0000735 Loc = Tok.getLocation();
Douglas Gregore60e5d32008-11-06 22:13:31 +0000736 ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); // ']'
737 Op = OO_Array_New;
738 } else {
739 Op = OO_New;
740 }
Sebastian Redl0c986032009-02-09 18:23:29 +0000741 if (EndLoc)
742 *EndLoc = Loc;
Douglas Gregor96a32dd2008-11-18 14:39:36 +0000743 return Op;
Douglas Gregore60e5d32008-11-06 22:13:31 +0000744
745 case tok::kw_delete:
746 ConsumeToken(); // 'operator'
Sebastian Redl0c986032009-02-09 18:23:29 +0000747 Loc = ConsumeToken(); // 'delete'
Douglas Gregore60e5d32008-11-06 22:13:31 +0000748 if (Tok.is(tok::l_square)) {
749 ConsumeBracket(); // '['
Sebastian Redl0c986032009-02-09 18:23:29 +0000750 Loc = Tok.getLocation();
Douglas Gregore60e5d32008-11-06 22:13:31 +0000751 ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); // ']'
752 Op = OO_Array_Delete;
753 } else {
754 Op = OO_Delete;
755 }
Sebastian Redl0c986032009-02-09 18:23:29 +0000756 if (EndLoc)
757 *EndLoc = Loc;
Douglas Gregor96a32dd2008-11-18 14:39:36 +0000758 return Op;
Douglas Gregore60e5d32008-11-06 22:13:31 +0000759
Douglas Gregor9c6210b2008-11-10 13:38:07 +0000760#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
Douglas Gregore60e5d32008-11-06 22:13:31 +0000761 case tok::Token: Op = OO_##Name; break;
Douglas Gregor9c6210b2008-11-10 13:38:07 +0000762#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
Douglas Gregore60e5d32008-11-06 22:13:31 +0000763#include "clang/Basic/OperatorKinds.def"
764
765 case tok::l_paren:
766 ConsumeToken(); // 'operator'
767 ConsumeParen(); // '('
Sebastian Redl0c986032009-02-09 18:23:29 +0000768 Loc = Tok.getLocation();
Douglas Gregore60e5d32008-11-06 22:13:31 +0000769 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); // ')'
Sebastian Redl0c986032009-02-09 18:23:29 +0000770 if (EndLoc)
771 *EndLoc = Loc;
Douglas Gregor96a32dd2008-11-18 14:39:36 +0000772 return OO_Call;
Douglas Gregore60e5d32008-11-06 22:13:31 +0000773
774 case tok::l_square:
775 ConsumeToken(); // 'operator'
776 ConsumeBracket(); // '['
Sebastian Redl0c986032009-02-09 18:23:29 +0000777 Loc = Tok.getLocation();
Douglas Gregore60e5d32008-11-06 22:13:31 +0000778 ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); // ']'
Sebastian Redl0c986032009-02-09 18:23:29 +0000779 if (EndLoc)
780 *EndLoc = Loc;
Douglas Gregor96a32dd2008-11-18 14:39:36 +0000781 return OO_Subscript;
Douglas Gregore60e5d32008-11-06 22:13:31 +0000782
783 default:
Douglas Gregor96a32dd2008-11-18 14:39:36 +0000784 return OO_None;
Douglas Gregore60e5d32008-11-06 22:13:31 +0000785 }
786
Douglas Gregor682a8cf2008-11-17 16:14:12 +0000787 ConsumeToken(); // 'operator'
Sebastian Redl0c986032009-02-09 18:23:29 +0000788 Loc = ConsumeAnyToken(); // the operator itself
789 if (EndLoc)
790 *EndLoc = Loc;
Douglas Gregor96a32dd2008-11-18 14:39:36 +0000791 return Op;
Douglas Gregore60e5d32008-11-06 22:13:31 +0000792}
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000793
794/// ParseConversionFunctionId - Parse a C++ conversion-function-id,
795/// which expresses the name of a user-defined conversion operator
796/// (C++ [class.conv.fct]p1). Returns the type that this operator is
797/// specifying a conversion for, or NULL if there was an error.
798///
799/// conversion-function-id: [C++ 12.3.2]
800/// operator conversion-type-id
801///
802/// conversion-type-id:
803/// type-specifier-seq conversion-declarator[opt]
804///
805/// conversion-declarator:
806/// ptr-operator conversion-declarator[opt]
Sebastian Redl0c986032009-02-09 18:23:29 +0000807Parser::TypeTy *Parser::ParseConversionFunctionId(SourceLocation *EndLoc) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000808 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
809 ConsumeToken(); // 'operator'
810
811 // Parse the type-specifier-seq.
812 DeclSpec DS;
813 if (ParseCXXTypeSpecifierSeq(DS))
814 return 0;
815
816 // Parse the conversion-declarator, which is merely a sequence of
817 // ptr-operators.
818 Declarator D(DS, Declarator::TypeNameContext);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000819 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
Sebastian Redl0c986032009-02-09 18:23:29 +0000820 if (EndLoc)
821 *EndLoc = D.getSourceRange().getEnd();
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000822
823 // Finish up the type.
824 Action::TypeResult Result = Actions.ActOnTypeName(CurScope, D);
Douglas Gregor10a18fc2009-01-26 22:44:13 +0000825 if (Result.isInvalid())
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000826 return 0;
827 else
Douglas Gregor10a18fc2009-01-26 22:44:13 +0000828 return Result.get();
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000829}
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000830
831/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
832/// memory in a typesafe manner and call constructors.
Chris Lattnere7de3612009-01-04 21:25:24 +0000833///
834/// This method is called to parse the new expression after the optional :: has
835/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
836/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000837///
838/// new-expression:
839/// '::'[opt] 'new' new-placement[opt] new-type-id
840/// new-initializer[opt]
841/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
842/// new-initializer[opt]
843///
844/// new-placement:
845/// '(' expression-list ')'
846///
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000847/// new-type-id:
848/// type-specifier-seq new-declarator[opt]
849///
850/// new-declarator:
851/// ptr-operator new-declarator[opt]
852/// direct-new-declarator
853///
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000854/// new-initializer:
855/// '(' expression-list[opt] ')'
856/// [C++0x] braced-init-list [TODO]
857///
Chris Lattnere7de3612009-01-04 21:25:24 +0000858Parser::OwningExprResult
859Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
860 assert(Tok.is(tok::kw_new) && "expected 'new' token");
861 ConsumeToken(); // Consume 'new'
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000862
863 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
864 // second form of new-expression. It can't be a new-type-id.
865
Sebastian Redl6008ac32008-11-25 22:21:31 +0000866 ExprVector PlacementArgs(Actions);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000867 SourceLocation PlacementLParen, PlacementRParen;
868
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000869 bool ParenTypeId;
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000870 DeclSpec DS;
871 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000872 if (Tok.is(tok::l_paren)) {
873 // If it turns out to be a placement, we change the type location.
874 PlacementLParen = ConsumeParen();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000875 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
876 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl39d4f022008-12-11 22:51:44 +0000877 return ExprError();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000878 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000879
880 PlacementRParen = MatchRHSPunctuation(tok::r_paren, PlacementLParen);
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000881 if (PlacementRParen.isInvalid()) {
882 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 Redl66df3ef2008-12-02 14:43:59 +0000886 if (PlacementArgs.empty()) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000887 // Reset the placement locations. There was no placement.
888 PlacementLParen = PlacementRParen = SourceLocation();
889 ParenTypeId = true;
890 } else {
891 // We still need the type.
892 if (Tok.is(tok::l_paren)) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000893 SourceLocation LParen = ConsumeParen();
894 ParseSpecifierQualifierList(DS);
Sebastian Redl0c986032009-02-09 18:23:29 +0000895 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000896 ParseDeclarator(DeclaratorInfo);
897 MatchRHSPunctuation(tok::r_paren, LParen);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000898 ParenTypeId = true;
899 } else {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000900 if (ParseCXXTypeSpecifierSeq(DS))
901 DeclaratorInfo.setInvalidType(true);
Sebastian Redl0c986032009-02-09 18:23:29 +0000902 else {
903 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000904 ParseDeclaratorInternal(DeclaratorInfo,
905 &Parser::ParseDirectNewDeclarator);
Sebastian Redl0c986032009-02-09 18:23:29 +0000906 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000907 ParenTypeId = false;
908 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000909 }
910 } else {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000911 // A new-type-id is a simplified type-id, where essentially the
912 // direct-declarator is replaced by a direct-new-declarator.
913 if (ParseCXXTypeSpecifierSeq(DS))
914 DeclaratorInfo.setInvalidType(true);
Sebastian Redl0c986032009-02-09 18:23:29 +0000915 else {
916 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000917 ParseDeclaratorInternal(DeclaratorInfo,
918 &Parser::ParseDirectNewDeclarator);
Sebastian Redl0c986032009-02-09 18:23:29 +0000919 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000920 ParenTypeId = false;
921 }
Chris Lattner34c61332009-04-25 08:06:05 +0000922 if (DeclaratorInfo.isInvalidType()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000923 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl39d4f022008-12-11 22:51:44 +0000924 return ExprError();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000925 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000926
Sebastian Redl6008ac32008-11-25 22:21:31 +0000927 ExprVector ConstructorArgs(Actions);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000928 SourceLocation ConstructorLParen, ConstructorRParen;
929
930 if (Tok.is(tok::l_paren)) {
931 ConstructorLParen = ConsumeParen();
932 if (Tok.isNot(tok::r_paren)) {
933 CommaLocsTy CommaLocs;
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000934 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
935 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl39d4f022008-12-11 22:51:44 +0000936 return ExprError();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000937 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000938 }
939 ConstructorRParen = MatchRHSPunctuation(tok::r_paren, ConstructorLParen);
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000940 if (ConstructorRParen.isInvalid()) {
941 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl39d4f022008-12-11 22:51:44 +0000942 return ExprError();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000943 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000944 }
945
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000946 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
947 move_arg(PlacementArgs), PlacementRParen,
948 ParenTypeId, DeclaratorInfo, ConstructorLParen,
949 move_arg(ConstructorArgs), ConstructorRParen);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000950}
951
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000952/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
953/// passed to ParseDeclaratorInternal.
954///
955/// direct-new-declarator:
956/// '[' expression ']'
957/// direct-new-declarator '[' constant-expression ']'
958///
Chris Lattnere7de3612009-01-04 21:25:24 +0000959void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000960 // Parse the array dimensions.
961 bool first = true;
962 while (Tok.is(tok::l_square)) {
963 SourceLocation LLoc = ConsumeBracket();
Sebastian Redl14ca7412008-12-11 21:36:32 +0000964 OwningExprResult Size(first ? ParseExpression()
965 : ParseConstantExpression());
Sebastian Redlbb4dae72008-12-09 13:15:23 +0000966 if (Size.isInvalid()) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000967 // Recover
968 SkipUntil(tok::r_square);
969 return;
970 }
971 first = false;
972
Sebastian Redl0c986032009-02-09 18:23:29 +0000973 SourceLocation RLoc = MatchRHSPunctuation(tok::r_square, LLoc);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000974 D.AddTypeInfo(DeclaratorChunk::getArray(0, /*static=*/false, /*star=*/false,
Douglas Gregor1d381132009-07-06 15:59:29 +0000975 Size.release(), LLoc, RLoc),
Sebastian Redl0c986032009-02-09 18:23:29 +0000976 RLoc);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000977
Sebastian Redl0c986032009-02-09 18:23:29 +0000978 if (RLoc.isInvalid())
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000979 return;
980 }
981}
982
983/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
984/// This ambiguity appears in the syntax of the C++ new operator.
985///
986/// new-expression:
987/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
988/// new-initializer[opt]
989///
990/// new-placement:
991/// '(' expression-list ')'
992///
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000993bool Parser::ParseExpressionListOrTypeId(ExprListTy &PlacementArgs,
Chris Lattnere7de3612009-01-04 21:25:24 +0000994 Declarator &D) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000995 // The '(' was already consumed.
996 if (isTypeIdInParens()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000997 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redl0c986032009-02-09 18:23:29 +0000998 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000999 ParseDeclarator(D);
Chris Lattner34c61332009-04-25 08:06:05 +00001000 return D.isInvalidType();
Sebastian Redl19fec9d2008-11-21 19:14:01 +00001001 }
1002
1003 // It's not a type, it has to be an expression list.
1004 // Discard the comma locations - ActOnCXXNew has enough parameters.
1005 CommaLocsTy CommaLocs;
1006 return ParseExpressionList(PlacementArgs, CommaLocs);
1007}
1008
1009/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
1010/// to free memory allocated by new.
1011///
Chris Lattnere7de3612009-01-04 21:25:24 +00001012/// This method is called to parse the 'delete' expression after the optional
1013/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
1014/// and "Start" is its location. Otherwise, "Start" is the location of the
1015/// 'delete' token.
1016///
Sebastian Redl19fec9d2008-11-21 19:14:01 +00001017/// delete-expression:
1018/// '::'[opt] 'delete' cast-expression
1019/// '::'[opt] 'delete' '[' ']' cast-expression
Chris Lattnere7de3612009-01-04 21:25:24 +00001020Parser::OwningExprResult
1021Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
1022 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
1023 ConsumeToken(); // Consume 'delete'
Sebastian Redl19fec9d2008-11-21 19:14:01 +00001024
1025 // Array delete?
1026 bool ArrayDelete = false;
1027 if (Tok.is(tok::l_square)) {
1028 ArrayDelete = true;
1029 SourceLocation LHS = ConsumeBracket();
1030 SourceLocation RHS = MatchRHSPunctuation(tok::r_square, LHS);
1031 if (RHS.isInvalid())
Sebastian Redl39d4f022008-12-11 22:51:44 +00001032 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +00001033 }
1034
Sebastian Redl14ca7412008-12-11 21:36:32 +00001035 OwningExprResult Operand(ParseCastExpression(false));
Sebastian Redlbb4dae72008-12-09 13:15:23 +00001036 if (Operand.isInvalid())
Sebastian Redl39d4f022008-12-11 22:51:44 +00001037 return move(Operand);
Sebastian Redl19fec9d2008-11-21 19:14:01 +00001038
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00001039 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, move(Operand));
Sebastian Redl19fec9d2008-11-21 19:14:01 +00001040}
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001041
1042static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind)
1043{
1044 switch(kind) {
1045 default: assert(false && "Not a known unary type trait.");
1046 case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign;
1047 case tok::kw___has_nothrow_copy: return UTT_HasNothrowCopy;
1048 case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor;
1049 case tok::kw___has_trivial_assign: return UTT_HasTrivialAssign;
1050 case tok::kw___has_trivial_copy: return UTT_HasTrivialCopy;
1051 case tok::kw___has_trivial_constructor: return UTT_HasTrivialConstructor;
1052 case tok::kw___has_trivial_destructor: return UTT_HasTrivialDestructor;
1053 case tok::kw___has_virtual_destructor: return UTT_HasVirtualDestructor;
1054 case tok::kw___is_abstract: return UTT_IsAbstract;
1055 case tok::kw___is_class: return UTT_IsClass;
1056 case tok::kw___is_empty: return UTT_IsEmpty;
1057 case tok::kw___is_enum: return UTT_IsEnum;
1058 case tok::kw___is_pod: return UTT_IsPOD;
1059 case tok::kw___is_polymorphic: return UTT_IsPolymorphic;
1060 case tok::kw___is_union: return UTT_IsUnion;
1061 }
1062}
1063
1064/// ParseUnaryTypeTrait - Parse the built-in unary type-trait
1065/// pseudo-functions that allow implementation of the TR1/C++0x type traits
1066/// templates.
1067///
1068/// primary-expression:
1069/// [GNU] unary-type-trait '(' type-id ')'
1070///
1071Parser::OwningExprResult Parser::ParseUnaryTypeTrait()
1072{
1073 UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind());
1074 SourceLocation Loc = ConsumeToken();
1075
1076 SourceLocation LParen = Tok.getLocation();
1077 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
1078 return ExprError();
1079
1080 // FIXME: Error reporting absolutely sucks! If the this fails to parse a type
1081 // there will be cryptic errors about mismatched parentheses and missing
1082 // specifiers.
Douglas Gregor6c0f4062009-02-18 17:45:20 +00001083 TypeResult Ty = ParseTypeName();
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001084
1085 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen);
1086
Douglas Gregor6c0f4062009-02-18 17:45:20 +00001087 if (Ty.isInvalid())
1088 return ExprError();
1089
1090 return Actions.ActOnUnaryTypeTrait(UTT, Loc, LParen, Ty.get(), RParen);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001091}
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001092
1093/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
1094/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
1095/// based on the context past the parens.
1096Parser::OwningExprResult
1097Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
1098 TypeTy *&CastTy,
1099 SourceLocation LParenLoc,
1100 SourceLocation &RParenLoc) {
1101 assert(getLang().CPlusPlus && "Should only be called for C++!");
1102 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
1103 assert(isTypeIdInParens() && "Not a type-id!");
1104
1105 OwningExprResult Result(Actions, true);
1106 CastTy = 0;
1107
1108 // We need to disambiguate a very ugly part of the C++ syntax:
1109 //
1110 // (T())x; - type-id
1111 // (T())*x; - type-id
1112 // (T())/x; - expression
1113 // (T()); - expression
1114 //
1115 // The bad news is that we cannot use the specialized tentative parser, since
1116 // it can only verify that the thing inside the parens can be parsed as
1117 // type-id, it is not useful for determining the context past the parens.
1118 //
1119 // The good news is that the parser can disambiguate this part without
Argiris Kirtzidisdd9cbe12009-05-22 15:12:46 +00001120 // making any unnecessary Action calls.
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001121 //
1122 // It uses a scheme similar to parsing inline methods. The parenthesized
1123 // tokens are cached, the context that follows is determined (possibly by
1124 // parsing a cast-expression), and then we re-introduce the cached tokens
1125 // into the token stream and parse them appropriately.
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001126
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001127 ParenParseOption ParseAs;
1128 CachedTokens Toks;
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001129
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001130 // Store the tokens of the parentheses. We will parse them after we determine
1131 // the context that follows them.
1132 if (!ConsumeAndStoreUntil(tok::r_paren, tok::unknown, Toks, tok::semi)) {
1133 // We didn't find the ')' we expected.
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001134 MatchRHSPunctuation(tok::r_paren, LParenLoc);
1135 return ExprError();
1136 }
1137
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001138 if (Tok.is(tok::l_brace)) {
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001139 ParseAs = CompoundLiteral;
1140 } else {
1141 bool NotCastExpr;
Eli Friedmane4595942009-05-25 19:41:42 +00001142 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
1143 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
1144 NotCastExpr = true;
1145 } else {
1146 // Try parsing the cast-expression that may follow.
1147 // If it is not a cast-expression, NotCastExpr will be true and no token
1148 // will be consumed.
1149 Result = ParseCastExpression(false/*isUnaryExpression*/,
1150 false/*isAddressofOperand*/,
1151 NotCastExpr);
1152 }
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001153
1154 // If we parsed a cast-expression, it's really a type-id, otherwise it's
1155 // an expression.
1156 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001157 }
1158
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001159 // The current token should go after the cached tokens.
1160 Toks.push_back(Tok);
1161 // Re-enter the stored parenthesized tokens into the token stream, so we may
1162 // parse them now.
1163 PP.EnterTokenStream(Toks.data(), Toks.size(),
1164 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
1165 // Drop the current token and bring the first cached one. It's the same token
1166 // as when we entered this function.
1167 ConsumeAnyToken();
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001168
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001169 if (ParseAs >= CompoundLiteral) {
1170 TypeResult Ty = ParseTypeName();
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001171
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001172 // Match the ')'.
1173 if (Tok.is(tok::r_paren))
1174 RParenLoc = ConsumeParen();
1175 else
1176 MatchRHSPunctuation(tok::r_paren, LParenLoc);
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001177
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001178 if (ParseAs == CompoundLiteral) {
1179 ExprType = CompoundLiteral;
1180 return ParseCompoundLiteralExpression(Ty.get(), LParenLoc, RParenLoc);
1181 }
1182
1183 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
1184 assert(ParseAs == CastExpr);
1185
1186 if (Ty.isInvalid())
1187 return ExprError();
1188
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001189 CastTy = Ty.get();
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001190
1191 // Result is what ParseCastExpression returned earlier.
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001192 if (!Result.isInvalid())
1193 Result = Actions.ActOnCastExpr(LParenLoc, CastTy, RParenLoc,move(Result));
1194 return move(Result);
1195 }
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001196
1197 // Not a compound literal, and not followed by a cast-expression.
1198 assert(ParseAs == SimpleExpr);
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001199
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001200 ExprType = SimpleExpr;
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001201 Result = ParseExpression();
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001202 if (!Result.isInvalid() && Tok.is(tok::r_paren))
1203 Result = Actions.ActOnParenExpr(LParenLoc, Tok.getLocation(), move(Result));
1204
1205 // Match the ')'.
1206 if (Result.isInvalid()) {
1207 SkipUntil(tok::r_paren);
1208 return ExprError();
1209 }
Argiris Kirtzidis4e400d42009-05-22 21:09:47 +00001210
Argiris Kirtzidis785299b2009-05-22 10:24:42 +00001211 if (Tok.is(tok::r_paren))
1212 RParenLoc = ConsumeParen();
1213 else
1214 MatchRHSPunctuation(tok::r_paren, LParenLoc);
1215
1216 return move(Result);
1217}