1 //===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Expression parsing implementation. Expressions in
11 // C99 basically consist of a bunch of binary operators with unary operators and
12 // other random stuff at the leaves.
13 //
14 // In the C99 grammar, these unary operators bind tightest and are represented
15 // as the 'cast-expression' production. Everything else is either a binary
16 // operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
17 // handled by ParseCastExpression, the higher level pieces are handled by
18 // ParseBinaryExpression.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "clang/Parse/Parser.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/Scope.h"
25 #include "clang/Sema/ParsedTemplate.h"
26 #include "clang/Sema/TypoCorrection.h"
27 #include "clang/Basic/PrettyStackTrace.h"
28 #include "RAIIObjectsForParser.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/SmallString.h"
31 using namespace clang;
32
33 /// getBinOpPrecedence - Return the precedence of the specified binary operator
34 /// token.
getBinOpPrecedence(tok::TokenKind Kind,bool GreaterThanIsOperator,bool CPlusPlus0x)35 static prec::Level getBinOpPrecedence(tok::TokenKind Kind,
36 bool GreaterThanIsOperator,
37 bool CPlusPlus0x) {
38 switch (Kind) {
39 case tok::greater:
40 // C++ [temp.names]p3:
41 // [...] When parsing a template-argument-list, the first
42 // non-nested > is taken as the ending delimiter rather than a
43 // greater-than operator. [...]
44 if (GreaterThanIsOperator)
45 return prec::Relational;
46 return prec::Unknown;
47
48 case tok::greatergreater:
49 // C++0x [temp.names]p3:
50 //
51 // [...] Similarly, the first non-nested >> is treated as two
52 // consecutive but distinct > tokens, the first of which is
53 // taken as the end of the template-argument-list and completes
54 // the template-id. [...]
55 if (GreaterThanIsOperator || !CPlusPlus0x)
56 return prec::Shift;
57 return prec::Unknown;
58
59 default: return prec::Unknown;
60 case tok::comma: return prec::Comma;
61 case tok::equal:
62 case tok::starequal:
63 case tok::slashequal:
64 case tok::percentequal:
65 case tok::plusequal:
66 case tok::minusequal:
67 case tok::lesslessequal:
68 case tok::greatergreaterequal:
69 case tok::ampequal:
70 case tok::caretequal:
71 case tok::pipeequal: return prec::Assignment;
72 case tok::question: return prec::Conditional;
73 case tok::pipepipe: return prec::LogicalOr;
74 case tok::ampamp: return prec::LogicalAnd;
75 case tok::pipe: return prec::InclusiveOr;
76 case tok::caret: return prec::ExclusiveOr;
77 case tok::amp: return prec::And;
78 case tok::exclaimequal:
79 case tok::equalequal: return prec::Equality;
80 case tok::lessequal:
81 case tok::less:
82 case tok::greaterequal: return prec::Relational;
83 case tok::lessless: return prec::Shift;
84 case tok::plus:
85 case tok::minus: return prec::Additive;
86 case tok::percent:
87 case tok::slash:
88 case tok::star: return prec::Multiplicative;
89 case tok::periodstar:
90 case tok::arrowstar: return prec::PointerToMember;
91 }
92 }
93
94
95 /// ParseExpression - Simple precedence-based parser for binary/ternary
96 /// operators.
97 ///
98 /// Note: we diverge from the C99 grammar when parsing the assignment-expression
99 /// production. C99 specifies that the LHS of an assignment operator should be
100 /// parsed as a unary-expression, but consistency dictates that it be a
101 /// conditional-expession. In practice, the important thing here is that the
102 /// LHS of an assignment has to be an l-value, which productions between
103 /// unary-expression and conditional-expression don't produce. Because we want
104 /// consistency, we parse the LHS as a conditional-expression, then check for
105 /// l-value-ness in semantic analysis stages.
106 ///
107 /// pm-expression: [C++ 5.5]
108 /// cast-expression
109 /// pm-expression '.*' cast-expression
110 /// pm-expression '->*' cast-expression
111 ///
112 /// multiplicative-expression: [C99 6.5.5]
113 /// Note: in C++, apply pm-expression instead of cast-expression
114 /// cast-expression
115 /// multiplicative-expression '*' cast-expression
116 /// multiplicative-expression '/' cast-expression
117 /// multiplicative-expression '%' cast-expression
118 ///
119 /// additive-expression: [C99 6.5.6]
120 /// multiplicative-expression
121 /// additive-expression '+' multiplicative-expression
122 /// additive-expression '-' multiplicative-expression
123 ///
124 /// shift-expression: [C99 6.5.7]
125 /// additive-expression
126 /// shift-expression '<<' additive-expression
127 /// shift-expression '>>' additive-expression
128 ///
129 /// relational-expression: [C99 6.5.8]
130 /// shift-expression
131 /// relational-expression '<' shift-expression
132 /// relational-expression '>' shift-expression
133 /// relational-expression '<=' shift-expression
134 /// relational-expression '>=' shift-expression
135 ///
136 /// equality-expression: [C99 6.5.9]
137 /// relational-expression
138 /// equality-expression '==' relational-expression
139 /// equality-expression '!=' relational-expression
140 ///
141 /// AND-expression: [C99 6.5.10]
142 /// equality-expression
143 /// AND-expression '&' equality-expression
144 ///
145 /// exclusive-OR-expression: [C99 6.5.11]
146 /// AND-expression
147 /// exclusive-OR-expression '^' AND-expression
148 ///
149 /// inclusive-OR-expression: [C99 6.5.12]
150 /// exclusive-OR-expression
151 /// inclusive-OR-expression '|' exclusive-OR-expression
152 ///
153 /// logical-AND-expression: [C99 6.5.13]
154 /// inclusive-OR-expression
155 /// logical-AND-expression '&&' inclusive-OR-expression
156 ///
157 /// logical-OR-expression: [C99 6.5.14]
158 /// logical-AND-expression
159 /// logical-OR-expression '||' logical-AND-expression
160 ///
161 /// conditional-expression: [C99 6.5.15]
162 /// logical-OR-expression
163 /// logical-OR-expression '?' expression ':' conditional-expression
164 /// [GNU] logical-OR-expression '?' ':' conditional-expression
165 /// [C++] the third operand is an assignment-expression
166 ///
167 /// assignment-expression: [C99 6.5.16]
168 /// conditional-expression
169 /// unary-expression assignment-operator assignment-expression
170 /// [C++] throw-expression [C++ 15]
171 ///
172 /// assignment-operator: one of
173 /// = *= /= %= += -= <<= >>= &= ^= |=
174 ///
175 /// expression: [C99 6.5.17]
176 /// assignment-expression ...[opt]
177 /// expression ',' assignment-expression ...[opt]
ParseExpression(TypeCastState isTypeCast)178 ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
179 ExprResult LHS(ParseAssignmentExpression(isTypeCast));
180 return ParseRHSOfBinaryExpression(move(LHS), prec::Comma);
181 }
182
183 /// This routine is called when the '@' is seen and consumed.
184 /// Current token is an Identifier and is not a 'try'. This
185 /// routine is necessary to disambiguate @try-statement from,
186 /// for example, @encode-expression.
187 ///
188 ExprResult
ParseExpressionWithLeadingAt(SourceLocation AtLoc)189 Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
190 ExprResult LHS(ParseObjCAtExpression(AtLoc));
191 return ParseRHSOfBinaryExpression(move(LHS), prec::Comma);
192 }
193
194 /// This routine is called when a leading '__extension__' is seen and
195 /// consumed. This is necessary because the token gets consumed in the
196 /// process of disambiguating between an expression and a declaration.
197 ExprResult
ParseExpressionWithLeadingExtension(SourceLocation ExtLoc)198 Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
199 ExprResult LHS(true);
200 {
201 // Silence extension warnings in the sub-expression
202 ExtensionRAIIObject O(Diags);
203
204 LHS = ParseCastExpression(false);
205 }
206
207 if (!LHS.isInvalid())
208 LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
209 LHS.take());
210
211 return ParseRHSOfBinaryExpression(move(LHS), prec::Comma);
212 }
213
214 /// ParseAssignmentExpression - Parse an expr that doesn't include commas.
ParseAssignmentExpression(TypeCastState isTypeCast)215 ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
216 if (Tok.is(tok::code_completion)) {
217 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
218 cutOffParsing();
219 return ExprError();
220 }
221
222 if (Tok.is(tok::kw_throw))
223 return ParseThrowExpression();
224
225 ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false,
226 /*isAddressOfOperand=*/false,
227 isTypeCast);
228 return ParseRHSOfBinaryExpression(move(LHS), prec::Assignment);
229 }
230
231 /// ParseAssignmentExprWithObjCMessageExprStart - Parse an assignment expression
232 /// where part of an objc message send has already been parsed. In this case
233 /// LBracLoc indicates the location of the '[' of the message send, and either
234 /// ReceiverName or ReceiverExpr is non-null indicating the receiver of the
235 /// message.
236 ///
237 /// Since this handles full assignment-expression's, it handles postfix
238 /// expressions and other binary operators for these expressions as well.
239 ExprResult
ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,SourceLocation SuperLoc,ParsedType ReceiverType,Expr * ReceiverExpr)240 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
241 SourceLocation SuperLoc,
242 ParsedType ReceiverType,
243 Expr *ReceiverExpr) {
244 ExprResult R
245 = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
246 ReceiverType, ReceiverExpr);
247 R = ParsePostfixExpressionSuffix(R);
248 return ParseRHSOfBinaryExpression(R, prec::Assignment);
249 }
250
251
ParseConstantExpression(TypeCastState isTypeCast)252 ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
253 // C++03 [basic.def.odr]p2:
254 // An expression is potentially evaluated unless it appears where an
255 // integral constant expression is required (see 5.19) [...].
256 // C++98 and C++11 have no such rule, but this is only a defect in C++98.
257 EnterExpressionEvaluationContext Unevaluated(Actions,
258 Sema::ConstantEvaluated);
259
260 ExprResult LHS(ParseCastExpression(false, false, isTypeCast));
261 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
262 return Actions.ActOnConstantExpression(Res);
263 }
264
265 /// ParseRHSOfBinaryExpression - Parse a binary expression that starts with
266 /// LHS and has a precedence of at least MinPrec.
267 ExprResult
ParseRHSOfBinaryExpression(ExprResult LHS,prec::Level MinPrec)268 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
269 prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
270 GreaterThanIsOperator,
271 getLangOpts().CPlusPlus0x);
272 SourceLocation ColonLoc;
273
274 while (1) {
275 // If this token has a lower precedence than we are allowed to parse (e.g.
276 // because we are called recursively, or because the token is not a binop),
277 // then we are done!
278 if (NextTokPrec < MinPrec)
279 return move(LHS);
280
281 // Consume the operator, saving the operator token for error reporting.
282 Token OpToken = Tok;
283 ConsumeToken();
284
285 // Special case handling for the ternary operator.
286 ExprResult TernaryMiddle(true);
287 if (NextTokPrec == prec::Conditional) {
288 if (Tok.isNot(tok::colon)) {
289 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
290 ColonProtectionRAIIObject X(*this);
291
292 // Handle this production specially:
293 // logical-OR-expression '?' expression ':' conditional-expression
294 // In particular, the RHS of the '?' is 'expression', not
295 // 'logical-OR-expression' as we might expect.
296 TernaryMiddle = ParseExpression();
297 if (TernaryMiddle.isInvalid()) {
298 LHS = ExprError();
299 TernaryMiddle = 0;
300 }
301 } else {
302 // Special case handling of "X ? Y : Z" where Y is empty:
303 // logical-OR-expression '?' ':' conditional-expression [GNU]
304 TernaryMiddle = 0;
305 Diag(Tok, diag::ext_gnu_conditional_expr);
306 }
307
308 if (Tok.is(tok::colon)) {
309 // Eat the colon.
310 ColonLoc = ConsumeToken();
311 } else {
312 // Otherwise, we're missing a ':'. Assume that this was a typo that
313 // the user forgot. If we're not in a macro expansion, we can suggest
314 // a fixit hint. If there were two spaces before the current token,
315 // suggest inserting the colon in between them, otherwise insert ": ".
316 SourceLocation FILoc = Tok.getLocation();
317 const char *FIText = ": ";
318 const SourceManager &SM = PP.getSourceManager();
319 if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
320 assert(FILoc.isFileID());
321 bool IsInvalid = false;
322 const char *SourcePtr =
323 SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
324 if (!IsInvalid && *SourcePtr == ' ') {
325 SourcePtr =
326 SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
327 if (!IsInvalid && *SourcePtr == ' ') {
328 FILoc = FILoc.getLocWithOffset(-1);
329 FIText = ":";
330 }
331 }
332 }
333
334 Diag(Tok, diag::err_expected_colon)
335 << FixItHint::CreateInsertion(FILoc, FIText);
336 Diag(OpToken, diag::note_matching) << "?";
337 ColonLoc = Tok.getLocation();
338 }
339 }
340
341 // Code completion for the right-hand side of an assignment expression
342 // goes through a special hook that takes the left-hand side into account.
343 if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
344 Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
345 cutOffParsing();
346 return ExprError();
347 }
348
349 // Parse another leaf here for the RHS of the operator.
350 // ParseCastExpression works here because all RHS expressions in C have it
351 // as a prefix, at least. However, in C++, an assignment-expression could
352 // be a throw-expression, which is not a valid cast-expression.
353 // Therefore we need some special-casing here.
354 // Also note that the third operand of the conditional operator is
355 // an assignment-expression in C++, and in C++11, we can have a
356 // braced-init-list on the RHS of an assignment. For better diagnostics,
357 // parse as if we were allowed braced-init-lists everywhere, and check that
358 // they only appear on the RHS of assignments later.
359 ExprResult RHS;
360 bool RHSIsInitList = false;
361 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
362 RHS = ParseBraceInitializer();
363 RHSIsInitList = true;
364 } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
365 RHS = ParseAssignmentExpression();
366 else
367 RHS = ParseCastExpression(false);
368
369 if (RHS.isInvalid())
370 LHS = ExprError();
371
372 // Remember the precedence of this operator and get the precedence of the
373 // operator immediately to the right of the RHS.
374 prec::Level ThisPrec = NextTokPrec;
375 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
376 getLangOpts().CPlusPlus0x);
377
378 // Assignment and conditional expressions are right-associative.
379 bool isRightAssoc = ThisPrec == prec::Conditional ||
380 ThisPrec == prec::Assignment;
381
382 // Get the precedence of the operator to the right of the RHS. If it binds
383 // more tightly with RHS than we do, evaluate it completely first.
384 if (ThisPrec < NextTokPrec ||
385 (ThisPrec == NextTokPrec && isRightAssoc)) {
386 if (!RHS.isInvalid() && RHSIsInitList) {
387 Diag(Tok, diag::err_init_list_bin_op)
388 << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
389 RHS = ExprError();
390 }
391 // If this is left-associative, only parse things on the RHS that bind
392 // more tightly than the current operator. If it is left-associative, it
393 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
394 // A=(B=(C=D)), where each paren is a level of recursion here.
395 // The function takes ownership of the RHS.
396 RHS = ParseRHSOfBinaryExpression(RHS,
397 static_cast<prec::Level>(ThisPrec + !isRightAssoc));
398 RHSIsInitList = false;
399
400 if (RHS.isInvalid())
401 LHS = ExprError();
402
403 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
404 getLangOpts().CPlusPlus0x);
405 }
406 assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
407
408 if (!RHS.isInvalid() && RHSIsInitList) {
409 if (ThisPrec == prec::Assignment) {
410 Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
411 << Actions.getExprRange(RHS.get());
412 } else {
413 Diag(OpToken, diag::err_init_list_bin_op)
414 << /*RHS*/1 << PP.getSpelling(OpToken)
415 << Actions.getExprRange(RHS.get());
416 LHS = ExprError();
417 }
418 }
419
420 if (!LHS.isInvalid()) {
421 // Combine the LHS and RHS into the LHS (e.g. build AST).
422 if (TernaryMiddle.isInvalid()) {
423 // If we're using '>>' as an operator within a template
424 // argument list (in C++98), suggest the addition of
425 // parentheses so that the code remains well-formed in C++0x.
426 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
427 SuggestParentheses(OpToken.getLocation(),
428 diag::warn_cxx0x_right_shift_in_template_arg,
429 SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
430 Actions.getExprRange(RHS.get()).getEnd()));
431
432 LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
433 OpToken.getKind(), LHS.take(), RHS.take());
434 } else
435 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
436 LHS.take(), TernaryMiddle.take(),
437 RHS.take());
438 }
439 }
440 }
441
442 /// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
443 /// true, parse a unary-expression. isAddressOfOperand exists because an
444 /// id-expression that is the operand of address-of gets special treatment
445 /// due to member pointers.
446 ///
ParseCastExpression(bool isUnaryExpression,bool isAddressOfOperand,TypeCastState isTypeCast)447 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
448 bool isAddressOfOperand,
449 TypeCastState isTypeCast) {
450 bool NotCastExpr;
451 ExprResult Res = ParseCastExpression(isUnaryExpression,
452 isAddressOfOperand,
453 NotCastExpr,
454 isTypeCast);
455 if (NotCastExpr)
456 Diag(Tok, diag::err_expected_expression);
457 return move(Res);
458 }
459
460 namespace {
461 class CastExpressionIdValidator : public CorrectionCandidateCallback {
462 public:
CastExpressionIdValidator(bool AllowTypes,bool AllowNonTypes)463 CastExpressionIdValidator(bool AllowTypes, bool AllowNonTypes)
464 : AllowNonTypes(AllowNonTypes) {
465 WantTypeSpecifiers = AllowTypes;
466 }
467
ValidateCandidate(const TypoCorrection & candidate)468 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
469 NamedDecl *ND = candidate.getCorrectionDecl();
470 if (!ND)
471 return candidate.isKeyword();
472
473 if (isa<TypeDecl>(ND))
474 return WantTypeSpecifiers;
475 return AllowNonTypes;
476 }
477
478 private:
479 bool AllowNonTypes;
480 };
481 }
482
483 /// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
484 /// true, parse a unary-expression. isAddressOfOperand exists because an
485 /// id-expression that is the operand of address-of gets special treatment
486 /// due to member pointers. NotCastExpr is set to true if the token is not the
487 /// start of a cast-expression, and no diagnostic is emitted in this case.
488 ///
489 /// cast-expression: [C99 6.5.4]
490 /// unary-expression
491 /// '(' type-name ')' cast-expression
492 ///
493 /// unary-expression: [C99 6.5.3]
494 /// postfix-expression
495 /// '++' unary-expression
496 /// '--' unary-expression
497 /// unary-operator cast-expression
498 /// 'sizeof' unary-expression
499 /// 'sizeof' '(' type-name ')'
500 /// [C++11] 'sizeof' '...' '(' identifier ')'
501 /// [GNU] '__alignof' unary-expression
502 /// [GNU] '__alignof' '(' type-name ')'
503 /// [C++11] 'alignof' '(' type-id ')'
504 /// [GNU] '&&' identifier
505 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
506 /// [C++] new-expression
507 /// [C++] delete-expression
508 ///
509 /// unary-operator: one of
510 /// '&' '*' '+' '-' '~' '!'
511 /// [GNU] '__extension__' '__real' '__imag'
512 ///
513 /// primary-expression: [C99 6.5.1]
514 /// [C99] identifier
515 /// [C++] id-expression
516 /// constant
517 /// string-literal
518 /// [C++] boolean-literal [C++ 2.13.5]
519 /// [C++11] 'nullptr' [C++11 2.14.7]
520 /// [C++11] user-defined-literal
521 /// '(' expression ')'
522 /// [C11] generic-selection
523 /// '__func__' [C99 6.4.2.2]
524 /// [GNU] '__FUNCTION__'
525 /// [GNU] '__PRETTY_FUNCTION__'
526 /// [GNU] '(' compound-statement ')'
527 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
528 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
529 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
530 /// assign-expr ')'
531 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
532 /// [GNU] '__null'
533 /// [OBJC] '[' objc-message-expr ']'
534 /// [OBJC] '@selector' '(' objc-selector-arg ')'
535 /// [OBJC] '@protocol' '(' identifier ')'
536 /// [OBJC] '@encode' '(' type-name ')'
537 /// [OBJC] objc-string-literal
538 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
539 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
540 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
541 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
542 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
543 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
544 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
545 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
546 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
547 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
548 /// [C++] 'this' [C++ 9.3.2]
549 /// [G++] unary-type-trait '(' type-id ')'
550 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
551 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
552 /// [clang] '^' block-literal
553 ///
554 /// constant: [C99 6.4.4]
555 /// integer-constant
556 /// floating-constant
557 /// enumeration-constant -> identifier
558 /// character-constant
559 ///
560 /// id-expression: [C++ 5.1]
561 /// unqualified-id
562 /// qualified-id
563 ///
564 /// unqualified-id: [C++ 5.1]
565 /// identifier
566 /// operator-function-id
567 /// conversion-function-id
568 /// '~' class-name
569 /// template-id
570 ///
571 /// new-expression: [C++ 5.3.4]
572 /// '::'[opt] 'new' new-placement[opt] new-type-id
573 /// new-initializer[opt]
574 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
575 /// new-initializer[opt]
576 ///
577 /// delete-expression: [C++ 5.3.5]
578 /// '::'[opt] 'delete' cast-expression
579 /// '::'[opt] 'delete' '[' ']' cast-expression
580 ///
581 /// [GNU/Embarcadero] unary-type-trait:
582 /// '__is_arithmetic'
583 /// '__is_floating_point'
584 /// '__is_integral'
585 /// '__is_lvalue_expr'
586 /// '__is_rvalue_expr'
587 /// '__is_complete_type'
588 /// '__is_void'
589 /// '__is_array'
590 /// '__is_function'
591 /// '__is_reference'
592 /// '__is_lvalue_reference'
593 /// '__is_rvalue_reference'
594 /// '__is_fundamental'
595 /// '__is_object'
596 /// '__is_scalar'
597 /// '__is_compound'
598 /// '__is_pointer'
599 /// '__is_member_object_pointer'
600 /// '__is_member_function_pointer'
601 /// '__is_member_pointer'
602 /// '__is_const'
603 /// '__is_volatile'
604 /// '__is_trivial'
605 /// '__is_standard_layout'
606 /// '__is_signed'
607 /// '__is_unsigned'
608 ///
609 /// [GNU] unary-type-trait:
610 /// '__has_nothrow_assign'
611 /// '__has_nothrow_copy'
612 /// '__has_nothrow_constructor'
613 /// '__has_trivial_assign' [TODO]
614 /// '__has_trivial_copy' [TODO]
615 /// '__has_trivial_constructor'
616 /// '__has_trivial_destructor'
617 /// '__has_virtual_destructor'
618 /// '__is_abstract' [TODO]
619 /// '__is_class'
620 /// '__is_empty' [TODO]
621 /// '__is_enum'
622 /// '__is_final'
623 /// '__is_pod'
624 /// '__is_polymorphic'
625 /// '__is_trivial'
626 /// '__is_union'
627 ///
628 /// [Clang] unary-type-trait:
629 /// '__trivially_copyable'
630 ///
631 /// binary-type-trait:
632 /// [GNU] '__is_base_of'
633 /// [MS] '__is_convertible_to'
634 /// '__is_convertible'
635 /// '__is_same'
636 ///
637 /// [Embarcadero] array-type-trait:
638 /// '__array_rank'
639 /// '__array_extent'
640 ///
641 /// [Embarcadero] expression-trait:
642 /// '__is_lvalue_expr'
643 /// '__is_rvalue_expr'
644 ///
ParseCastExpression(bool isUnaryExpression,bool isAddressOfOperand,bool & NotCastExpr,TypeCastState isTypeCast)645 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
646 bool isAddressOfOperand,
647 bool &NotCastExpr,
648 TypeCastState isTypeCast) {
649 ExprResult Res;
650 tok::TokenKind SavedKind = Tok.getKind();
651 NotCastExpr = false;
652
653 // This handles all of cast-expression, unary-expression, postfix-expression,
654 // and primary-expression. We handle them together like this for efficiency
655 // and to simplify handling of an expression starting with a '(' token: which
656 // may be one of a parenthesized expression, cast-expression, compound literal
657 // expression, or statement expression.
658 //
659 // If the parsed tokens consist of a primary-expression, the cases below
660 // break out of the switch; at the end we call ParsePostfixExpressionSuffix
661 // to handle the postfix expression suffixes. Cases that cannot be followed
662 // by postfix exprs should return without invoking
663 // ParsePostfixExpressionSuffix.
664 switch (SavedKind) {
665 case tok::l_paren: {
666 // If this expression is limited to being a unary-expression, the parent can
667 // not start a cast expression.
668 ParenParseOption ParenExprType =
669 (isUnaryExpression && !getLangOpts().CPlusPlus)? CompoundLiteral : CastExpr;
670 ParsedType CastTy;
671 SourceLocation RParenLoc;
672
673 {
674 // The inside of the parens don't need to be a colon protected scope, and
675 // isn't immediately a message send.
676 ColonProtectionRAIIObject X(*this, false);
677
678 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
679 isTypeCast == IsTypeCast, CastTy, RParenLoc);
680 }
681
682 switch (ParenExprType) {
683 case SimpleExpr: break; // Nothing else to do.
684 case CompoundStmt: break; // Nothing else to do.
685 case CompoundLiteral:
686 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
687 // postfix-expression exist, parse them now.
688 break;
689 case CastExpr:
690 // We have parsed the cast-expression and no postfix-expr pieces are
691 // following.
692 return move(Res);
693 }
694
695 break;
696 }
697
698 // primary-expression
699 case tok::numeric_constant:
700 // constant: integer-constant
701 // constant: floating-constant
702
703 Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
704 ConsumeToken();
705 break;
706
707 case tok::kw_true:
708 case tok::kw_false:
709 return ParseCXXBoolLiteral();
710
711 case tok::kw___objc_yes:
712 case tok::kw___objc_no:
713 return ParseObjCBoolLiteral();
714
715 case tok::kw_nullptr:
716 Diag(Tok, diag::warn_cxx98_compat_nullptr);
717 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
718
719 case tok::annot_primary_expr:
720 assert(Res.get() == 0 && "Stray primary-expression annotation?");
721 Res = getExprAnnotation(Tok);
722 ConsumeToken();
723 break;
724
725 case tok::kw_decltype:
726 case tok::identifier: { // primary-expression: identifier
727 // unqualified-id: identifier
728 // constant: enumeration-constant
729 // Turn a potentially qualified name into a annot_typename or
730 // annot_cxxscope if it would be valid. This handles things like x::y, etc.
731 if (getLangOpts().CPlusPlus) {
732 // Avoid the unnecessary parse-time lookup in the common case
733 // where the syntax forbids a type.
734 const Token &Next = NextToken();
735 if (Next.is(tok::coloncolon) ||
736 (!ColonIsSacred && Next.is(tok::colon)) ||
737 Next.is(tok::less) ||
738 Next.is(tok::l_paren) ||
739 Next.is(tok::l_brace)) {
740 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
741 if (TryAnnotateTypeOrScopeToken())
742 return ExprError();
743 if (!Tok.is(tok::identifier))
744 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
745 }
746 }
747
748 // Consume the identifier so that we can see if it is followed by a '(' or
749 // '.'.
750 IdentifierInfo &II = *Tok.getIdentifierInfo();
751 SourceLocation ILoc = ConsumeToken();
752
753 // Support 'Class.property' and 'super.property' notation.
754 if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
755 (Actions.getTypeName(II, ILoc, getCurScope()) ||
756 // Allow the base to be 'super' if in an objc-method.
757 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
758 ConsumeToken();
759
760 // Allow either an identifier or the keyword 'class' (in C++).
761 if (Tok.isNot(tok::identifier) &&
762 !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
763 Diag(Tok, diag::err_expected_property_name);
764 return ExprError();
765 }
766 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
767 SourceLocation PropertyLoc = ConsumeToken();
768
769 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
770 ILoc, PropertyLoc);
771 break;
772 }
773
774 // In an Objective-C method, if we have "super" followed by an identifier,
775 // the token sequence is ill-formed. However, if there's a ':' or ']' after
776 // that identifier, this is probably a message send with a missing open
777 // bracket. Treat it as such.
778 if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
779 getCurScope()->isInObjcMethodScope() &&
780 ((Tok.is(tok::identifier) &&
781 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
782 Tok.is(tok::code_completion))) {
783 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(),
784 0);
785 break;
786 }
787
788 // If we have an Objective-C class name followed by an identifier
789 // and either ':' or ']', this is an Objective-C class message
790 // send that's missing the opening '['. Recovery
791 // appropriately. Also take this path if we're performing code
792 // completion after an Objective-C class name.
793 if (getLangOpts().ObjC1 &&
794 ((Tok.is(tok::identifier) && !InMessageExpression) ||
795 Tok.is(tok::code_completion))) {
796 const Token& Next = NextToken();
797 if (Tok.is(tok::code_completion) ||
798 Next.is(tok::colon) || Next.is(tok::r_square))
799 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
800 if (Typ.get()->isObjCObjectOrInterfaceType()) {
801 // Fake up a Declarator to use with ActOnTypeName.
802 DeclSpec DS(AttrFactory);
803 DS.SetRangeStart(ILoc);
804 DS.SetRangeEnd(ILoc);
805 const char *PrevSpec = 0;
806 unsigned DiagID;
807 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ);
808
809 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
810 TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
811 DeclaratorInfo);
812 if (Ty.isInvalid())
813 break;
814
815 Res = ParseObjCMessageExpressionBody(SourceLocation(),
816 SourceLocation(),
817 Ty.get(), 0);
818 break;
819 }
820 }
821
822 // Make sure to pass down the right value for isAddressOfOperand.
823 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
824 isAddressOfOperand = false;
825
826 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
827 // need to know whether or not this identifier is a function designator or
828 // not.
829 UnqualifiedId Name;
830 CXXScopeSpec ScopeSpec;
831 SourceLocation TemplateKWLoc;
832 CastExpressionIdValidator Validator(isTypeCast != NotTypeCast,
833 isTypeCast != IsTypeCast);
834 Name.setIdentifier(&II, ILoc);
835 Res = Actions.ActOnIdExpression(getCurScope(), ScopeSpec, TemplateKWLoc,
836 Name, Tok.is(tok::l_paren),
837 isAddressOfOperand, &Validator);
838 break;
839 }
840 case tok::char_constant: // constant: character-constant
841 case tok::wide_char_constant:
842 case tok::utf16_char_constant:
843 case tok::utf32_char_constant:
844 Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
845 ConsumeToken();
846 break;
847 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
848 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
849 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
850 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
851 ConsumeToken();
852 break;
853 case tok::string_literal: // primary-expression: string-literal
854 case tok::wide_string_literal:
855 case tok::utf8_string_literal:
856 case tok::utf16_string_literal:
857 case tok::utf32_string_literal:
858 Res = ParseStringLiteralExpression(true);
859 break;
860 case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
861 Res = ParseGenericSelectionExpression();
862 break;
863 case tok::kw___builtin_va_arg:
864 case tok::kw___builtin_offsetof:
865 case tok::kw___builtin_choose_expr:
866 case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
867 return ParseBuiltinPrimaryExpression();
868 case tok::kw___null:
869 return Actions.ActOnGNUNullExpr(ConsumeToken());
870
871 case tok::plusplus: // unary-expression: '++' unary-expression [C99]
872 case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
873 // C++ [expr.unary] has:
874 // unary-expression:
875 // ++ cast-expression
876 // -- cast-expression
877 SourceLocation SavedLoc = ConsumeToken();
878 Res = ParseCastExpression(!getLangOpts().CPlusPlus);
879 if (!Res.isInvalid())
880 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
881 return move(Res);
882 }
883 case tok::amp: { // unary-expression: '&' cast-expression
884 // Special treatment because of member pointers
885 SourceLocation SavedLoc = ConsumeToken();
886 Res = ParseCastExpression(false, true);
887 if (!Res.isInvalid())
888 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
889 return move(Res);
890 }
891
892 case tok::star: // unary-expression: '*' cast-expression
893 case tok::plus: // unary-expression: '+' cast-expression
894 case tok::minus: // unary-expression: '-' cast-expression
895 case tok::tilde: // unary-expression: '~' cast-expression
896 case tok::exclaim: // unary-expression: '!' cast-expression
897 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
898 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
899 SourceLocation SavedLoc = ConsumeToken();
900 Res = ParseCastExpression(false);
901 if (!Res.isInvalid())
902 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
903 return move(Res);
904 }
905
906 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
907 // __extension__ silences extension warnings in the subexpression.
908 ExtensionRAIIObject O(Diags); // Use RAII to do this.
909 SourceLocation SavedLoc = ConsumeToken();
910 Res = ParseCastExpression(false);
911 if (!Res.isInvalid())
912 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
913 return move(Res);
914 }
915 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
916 // unary-expression: 'sizeof' '(' type-name ')'
917 case tok::kw_alignof:
918 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
919 // unary-expression: '__alignof' '(' type-name ')'
920 // unary-expression: 'alignof' '(' type-id ')'
921 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
922 return ParseUnaryExprOrTypeTraitExpression();
923 case tok::ampamp: { // unary-expression: '&&' identifier
924 SourceLocation AmpAmpLoc = ConsumeToken();
925 if (Tok.isNot(tok::identifier))
926 return ExprError(Diag(Tok, diag::err_expected_ident));
927
928 if (getCurScope()->getFnParent() == 0)
929 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
930
931 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
932 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
933 Tok.getLocation());
934 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
935 ConsumeToken();
936 return move(Res);
937 }
938 case tok::kw_const_cast:
939 case tok::kw_dynamic_cast:
940 case tok::kw_reinterpret_cast:
941 case tok::kw_static_cast:
942 Res = ParseCXXCasts();
943 break;
944 case tok::kw_typeid:
945 Res = ParseCXXTypeid();
946 break;
947 case tok::kw___uuidof:
948 Res = ParseCXXUuidof();
949 break;
950 case tok::kw_this:
951 Res = ParseCXXThis();
952 break;
953
954 case tok::annot_typename:
955 if (isStartOfObjCClassMessageMissingOpenBracket()) {
956 ParsedType Type = getTypeAnnotation(Tok);
957
958 // Fake up a Declarator to use with ActOnTypeName.
959 DeclSpec DS(AttrFactory);
960 DS.SetRangeStart(Tok.getLocation());
961 DS.SetRangeEnd(Tok.getLastLoc());
962
963 const char *PrevSpec = 0;
964 unsigned DiagID;
965 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
966 PrevSpec, DiagID, Type);
967
968 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
969 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
970 if (Ty.isInvalid())
971 break;
972
973 ConsumeToken();
974 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
975 Ty.get(), 0);
976 break;
977 }
978 // Fall through
979
980 case tok::annot_decltype:
981 case tok::kw_char:
982 case tok::kw_wchar_t:
983 case tok::kw_char16_t:
984 case tok::kw_char32_t:
985 case tok::kw_bool:
986 case tok::kw_short:
987 case tok::kw_int:
988 case tok::kw_long:
989 case tok::kw___int64:
990 case tok::kw___int128:
991 case tok::kw_signed:
992 case tok::kw_unsigned:
993 case tok::kw_half:
994 case tok::kw_float:
995 case tok::kw_double:
996 case tok::kw_void:
997 case tok::kw_typename:
998 case tok::kw_typeof:
999 case tok::kw___vector: {
1000 if (!getLangOpts().CPlusPlus) {
1001 Diag(Tok, diag::err_expected_expression);
1002 return ExprError();
1003 }
1004
1005 if (SavedKind == tok::kw_typename) {
1006 // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1007 // typename-specifier braced-init-list
1008 if (TryAnnotateTypeOrScopeToken())
1009 return ExprError();
1010 }
1011
1012 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1013 // simple-type-specifier braced-init-list
1014 //
1015 DeclSpec DS(AttrFactory);
1016 ParseCXXSimpleTypeSpecifier(DS);
1017 if (Tok.isNot(tok::l_paren) &&
1018 (!getLangOpts().CPlusPlus0x || Tok.isNot(tok::l_brace)))
1019 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1020 << DS.getSourceRange());
1021
1022 if (Tok.is(tok::l_brace))
1023 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1024
1025 Res = ParseCXXTypeConstructExpression(DS);
1026 break;
1027 }
1028
1029 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1030 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1031 // (We can end up in this situation after tentative parsing.)
1032 if (TryAnnotateTypeOrScopeToken())
1033 return ExprError();
1034 if (!Tok.is(tok::annot_cxxscope))
1035 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1036 NotCastExpr, isTypeCast);
1037
1038 Token Next = NextToken();
1039 if (Next.is(tok::annot_template_id)) {
1040 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1041 if (TemplateId->Kind == TNK_Type_template) {
1042 // We have a qualified template-id that we know refers to a
1043 // type, translate it into a type and continue parsing as a
1044 // cast expression.
1045 CXXScopeSpec SS;
1046 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1047 /*EnteringContext=*/false);
1048 AnnotateTemplateIdTokenAsType();
1049 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1050 NotCastExpr, isTypeCast);
1051 }
1052 }
1053
1054 // Parse as an id-expression.
1055 Res = ParseCXXIdExpression(isAddressOfOperand);
1056 break;
1057 }
1058
1059 case tok::annot_template_id: { // [C++] template-id
1060 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1061 if (TemplateId->Kind == TNK_Type_template) {
1062 // We have a template-id that we know refers to a type,
1063 // translate it into a type and continue parsing as a cast
1064 // expression.
1065 AnnotateTemplateIdTokenAsType();
1066 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1067 NotCastExpr, isTypeCast);
1068 }
1069
1070 // Fall through to treat the template-id as an id-expression.
1071 }
1072
1073 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1074 Res = ParseCXXIdExpression(isAddressOfOperand);
1075 break;
1076
1077 case tok::coloncolon: {
1078 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1079 // annotates the token, tail recurse.
1080 if (TryAnnotateTypeOrScopeToken())
1081 return ExprError();
1082 if (!Tok.is(tok::coloncolon))
1083 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
1084
1085 // ::new -> [C++] new-expression
1086 // ::delete -> [C++] delete-expression
1087 SourceLocation CCLoc = ConsumeToken();
1088 if (Tok.is(tok::kw_new))
1089 return ParseCXXNewExpression(true, CCLoc);
1090 if (Tok.is(tok::kw_delete))
1091 return ParseCXXDeleteExpression(true, CCLoc);
1092
1093 // This is not a type name or scope specifier, it is an invalid expression.
1094 Diag(CCLoc, diag::err_expected_expression);
1095 return ExprError();
1096 }
1097
1098 case tok::kw_new: // [C++] new-expression
1099 return ParseCXXNewExpression(false, Tok.getLocation());
1100
1101 case tok::kw_delete: // [C++] delete-expression
1102 return ParseCXXDeleteExpression(false, Tok.getLocation());
1103
1104 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1105 Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1106 SourceLocation KeyLoc = ConsumeToken();
1107 BalancedDelimiterTracker T(*this, tok::l_paren);
1108
1109 if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1110 return ExprError();
1111 // C++11 [expr.unary.noexcept]p1:
1112 // The noexcept operator determines whether the evaluation of its operand,
1113 // which is an unevaluated operand, can throw an exception.
1114 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1115 ExprResult Result = ParseExpression();
1116
1117 T.consumeClose();
1118
1119 if (!Result.isInvalid())
1120 Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
1121 Result.take(), T.getCloseLocation());
1122 return move(Result);
1123 }
1124
1125 case tok::kw___is_abstract: // [GNU] unary-type-trait
1126 case tok::kw___is_class:
1127 case tok::kw___is_empty:
1128 case tok::kw___is_enum:
1129 case tok::kw___is_literal:
1130 case tok::kw___is_arithmetic:
1131 case tok::kw___is_integral:
1132 case tok::kw___is_floating_point:
1133 case tok::kw___is_complete_type:
1134 case tok::kw___is_void:
1135 case tok::kw___is_array:
1136 case tok::kw___is_function:
1137 case tok::kw___is_reference:
1138 case tok::kw___is_lvalue_reference:
1139 case tok::kw___is_rvalue_reference:
1140 case tok::kw___is_fundamental:
1141 case tok::kw___is_object:
1142 case tok::kw___is_scalar:
1143 case tok::kw___is_compound:
1144 case tok::kw___is_pointer:
1145 case tok::kw___is_member_object_pointer:
1146 case tok::kw___is_member_function_pointer:
1147 case tok::kw___is_member_pointer:
1148 case tok::kw___is_const:
1149 case tok::kw___is_volatile:
1150 case tok::kw___is_standard_layout:
1151 case tok::kw___is_signed:
1152 case tok::kw___is_unsigned:
1153 case tok::kw___is_literal_type:
1154 case tok::kw___is_pod:
1155 case tok::kw___is_polymorphic:
1156 case tok::kw___is_trivial:
1157 case tok::kw___is_trivially_copyable:
1158 case tok::kw___is_union:
1159 case tok::kw___is_final:
1160 case tok::kw___has_trivial_constructor:
1161 case tok::kw___has_trivial_copy:
1162 case tok::kw___has_trivial_assign:
1163 case tok::kw___has_trivial_destructor:
1164 case tok::kw___has_nothrow_assign:
1165 case tok::kw___has_nothrow_copy:
1166 case tok::kw___has_nothrow_constructor:
1167 case tok::kw___has_virtual_destructor:
1168 return ParseUnaryTypeTrait();
1169
1170 case tok::kw___builtin_types_compatible_p:
1171 case tok::kw___is_base_of:
1172 case tok::kw___is_same:
1173 case tok::kw___is_convertible:
1174 case tok::kw___is_convertible_to:
1175 case tok::kw___is_trivially_assignable:
1176 return ParseBinaryTypeTrait();
1177
1178 case tok::kw___is_trivially_constructible:
1179 return ParseTypeTrait();
1180
1181 case tok::kw___array_rank:
1182 case tok::kw___array_extent:
1183 return ParseArrayTypeTrait();
1184
1185 case tok::kw___is_lvalue_expr:
1186 case tok::kw___is_rvalue_expr:
1187 return ParseExpressionTrait();
1188
1189 case tok::at: {
1190 SourceLocation AtLoc = ConsumeToken();
1191 return ParseObjCAtExpression(AtLoc);
1192 }
1193 case tok::caret:
1194 Res = ParseBlockLiteralExpression();
1195 break;
1196 case tok::code_completion: {
1197 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1198 cutOffParsing();
1199 return ExprError();
1200 }
1201 case tok::l_square:
1202 if (getLangOpts().CPlusPlus0x) {
1203 if (getLangOpts().ObjC1) {
1204 // C++11 lambda expressions and Objective-C message sends both start with a
1205 // square bracket. There are three possibilities here:
1206 // we have a valid lambda expression, we have an invalid lambda
1207 // expression, or we have something that doesn't appear to be a lambda.
1208 // If we're in the last case, we fall back to ParseObjCMessageExpression.
1209 Res = TryParseLambdaExpression();
1210 if (!Res.isInvalid() && !Res.get())
1211 Res = ParseObjCMessageExpression();
1212 break;
1213 }
1214 Res = ParseLambdaExpression();
1215 break;
1216 }
1217 if (getLangOpts().ObjC1) {
1218 Res = ParseObjCMessageExpression();
1219 break;
1220 }
1221 // FALL THROUGH.
1222 default:
1223 NotCastExpr = true;
1224 return ExprError();
1225 }
1226
1227 // These can be followed by postfix-expr pieces.
1228 return ParsePostfixExpressionSuffix(Res);
1229 }
1230
1231 /// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
1232 /// is parsed, this method parses any suffixes that apply.
1233 ///
1234 /// postfix-expression: [C99 6.5.2]
1235 /// primary-expression
1236 /// postfix-expression '[' expression ']'
1237 /// postfix-expression '[' braced-init-list ']'
1238 /// postfix-expression '(' argument-expression-list[opt] ')'
1239 /// postfix-expression '.' identifier
1240 /// postfix-expression '->' identifier
1241 /// postfix-expression '++'
1242 /// postfix-expression '--'
1243 /// '(' type-name ')' '{' initializer-list '}'
1244 /// '(' type-name ')' '{' initializer-list ',' '}'
1245 ///
1246 /// argument-expression-list: [C99 6.5.2]
1247 /// argument-expression ...[opt]
1248 /// argument-expression-list ',' assignment-expression ...[opt]
1249 ///
1250 ExprResult
ParsePostfixExpressionSuffix(ExprResult LHS)1251 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1252 // Now that the primary-expression piece of the postfix-expression has been
1253 // parsed, see if there are any postfix-expression pieces here.
1254 SourceLocation Loc;
1255 while (1) {
1256 switch (Tok.getKind()) {
1257 case tok::code_completion:
1258 if (InMessageExpression)
1259 return move(LHS);
1260
1261 Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
1262 cutOffParsing();
1263 return ExprError();
1264
1265 case tok::identifier:
1266 // If we see identifier: after an expression, and we're not already in a
1267 // message send, then this is probably a message send with a missing
1268 // opening bracket '['.
1269 if (getLangOpts().ObjC1 && !InMessageExpression &&
1270 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1271 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1272 ParsedType(), LHS.get());
1273 break;
1274 }
1275
1276 // Fall through; this isn't a message send.
1277
1278 default: // Not a postfix-expression suffix.
1279 return move(LHS);
1280 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
1281 // If we have a array postfix expression that starts on a new line and
1282 // Objective-C is enabled, it is highly likely that the user forgot a
1283 // semicolon after the base expression and that the array postfix-expr is
1284 // actually another message send. In this case, do some look-ahead to see
1285 // if the contents of the square brackets are obviously not a valid
1286 // expression and recover by pretending there is no suffix.
1287 if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
1288 isSimpleObjCMessageExpression())
1289 return move(LHS);
1290
1291 // Reject array indices starting with a lambda-expression. '[[' is
1292 // reserved for attributes.
1293 if (CheckProhibitedCXX11Attribute())
1294 return ExprError();
1295
1296 BalancedDelimiterTracker T(*this, tok::l_square);
1297 T.consumeOpen();
1298 Loc = T.getOpenLocation();
1299 ExprResult Idx;
1300 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
1301 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1302 Idx = ParseBraceInitializer();
1303 } else
1304 Idx = ParseExpression();
1305
1306 SourceLocation RLoc = Tok.getLocation();
1307
1308 if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) {
1309 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.take(), Loc,
1310 Idx.take(), RLoc);
1311 } else
1312 LHS = ExprError();
1313
1314 // Match the ']'.
1315 T.consumeClose();
1316 break;
1317 }
1318
1319 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
1320 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
1321 // '(' argument-expression-list[opt] ')'
1322 tok::TokenKind OpKind = Tok.getKind();
1323 InMessageExpressionRAIIObject InMessage(*this, false);
1324
1325 Expr *ExecConfig = 0;
1326
1327 BalancedDelimiterTracker PT(*this, tok::l_paren);
1328
1329 if (OpKind == tok::lesslessless) {
1330 ExprVector ExecConfigExprs(Actions);
1331 CommaLocsTy ExecConfigCommaLocs;
1332 SourceLocation OpenLoc = ConsumeToken();
1333
1334 if (ParseExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1335 LHS = ExprError();
1336 }
1337
1338 SourceLocation CloseLoc = Tok.getLocation();
1339 if (Tok.is(tok::greatergreatergreater)) {
1340 ConsumeToken();
1341 } else if (LHS.isInvalid()) {
1342 SkipUntil(tok::greatergreatergreater);
1343 } else {
1344 // There was an error closing the brackets
1345 Diag(Tok, diag::err_expected_ggg);
1346 Diag(OpenLoc, diag::note_matching) << "<<<";
1347 SkipUntil(tok::greatergreatergreater);
1348 LHS = ExprError();
1349 }
1350
1351 if (!LHS.isInvalid()) {
1352 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen, ""))
1353 LHS = ExprError();
1354 else
1355 Loc = PrevTokLocation;
1356 }
1357
1358 if (!LHS.isInvalid()) {
1359 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1360 OpenLoc,
1361 move_arg(ExecConfigExprs),
1362 CloseLoc);
1363 if (ECResult.isInvalid())
1364 LHS = ExprError();
1365 else
1366 ExecConfig = ECResult.get();
1367 }
1368 } else {
1369 PT.consumeOpen();
1370 Loc = PT.getOpenLocation();
1371 }
1372
1373 ExprVector ArgExprs(Actions);
1374 CommaLocsTy CommaLocs;
1375
1376 if (Tok.is(tok::code_completion)) {
1377 Actions.CodeCompleteCall(getCurScope(), LHS.get(),
1378 llvm::ArrayRef<Expr *>());
1379 cutOffParsing();
1380 return ExprError();
1381 }
1382
1383 if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1384 if (Tok.isNot(tok::r_paren)) {
1385 if (ParseExpressionList(ArgExprs, CommaLocs, &Sema::CodeCompleteCall,
1386 LHS.get())) {
1387 LHS = ExprError();
1388 }
1389 }
1390 }
1391
1392 // Match the ')'.
1393 if (LHS.isInvalid()) {
1394 SkipUntil(tok::r_paren);
1395 } else if (Tok.isNot(tok::r_paren)) {
1396 PT.consumeClose();
1397 LHS = ExprError();
1398 } else {
1399 assert((ArgExprs.size() == 0 ||
1400 ArgExprs.size()-1 == CommaLocs.size())&&
1401 "Unexpected number of commas!");
1402 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.take(), Loc,
1403 move_arg(ArgExprs), Tok.getLocation(),
1404 ExecConfig);
1405 PT.consumeClose();
1406 }
1407
1408 break;
1409 }
1410 case tok::arrow:
1411 case tok::period: {
1412 // postfix-expression: p-e '->' template[opt] id-expression
1413 // postfix-expression: p-e '.' template[opt] id-expression
1414 tok::TokenKind OpKind = Tok.getKind();
1415 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
1416
1417 CXXScopeSpec SS;
1418 ParsedType ObjectType;
1419 bool MayBePseudoDestructor = false;
1420 if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
1421 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), LHS.take(),
1422 OpLoc, OpKind, ObjectType,
1423 MayBePseudoDestructor);
1424 if (LHS.isInvalid())
1425 break;
1426
1427 ParseOptionalCXXScopeSpecifier(SS, ObjectType,
1428 /*EnteringContext=*/false,
1429 &MayBePseudoDestructor);
1430 if (SS.isNotEmpty())
1431 ObjectType = ParsedType();
1432 }
1433
1434 if (Tok.is(tok::code_completion)) {
1435 // Code completion for a member access expression.
1436 Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(),
1437 OpLoc, OpKind == tok::arrow);
1438
1439 cutOffParsing();
1440 return ExprError();
1441 }
1442
1443 if (MayBePseudoDestructor && !LHS.isInvalid()) {
1444 LHS = ParseCXXPseudoDestructor(LHS.take(), OpLoc, OpKind, SS,
1445 ObjectType);
1446 break;
1447 }
1448
1449 // Either the action has told is that this cannot be a
1450 // pseudo-destructor expression (based on the type of base
1451 // expression), or we didn't see a '~' in the right place. We
1452 // can still parse a destructor name here, but in that case it
1453 // names a real destructor.
1454 // Allow explicit constructor calls in Microsoft mode.
1455 // FIXME: Add support for explicit call of template constructor.
1456 SourceLocation TemplateKWLoc;
1457 UnqualifiedId Name;
1458 if (getLangOpts().ObjC2 && OpKind == tok::period && Tok.is(tok::kw_class)) {
1459 // Objective-C++:
1460 // After a '.' in a member access expression, treat the keyword
1461 // 'class' as if it were an identifier.
1462 //
1463 // This hack allows property access to the 'class' method because it is
1464 // such a common method name. For other C++ keywords that are
1465 // Objective-C method names, one must use the message send syntax.
1466 IdentifierInfo *Id = Tok.getIdentifierInfo();
1467 SourceLocation Loc = ConsumeToken();
1468 Name.setIdentifier(Id, Loc);
1469 } else if (ParseUnqualifiedId(SS,
1470 /*EnteringContext=*/false,
1471 /*AllowDestructorName=*/true,
1472 /*AllowConstructorName=*/
1473 getLangOpts().MicrosoftExt,
1474 ObjectType, TemplateKWLoc, Name))
1475 LHS = ExprError();
1476
1477 if (!LHS.isInvalid())
1478 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.take(), OpLoc,
1479 OpKind, SS, TemplateKWLoc, Name,
1480 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl : 0,
1481 Tok.is(tok::l_paren));
1482 break;
1483 }
1484 case tok::plusplus: // postfix-expression: postfix-expression '++'
1485 case tok::minusminus: // postfix-expression: postfix-expression '--'
1486 if (!LHS.isInvalid()) {
1487 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1488 Tok.getKind(), LHS.take());
1489 }
1490 ConsumeToken();
1491 break;
1492 }
1493 }
1494 }
1495
1496 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1497 /// vec_step and we are at the start of an expression or a parenthesized
1498 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1499 /// expression (isCastExpr == false) or the type (isCastExpr == true).
1500 ///
1501 /// unary-expression: [C99 6.5.3]
1502 /// 'sizeof' unary-expression
1503 /// 'sizeof' '(' type-name ')'
1504 /// [GNU] '__alignof' unary-expression
1505 /// [GNU] '__alignof' '(' type-name ')'
1506 /// [C++0x] 'alignof' '(' type-id ')'
1507 ///
1508 /// [GNU] typeof-specifier:
1509 /// typeof ( expressions )
1510 /// typeof ( type-name )
1511 /// [GNU/C++] typeof unary-expression
1512 ///
1513 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
1514 /// vec_step ( expressions )
1515 /// vec_step ( type-name )
1516 ///
1517 ExprResult
ParseExprAfterUnaryExprOrTypeTrait(const Token & OpTok,bool & isCastExpr,ParsedType & CastTy,SourceRange & CastRange)1518 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1519 bool &isCastExpr,
1520 ParsedType &CastTy,
1521 SourceRange &CastRange) {
1522
1523 assert((OpTok.is(tok::kw_typeof) || OpTok.is(tok::kw_sizeof) ||
1524 OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof) ||
1525 OpTok.is(tok::kw_vec_step)) &&
1526 "Not a typeof/sizeof/alignof/vec_step expression!");
1527
1528 ExprResult Operand;
1529
1530 // If the operand doesn't start with an '(', it must be an expression.
1531 if (Tok.isNot(tok::l_paren)) {
1532 isCastExpr = false;
1533 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
1534 Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierInfo();
1535 return ExprError();
1536 }
1537
1538 Operand = ParseCastExpression(true/*isUnaryExpression*/);
1539 } else {
1540 // If it starts with a '(', we know that it is either a parenthesized
1541 // type-name, or it is a unary-expression that starts with a compound
1542 // literal, or starts with a primary-expression that is a parenthesized
1543 // expression.
1544 ParenParseOption ExprType = CastExpr;
1545 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1546
1547 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1548 false, CastTy, RParenLoc);
1549 CastRange = SourceRange(LParenLoc, RParenLoc);
1550
1551 // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1552 // a type.
1553 if (ExprType == CastExpr) {
1554 isCastExpr = true;
1555 return ExprEmpty();
1556 }
1557
1558 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1559 // GNU typeof in C requires the expression to be parenthesized. Not so for
1560 // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1561 // the start of a unary-expression, but doesn't include any postfix
1562 // pieces. Parse these now if present.
1563 if (!Operand.isInvalid())
1564 Operand = ParsePostfixExpressionSuffix(Operand.get());
1565 }
1566 }
1567
1568 // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
1569 isCastExpr = false;
1570 return move(Operand);
1571 }
1572
1573
1574 /// ParseUnaryExprOrTypeTraitExpression - Parse a sizeof or alignof expression.
1575 /// unary-expression: [C99 6.5.3]
1576 /// 'sizeof' unary-expression
1577 /// 'sizeof' '(' type-name ')'
1578 /// [C++0x] 'sizeof' '...' '(' identifier ')'
1579 /// [GNU] '__alignof' unary-expression
1580 /// [GNU] '__alignof' '(' type-name ')'
1581 /// [C++0x] 'alignof' '(' type-id ')'
ParseUnaryExprOrTypeTraitExpression()1582 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1583 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof)
1584 || Tok.is(tok::kw_alignof) || Tok.is(tok::kw_vec_step)) &&
1585 "Not a sizeof/alignof/vec_step expression!");
1586 Token OpTok = Tok;
1587 ConsumeToken();
1588
1589 // [C++0x] 'sizeof' '...' '(' identifier ')'
1590 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1591 SourceLocation EllipsisLoc = ConsumeToken();
1592 SourceLocation LParenLoc, RParenLoc;
1593 IdentifierInfo *Name = 0;
1594 SourceLocation NameLoc;
1595 if (Tok.is(tok::l_paren)) {
1596 BalancedDelimiterTracker T(*this, tok::l_paren);
1597 T.consumeOpen();
1598 LParenLoc = T.getOpenLocation();
1599 if (Tok.is(tok::identifier)) {
1600 Name = Tok.getIdentifierInfo();
1601 NameLoc = ConsumeToken();
1602 T.consumeClose();
1603 RParenLoc = T.getCloseLocation();
1604 if (RParenLoc.isInvalid())
1605 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1606 } else {
1607 Diag(Tok, diag::err_expected_parameter_pack);
1608 SkipUntil(tok::r_paren);
1609 }
1610 } else if (Tok.is(tok::identifier)) {
1611 Name = Tok.getIdentifierInfo();
1612 NameLoc = ConsumeToken();
1613 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1614 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1615 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1616 << Name
1617 << FixItHint::CreateInsertion(LParenLoc, "(")
1618 << FixItHint::CreateInsertion(RParenLoc, ")");
1619 } else {
1620 Diag(Tok, diag::err_sizeof_parameter_pack);
1621 }
1622
1623 if (!Name)
1624 return ExprError();
1625
1626 return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
1627 OpTok.getLocation(),
1628 *Name, NameLoc,
1629 RParenLoc);
1630 }
1631
1632 if (OpTok.is(tok::kw_alignof))
1633 Diag(OpTok, diag::warn_cxx98_compat_alignof);
1634
1635 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1636
1637 bool isCastExpr;
1638 ParsedType CastTy;
1639 SourceRange CastRange;
1640 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
1641 isCastExpr,
1642 CastTy,
1643 CastRange);
1644
1645 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
1646 if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw___alignof))
1647 ExprKind = UETT_AlignOf;
1648 else if (OpTok.is(tok::kw_vec_step))
1649 ExprKind = UETT_VecStep;
1650
1651 if (isCastExpr)
1652 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1653 ExprKind,
1654 /*isType=*/true,
1655 CastTy.getAsOpaquePtr(),
1656 CastRange);
1657
1658 // If we get here, the operand to the sizeof/alignof was an expresion.
1659 if (!Operand.isInvalid())
1660 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1661 ExprKind,
1662 /*isType=*/false,
1663 Operand.release(),
1664 CastRange);
1665 return move(Operand);
1666 }
1667
1668 /// ParseBuiltinPrimaryExpression
1669 ///
1670 /// primary-expression: [C99 6.5.1]
1671 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1672 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
1673 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
1674 /// assign-expr ')'
1675 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
1676 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
1677 ///
1678 /// [GNU] offsetof-member-designator:
1679 /// [GNU] identifier
1680 /// [GNU] offsetof-member-designator '.' identifier
1681 /// [GNU] offsetof-member-designator '[' expression ']'
1682 ///
ParseBuiltinPrimaryExpression()1683 ExprResult Parser::ParseBuiltinPrimaryExpression() {
1684 ExprResult Res;
1685 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1686
1687 tok::TokenKind T = Tok.getKind();
1688 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
1689
1690 // All of these start with an open paren.
1691 if (Tok.isNot(tok::l_paren))
1692 return ExprError(Diag(Tok, diag::err_expected_lparen_after_id)
1693 << BuiltinII);
1694
1695 BalancedDelimiterTracker PT(*this, tok::l_paren);
1696 PT.consumeOpen();
1697
1698 // TODO: Build AST.
1699
1700 switch (T) {
1701 default: llvm_unreachable("Not a builtin primary expression!");
1702 case tok::kw___builtin_va_arg: {
1703 ExprResult Expr(ParseAssignmentExpression());
1704
1705 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1706 Expr = ExprError();
1707
1708 TypeResult Ty = ParseTypeName();
1709
1710 if (Tok.isNot(tok::r_paren)) {
1711 Diag(Tok, diag::err_expected_rparen);
1712 Expr = ExprError();
1713 }
1714
1715 if (Expr.isInvalid() || Ty.isInvalid())
1716 Res = ExprError();
1717 else
1718 Res = Actions.ActOnVAArg(StartLoc, Expr.take(), Ty.get(), ConsumeParen());
1719 break;
1720 }
1721 case tok::kw___builtin_offsetof: {
1722 SourceLocation TypeLoc = Tok.getLocation();
1723 TypeResult Ty = ParseTypeName();
1724 if (Ty.isInvalid()) {
1725 SkipUntil(tok::r_paren);
1726 return ExprError();
1727 }
1728
1729 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1730 return ExprError();
1731
1732 // We must have at least one identifier here.
1733 if (Tok.isNot(tok::identifier)) {
1734 Diag(Tok, diag::err_expected_ident);
1735 SkipUntil(tok::r_paren);
1736 return ExprError();
1737 }
1738
1739 // Keep track of the various subcomponents we see.
1740 SmallVector<Sema::OffsetOfComponent, 4> Comps;
1741
1742 Comps.push_back(Sema::OffsetOfComponent());
1743 Comps.back().isBrackets = false;
1744 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1745 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
1746
1747 // FIXME: This loop leaks the index expressions on error.
1748 while (1) {
1749 if (Tok.is(tok::period)) {
1750 // offsetof-member-designator: offsetof-member-designator '.' identifier
1751 Comps.push_back(Sema::OffsetOfComponent());
1752 Comps.back().isBrackets = false;
1753 Comps.back().LocStart = ConsumeToken();
1754
1755 if (Tok.isNot(tok::identifier)) {
1756 Diag(Tok, diag::err_expected_ident);
1757 SkipUntil(tok::r_paren);
1758 return ExprError();
1759 }
1760 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1761 Comps.back().LocEnd = ConsumeToken();
1762
1763 } else if (Tok.is(tok::l_square)) {
1764 if (CheckProhibitedCXX11Attribute())
1765 return ExprError();
1766
1767 // offsetof-member-designator: offsetof-member-design '[' expression ']'
1768 Comps.push_back(Sema::OffsetOfComponent());
1769 Comps.back().isBrackets = true;
1770 BalancedDelimiterTracker ST(*this, tok::l_square);
1771 ST.consumeOpen();
1772 Comps.back().LocStart = ST.getOpenLocation();
1773 Res = ParseExpression();
1774 if (Res.isInvalid()) {
1775 SkipUntil(tok::r_paren);
1776 return move(Res);
1777 }
1778 Comps.back().U.E = Res.release();
1779
1780 ST.consumeClose();
1781 Comps.back().LocEnd = ST.getCloseLocation();
1782 } else {
1783 if (Tok.isNot(tok::r_paren)) {
1784 PT.consumeClose();
1785 Res = ExprError();
1786 } else if (Ty.isInvalid()) {
1787 Res = ExprError();
1788 } else {
1789 PT.consumeClose();
1790 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
1791 Ty.get(), &Comps[0], Comps.size(),
1792 PT.getCloseLocation());
1793 }
1794 break;
1795 }
1796 }
1797 break;
1798 }
1799 case tok::kw___builtin_choose_expr: {
1800 ExprResult Cond(ParseAssignmentExpression());
1801 if (Cond.isInvalid()) {
1802 SkipUntil(tok::r_paren);
1803 return move(Cond);
1804 }
1805 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1806 return ExprError();
1807
1808 ExprResult Expr1(ParseAssignmentExpression());
1809 if (Expr1.isInvalid()) {
1810 SkipUntil(tok::r_paren);
1811 return move(Expr1);
1812 }
1813 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1814 return ExprError();
1815
1816 ExprResult Expr2(ParseAssignmentExpression());
1817 if (Expr2.isInvalid()) {
1818 SkipUntil(tok::r_paren);
1819 return move(Expr2);
1820 }
1821 if (Tok.isNot(tok::r_paren)) {
1822 Diag(Tok, diag::err_expected_rparen);
1823 return ExprError();
1824 }
1825 Res = Actions.ActOnChooseExpr(StartLoc, Cond.take(), Expr1.take(),
1826 Expr2.take(), ConsumeParen());
1827 break;
1828 }
1829 case tok::kw___builtin_astype: {
1830 // The first argument is an expression to be converted, followed by a comma.
1831 ExprResult Expr(ParseAssignmentExpression());
1832 if (Expr.isInvalid()) {
1833 SkipUntil(tok::r_paren);
1834 return ExprError();
1835 }
1836
1837 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",
1838 tok::r_paren))
1839 return ExprError();
1840
1841 // Second argument is the type to bitcast to.
1842 TypeResult DestTy = ParseTypeName();
1843 if (DestTy.isInvalid())
1844 return ExprError();
1845
1846 // Attempt to consume the r-paren.
1847 if (Tok.isNot(tok::r_paren)) {
1848 Diag(Tok, diag::err_expected_rparen);
1849 SkipUntil(tok::r_paren);
1850 return ExprError();
1851 }
1852
1853 Res = Actions.ActOnAsTypeExpr(Expr.take(), DestTy.get(), StartLoc,
1854 ConsumeParen());
1855 break;
1856 }
1857 }
1858
1859 if (Res.isInvalid())
1860 return ExprError();
1861
1862 // These can be followed by postfix-expr pieces because they are
1863 // primary-expressions.
1864 return ParsePostfixExpressionSuffix(Res.take());
1865 }
1866
1867 /// ParseParenExpression - This parses the unit that starts with a '(' token,
1868 /// based on what is allowed by ExprType. The actual thing parsed is returned
1869 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
1870 /// not the parsed cast-expression.
1871 ///
1872 /// primary-expression: [C99 6.5.1]
1873 /// '(' expression ')'
1874 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
1875 /// postfix-expression: [C99 6.5.2]
1876 /// '(' type-name ')' '{' initializer-list '}'
1877 /// '(' type-name ')' '{' initializer-list ',' '}'
1878 /// cast-expression: [C99 6.5.4]
1879 /// '(' type-name ')' cast-expression
1880 /// [ARC] bridged-cast-expression
1881 ///
1882 /// [ARC] bridged-cast-expression:
1883 /// (__bridge type-name) cast-expression
1884 /// (__bridge_transfer type-name) cast-expression
1885 /// (__bridge_retained type-name) cast-expression
1886 ExprResult
ParseParenExpression(ParenParseOption & ExprType,bool stopIfCastExpr,bool isTypeCast,ParsedType & CastTy,SourceLocation & RParenLoc)1887 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
1888 bool isTypeCast, ParsedType &CastTy,
1889 SourceLocation &RParenLoc) {
1890 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
1891 GreaterThanIsOperatorScope G(GreaterThanIsOperator, true);
1892 BalancedDelimiterTracker T(*this, tok::l_paren);
1893 if (T.consumeOpen())
1894 return ExprError();
1895 SourceLocation OpenLoc = T.getOpenLocation();
1896
1897 ExprResult Result(true);
1898 bool isAmbiguousTypeId;
1899 CastTy = ParsedType();
1900
1901 if (Tok.is(tok::code_completion)) {
1902 Actions.CodeCompleteOrdinaryName(getCurScope(),
1903 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
1904 : Sema::PCC_Expression);
1905 cutOffParsing();
1906 return ExprError();
1907 }
1908
1909 // Diagnose use of bridge casts in non-arc mode.
1910 bool BridgeCast = (getLangOpts().ObjC2 &&
1911 (Tok.is(tok::kw___bridge) ||
1912 Tok.is(tok::kw___bridge_transfer) ||
1913 Tok.is(tok::kw___bridge_retained) ||
1914 Tok.is(tok::kw___bridge_retain)));
1915 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
1916 StringRef BridgeCastName = Tok.getName();
1917 SourceLocation BridgeKeywordLoc = ConsumeToken();
1918 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
1919 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
1920 << BridgeCastName
1921 << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
1922 BridgeCast = false;
1923 }
1924
1925 // None of these cases should fall through with an invalid Result
1926 // unless they've already reported an error.
1927 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
1928 Diag(Tok, diag::ext_gnu_statement_expr);
1929 Actions.ActOnStartStmtExpr();
1930
1931 StmtResult Stmt(ParseCompoundStatement(true));
1932 ExprType = CompoundStmt;
1933
1934 // If the substmt parsed correctly, build the AST node.
1935 if (!Stmt.isInvalid()) {
1936 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.take(), Tok.getLocation());
1937 } else {
1938 Actions.ActOnStmtExprError();
1939 }
1940 } else if (ExprType >= CompoundLiteral && BridgeCast) {
1941 tok::TokenKind tokenKind = Tok.getKind();
1942 SourceLocation BridgeKeywordLoc = ConsumeToken();
1943
1944 // Parse an Objective-C ARC ownership cast expression.
1945 ObjCBridgeCastKind Kind;
1946 if (tokenKind == tok::kw___bridge)
1947 Kind = OBC_Bridge;
1948 else if (tokenKind == tok::kw___bridge_transfer)
1949 Kind = OBC_BridgeTransfer;
1950 else if (tokenKind == tok::kw___bridge_retained)
1951 Kind = OBC_BridgeRetained;
1952 else {
1953 // As a hopefully temporary workaround, allow __bridge_retain as
1954 // a synonym for __bridge_retained, but only in system headers.
1955 assert(tokenKind == tok::kw___bridge_retain);
1956 Kind = OBC_BridgeRetained;
1957 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
1958 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
1959 << FixItHint::CreateReplacement(BridgeKeywordLoc,
1960 "__bridge_retained");
1961 }
1962
1963 TypeResult Ty = ParseTypeName();
1964 T.consumeClose();
1965 RParenLoc = T.getCloseLocation();
1966 ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
1967
1968 if (Ty.isInvalid() || SubExpr.isInvalid())
1969 return ExprError();
1970
1971 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
1972 BridgeKeywordLoc, Ty.get(),
1973 RParenLoc, SubExpr.get());
1974 } else if (ExprType >= CompoundLiteral &&
1975 isTypeIdInParens(isAmbiguousTypeId)) {
1976
1977 // Otherwise, this is a compound literal expression or cast expression.
1978
1979 // In C++, if the type-id is ambiguous we disambiguate based on context.
1980 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
1981 // in which case we should treat it as type-id.
1982 // if stopIfCastExpr is false, we need to determine the context past the
1983 // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
1984 if (isAmbiguousTypeId && !stopIfCastExpr) {
1985 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T);
1986 RParenLoc = T.getCloseLocation();
1987 return res;
1988 }
1989
1990 // Parse the type declarator.
1991 DeclSpec DS(AttrFactory);
1992 ParseSpecifierQualifierList(DS);
1993 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1994 ParseDeclarator(DeclaratorInfo);
1995
1996 // If our type is followed by an identifier and either ':' or ']', then
1997 // this is probably an Objective-C message send where the leading '[' is
1998 // missing. Recover as if that were the case.
1999 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2000 !InMessageExpression && getLangOpts().ObjC1 &&
2001 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2002 TypeResult Ty;
2003 {
2004 InMessageExpressionRAIIObject InMessage(*this, false);
2005 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2006 }
2007 Result = ParseObjCMessageExpressionBody(SourceLocation(),
2008 SourceLocation(),
2009 Ty.get(), 0);
2010 } else {
2011 // Match the ')'.
2012 T.consumeClose();
2013 RParenLoc = T.getCloseLocation();
2014 if (Tok.is(tok::l_brace)) {
2015 ExprType = CompoundLiteral;
2016 TypeResult Ty;
2017 {
2018 InMessageExpressionRAIIObject InMessage(*this, false);
2019 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2020 }
2021 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2022 }
2023
2024 if (ExprType == CastExpr) {
2025 // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2026
2027 if (DeclaratorInfo.isInvalidType())
2028 return ExprError();
2029
2030 // Note that this doesn't parse the subsequent cast-expression, it just
2031 // returns the parsed type to the callee.
2032 if (stopIfCastExpr) {
2033 TypeResult Ty;
2034 {
2035 InMessageExpressionRAIIObject InMessage(*this, false);
2036 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2037 }
2038 CastTy = Ty.get();
2039 return ExprResult();
2040 }
2041
2042 // Reject the cast of super idiom in ObjC.
2043 if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
2044 Tok.getIdentifierInfo() == Ident_super &&
2045 getCurScope()->isInObjcMethodScope() &&
2046 GetLookAheadToken(1).isNot(tok::period)) {
2047 Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2048 << SourceRange(OpenLoc, RParenLoc);
2049 return ExprError();
2050 }
2051
2052 // Parse the cast-expression that follows it next.
2053 // TODO: For cast expression with CastTy.
2054 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2055 /*isAddressOfOperand=*/false,
2056 /*isTypeCast=*/IsTypeCast);
2057 if (!Result.isInvalid()) {
2058 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2059 DeclaratorInfo, CastTy,
2060 RParenLoc, Result.take());
2061 }
2062 return move(Result);
2063 }
2064
2065 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2066 return ExprError();
2067 }
2068 } else if (isTypeCast) {
2069 // Parse the expression-list.
2070 InMessageExpressionRAIIObject InMessage(*this, false);
2071
2072 ExprVector ArgExprs(Actions);
2073 CommaLocsTy CommaLocs;
2074
2075 if (!ParseExpressionList(ArgExprs, CommaLocs)) {
2076 ExprType = SimpleExpr;
2077 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2078 move_arg(ArgExprs));
2079 }
2080 } else {
2081 InMessageExpressionRAIIObject InMessage(*this, false);
2082
2083 Result = ParseExpression(MaybeTypeCast);
2084 ExprType = SimpleExpr;
2085
2086 // Don't build a paren expression unless we actually match a ')'.
2087 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2088 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.take());
2089 }
2090
2091 // Match the ')'.
2092 if (Result.isInvalid()) {
2093 SkipUntil(tok::r_paren);
2094 return ExprError();
2095 }
2096
2097 T.consumeClose();
2098 RParenLoc = T.getCloseLocation();
2099 return move(Result);
2100 }
2101
2102 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2103 /// and we are at the left brace.
2104 ///
2105 /// postfix-expression: [C99 6.5.2]
2106 /// '(' type-name ')' '{' initializer-list '}'
2107 /// '(' type-name ')' '{' initializer-list ',' '}'
2108 ///
2109 ExprResult
ParseCompoundLiteralExpression(ParsedType Ty,SourceLocation LParenLoc,SourceLocation RParenLoc)2110 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2111 SourceLocation LParenLoc,
2112 SourceLocation RParenLoc) {
2113 assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2114 if (!getLangOpts().C99) // Compound literals don't exist in C90.
2115 Diag(LParenLoc, diag::ext_c99_compound_literal);
2116 ExprResult Result = ParseInitializer();
2117 if (!Result.isInvalid() && Ty)
2118 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.take());
2119 return move(Result);
2120 }
2121
2122 /// ParseStringLiteralExpression - This handles the various token types that
2123 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
2124 /// translation phase #6].
2125 ///
2126 /// primary-expression: [C99 6.5.1]
2127 /// string-literal
ParseStringLiteralExpression(bool AllowUserDefinedLiteral)2128 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2129 assert(isTokenStringLiteral() && "Not a string literal!");
2130
2131 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
2132 // considered to be strings for concatenation purposes.
2133 SmallVector<Token, 4> StringToks;
2134
2135 do {
2136 StringToks.push_back(Tok);
2137 ConsumeStringToken();
2138 } while (isTokenStringLiteral());
2139
2140 // Pass the set of string tokens, ready for concatenation, to the actions.
2141 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size(),
2142 AllowUserDefinedLiteral ? getCurScope() : 0);
2143 }
2144
2145 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
2146 /// [C11 6.5.1.1].
2147 ///
2148 /// generic-selection:
2149 /// _Generic ( assignment-expression , generic-assoc-list )
2150 /// generic-assoc-list:
2151 /// generic-association
2152 /// generic-assoc-list , generic-association
2153 /// generic-association:
2154 /// type-name : assignment-expression
2155 /// default : assignment-expression
ParseGenericSelectionExpression()2156 ExprResult Parser::ParseGenericSelectionExpression() {
2157 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2158 SourceLocation KeyLoc = ConsumeToken();
2159
2160 if (!getLangOpts().C11)
2161 Diag(KeyLoc, diag::ext_c11_generic_selection);
2162
2163 BalancedDelimiterTracker T(*this, tok::l_paren);
2164 if (T.expectAndConsume(diag::err_expected_lparen))
2165 return ExprError();
2166
2167 ExprResult ControllingExpr;
2168 {
2169 // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2170 // not evaluated."
2171 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
2172 ControllingExpr = ParseAssignmentExpression();
2173 if (ControllingExpr.isInvalid()) {
2174 SkipUntil(tok::r_paren);
2175 return ExprError();
2176 }
2177 }
2178
2179 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "")) {
2180 SkipUntil(tok::r_paren);
2181 return ExprError();
2182 }
2183
2184 SourceLocation DefaultLoc;
2185 TypeVector Types(Actions);
2186 ExprVector Exprs(Actions);
2187 while (1) {
2188 ParsedType Ty;
2189 if (Tok.is(tok::kw_default)) {
2190 // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2191 // generic association."
2192 if (!DefaultLoc.isInvalid()) {
2193 Diag(Tok, diag::err_duplicate_default_assoc);
2194 Diag(DefaultLoc, diag::note_previous_default_assoc);
2195 SkipUntil(tok::r_paren);
2196 return ExprError();
2197 }
2198 DefaultLoc = ConsumeToken();
2199 Ty = ParsedType();
2200 } else {
2201 ColonProtectionRAIIObject X(*this);
2202 TypeResult TR = ParseTypeName();
2203 if (TR.isInvalid()) {
2204 SkipUntil(tok::r_paren);
2205 return ExprError();
2206 }
2207 Ty = TR.release();
2208 }
2209 Types.push_back(Ty);
2210
2211 if (ExpectAndConsume(tok::colon, diag::err_expected_colon, "")) {
2212 SkipUntil(tok::r_paren);
2213 return ExprError();
2214 }
2215
2216 // FIXME: These expressions should be parsed in a potentially potentially
2217 // evaluated context.
2218 ExprResult ER(ParseAssignmentExpression());
2219 if (ER.isInvalid()) {
2220 SkipUntil(tok::r_paren);
2221 return ExprError();
2222 }
2223 Exprs.push_back(ER.release());
2224
2225 if (Tok.isNot(tok::comma))
2226 break;
2227 ConsumeToken();
2228 }
2229
2230 T.consumeClose();
2231 if (T.getCloseLocation().isInvalid())
2232 return ExprError();
2233
2234 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
2235 T.getCloseLocation(),
2236 ControllingExpr.release(),
2237 move_arg(Types), move_arg(Exprs));
2238 }
2239
2240 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
2241 ///
2242 /// argument-expression-list:
2243 /// assignment-expression
2244 /// argument-expression-list , assignment-expression
2245 ///
2246 /// [C++] expression-list:
2247 /// [C++] assignment-expression
2248 /// [C++] expression-list , assignment-expression
2249 ///
2250 /// [C++0x] expression-list:
2251 /// [C++0x] initializer-list
2252 ///
2253 /// [C++0x] initializer-list
2254 /// [C++0x] initializer-clause ...[opt]
2255 /// [C++0x] initializer-list , initializer-clause ...[opt]
2256 ///
2257 /// [C++0x] initializer-clause:
2258 /// [C++0x] assignment-expression
2259 /// [C++0x] braced-init-list
2260 ///
ParseExpressionList(SmallVectorImpl<Expr * > & Exprs,SmallVectorImpl<SourceLocation> & CommaLocs,void (Sema::* Completer)(Scope * S,Expr * Data,llvm::ArrayRef<Expr * > Args),Expr * Data)2261 bool Parser::ParseExpressionList(SmallVectorImpl<Expr*> &Exprs,
2262 SmallVectorImpl<SourceLocation> &CommaLocs,
2263 void (Sema::*Completer)(Scope *S,
2264 Expr *Data,
2265 llvm::ArrayRef<Expr *> Args),
2266 Expr *Data) {
2267 while (1) {
2268 if (Tok.is(tok::code_completion)) {
2269 if (Completer)
2270 (Actions.*Completer)(getCurScope(), Data, Exprs);
2271 else
2272 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
2273 cutOffParsing();
2274 return true;
2275 }
2276
2277 ExprResult Expr;
2278 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
2279 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2280 Expr = ParseBraceInitializer();
2281 } else
2282 Expr = ParseAssignmentExpression();
2283
2284 if (Tok.is(tok::ellipsis))
2285 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
2286 if (Expr.isInvalid())
2287 return true;
2288
2289 Exprs.push_back(Expr.release());
2290
2291 if (Tok.isNot(tok::comma))
2292 return false;
2293 // Move to the next argument, remember where the comma was.
2294 CommaLocs.push_back(ConsumeToken());
2295 }
2296 }
2297
2298 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
2299 ///
2300 /// [clang] block-id:
2301 /// [clang] specifier-qualifier-list block-declarator
2302 ///
ParseBlockId()2303 void Parser::ParseBlockId() {
2304 if (Tok.is(tok::code_completion)) {
2305 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
2306 return cutOffParsing();
2307 }
2308
2309 // Parse the specifier-qualifier-list piece.
2310 DeclSpec DS(AttrFactory);
2311 ParseSpecifierQualifierList(DS);
2312
2313 // Parse the block-declarator.
2314 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
2315 ParseDeclarator(DeclaratorInfo);
2316
2317 // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes.
2318 DeclaratorInfo.takeAttributes(DS.getAttributes(), SourceLocation());
2319
2320 MaybeParseGNUAttributes(DeclaratorInfo);
2321
2322 // Inform sema that we are starting a block.
2323 Actions.ActOnBlockArguments(DeclaratorInfo, getCurScope());
2324 }
2325
2326 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
2327 /// like ^(int x){ return x+1; }
2328 ///
2329 /// block-literal:
2330 /// [clang] '^' block-args[opt] compound-statement
2331 /// [clang] '^' block-id compound-statement
2332 /// [clang] block-args:
2333 /// [clang] '(' parameter-list ')'
2334 ///
ParseBlockLiteralExpression()2335 ExprResult Parser::ParseBlockLiteralExpression() {
2336 assert(Tok.is(tok::caret) && "block literal starts with ^");
2337 SourceLocation CaretLoc = ConsumeToken();
2338
2339 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2340 "block literal parsing");
2341
2342 // Enter a scope to hold everything within the block. This includes the
2343 // argument decls, decls within the compound expression, etc. This also
2344 // allows determining whether a variable reference inside the block is
2345 // within or outside of the block.
2346 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2347 Scope::DeclScope);
2348
2349 // Inform sema that we are starting a block.
2350 Actions.ActOnBlockStart(CaretLoc, getCurScope());
2351
2352 // Parse the return type if present.
2353 DeclSpec DS(AttrFactory);
2354 Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
2355 // FIXME: Since the return type isn't actually parsed, it can't be used to
2356 // fill ParamInfo with an initial valid range, so do it manually.
2357 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2358
2359 // If this block has arguments, parse them. There is no ambiguity here with
2360 // the expression case, because the expression case requires a parameter list.
2361 if (Tok.is(tok::l_paren)) {
2362 ParseParenDeclarator(ParamInfo);
2363 // Parse the pieces after the identifier as if we had "int(...)".
2364 // SetIdentifier sets the source range end, but in this case we're past
2365 // that location.
2366 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2367 ParamInfo.SetIdentifier(0, CaretLoc);
2368 ParamInfo.SetRangeEnd(Tmp);
2369 if (ParamInfo.isInvalidType()) {
2370 // If there was an error parsing the arguments, they may have
2371 // tried to use ^(x+y) which requires an argument list. Just
2372 // skip the whole block literal.
2373 Actions.ActOnBlockError(CaretLoc, getCurScope());
2374 return ExprError();
2375 }
2376
2377 MaybeParseGNUAttributes(ParamInfo);
2378
2379 // Inform sema that we are starting a block.
2380 Actions.ActOnBlockArguments(ParamInfo, getCurScope());
2381 } else if (!Tok.is(tok::l_brace)) {
2382 ParseBlockId();
2383 } else {
2384 // Otherwise, pretend we saw (void).
2385 ParsedAttributes attrs(AttrFactory);
2386 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false,
2387 SourceLocation(),
2388 0, 0, 0,
2389 true, SourceLocation(),
2390 SourceLocation(),
2391 SourceLocation(),
2392 SourceLocation(),
2393 EST_None,
2394 SourceLocation(),
2395 0, 0, 0, 0, 0,
2396 CaretLoc, CaretLoc,
2397 ParamInfo),
2398 attrs, CaretLoc);
2399
2400 MaybeParseGNUAttributes(ParamInfo);
2401
2402 // Inform sema that we are starting a block.
2403 Actions.ActOnBlockArguments(ParamInfo, getCurScope());
2404 }
2405
2406
2407 ExprResult Result(true);
2408 if (!Tok.is(tok::l_brace)) {
2409 // Saw something like: ^expr
2410 Diag(Tok, diag::err_expected_expression);
2411 Actions.ActOnBlockError(CaretLoc, getCurScope());
2412 return ExprError();
2413 }
2414
2415 StmtResult Stmt(ParseCompoundStatementBody());
2416 BlockScope.Exit();
2417 if (!Stmt.isInvalid())
2418 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.take(), getCurScope());
2419 else
2420 Actions.ActOnBlockError(CaretLoc, getCurScope());
2421 return move(Result);
2422 }
2423
2424 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
2425 ///
2426 /// '__objc_yes'
2427 /// '__objc_no'
ParseObjCBoolLiteral()2428 ExprResult Parser::ParseObjCBoolLiteral() {
2429 tok::TokenKind Kind = Tok.getKind();
2430 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
2431 }
2432