1 //===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
20 //===----------------------------------------------------------------------===//
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/Basic/PrettyStackTrace.h"
27 #include "RAIIObjectsForParser.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/SmallString.h"
30 using namespace clang
;
32 /// getBinOpPrecedence - Return the precedence of the specified binary operator
34 static prec::Level
getBinOpPrecedence(tok::TokenKind Kind
,
35 bool GreaterThanIsOperator
,
39 // C++ [temp.names]p3:
40 // [...] When parsing a template-argument-list, the first
41 // non-nested > is taken as the ending delimiter rather than a
42 // greater-than operator. [...]
43 if (GreaterThanIsOperator
)
44 return prec::Relational
;
47 case tok::greatergreater
:
48 // C++0x [temp.names]p3:
50 // [...] Similarly, the first non-nested >> is treated as two
51 // consecutive but distinct > tokens, the first of which is
52 // taken as the end of the template-argument-list and completes
53 // the template-id. [...]
54 if (GreaterThanIsOperator
|| !CPlusPlus0x
)
58 default: return prec::Unknown
;
59 case tok::comma
: return prec::Comma
;
63 case tok::percentequal
:
66 case tok::lesslessequal
:
67 case tok::greatergreaterequal
:
70 case tok::pipeequal
: return prec::Assignment
;
71 case tok::question
: return prec::Conditional
;
72 case tok::pipepipe
: return prec::LogicalOr
;
73 case tok::ampamp
: return prec::LogicalAnd
;
74 case tok::pipe
: return prec::InclusiveOr
;
75 case tok::caret
: return prec::ExclusiveOr
;
76 case tok::amp
: return prec::And
;
77 case tok::exclaimequal
:
78 case tok::equalequal
: return prec::Equality
;
81 case tok::greaterequal
: return prec::Relational
;
82 case tok::lessless
: return prec::Shift
;
84 case tok::minus
: return prec::Additive
;
87 case tok::star
: return prec::Multiplicative
;
89 case tok::arrowstar
: return prec::PointerToMember
;
94 /// ParseExpression - Simple precedence-based parser for binary/ternary
97 /// Note: we diverge from the C99 grammar when parsing the assignment-expression
98 /// production. C99 specifies that the LHS of an assignment operator should be
99 /// parsed as a unary-expression, but consistency dictates that it be a
100 /// conditional-expession. In practice, the important thing here is that the
101 /// LHS of an assignment has to be an l-value, which productions between
102 /// unary-expression and conditional-expression don't produce. Because we want
103 /// consistency, we parse the LHS as a conditional-expression, then check for
104 /// l-value-ness in semantic analysis stages.
106 /// pm-expression: [C++ 5.5]
108 /// pm-expression '.*' cast-expression
109 /// pm-expression '->*' cast-expression
111 /// multiplicative-expression: [C99 6.5.5]
112 /// Note: in C++, apply pm-expression instead of cast-expression
114 /// multiplicative-expression '*' cast-expression
115 /// multiplicative-expression '/' cast-expression
116 /// multiplicative-expression '%' cast-expression
118 /// additive-expression: [C99 6.5.6]
119 /// multiplicative-expression
120 /// additive-expression '+' multiplicative-expression
121 /// additive-expression '-' multiplicative-expression
123 /// shift-expression: [C99 6.5.7]
124 /// additive-expression
125 /// shift-expression '<<' additive-expression
126 /// shift-expression '>>' additive-expression
128 /// relational-expression: [C99 6.5.8]
130 /// relational-expression '<' shift-expression
131 /// relational-expression '>' shift-expression
132 /// relational-expression '<=' shift-expression
133 /// relational-expression '>=' shift-expression
135 /// equality-expression: [C99 6.5.9]
136 /// relational-expression
137 /// equality-expression '==' relational-expression
138 /// equality-expression '!=' relational-expression
140 /// AND-expression: [C99 6.5.10]
141 /// equality-expression
142 /// AND-expression '&' equality-expression
144 /// exclusive-OR-expression: [C99 6.5.11]
146 /// exclusive-OR-expression '^' AND-expression
148 /// inclusive-OR-expression: [C99 6.5.12]
149 /// exclusive-OR-expression
150 /// inclusive-OR-expression '|' exclusive-OR-expression
152 /// logical-AND-expression: [C99 6.5.13]
153 /// inclusive-OR-expression
154 /// logical-AND-expression '&&' inclusive-OR-expression
156 /// logical-OR-expression: [C99 6.5.14]
157 /// logical-AND-expression
158 /// logical-OR-expression '||' logical-AND-expression
160 /// conditional-expression: [C99 6.5.15]
161 /// logical-OR-expression
162 /// logical-OR-expression '?' expression ':' conditional-expression
163 /// [GNU] logical-OR-expression '?' ':' conditional-expression
164 /// [C++] the third operand is an assignment-expression
166 /// assignment-expression: [C99 6.5.16]
167 /// conditional-expression
168 /// unary-expression assignment-operator assignment-expression
169 /// [C++] throw-expression [C++ 15]
171 /// assignment-operator: one of
172 /// = *= /= %= += -= <<= >>= &= ^= |=
174 /// expression: [C99 6.5.17]
175 /// assignment-expression ...[opt]
176 /// expression ',' assignment-expression ...[opt]
178 ExprResult
Parser::ParseExpression() {
179 ExprResult
LHS(ParseAssignmentExpression());
180 return ParseRHSOfBinaryExpression(move(LHS
), prec::Comma
);
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.
189 Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc
) {
190 ExprResult
LHS(ParseObjCAtExpression(AtLoc
));
191 return ParseRHSOfBinaryExpression(move(LHS
), prec::Comma
);
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.
198 Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc
) {
199 ExprResult
LHS(true);
201 // Silence extension warnings in the sub-expression
202 ExtensionRAIIObject
O(Diags
);
204 LHS
= ParseCastExpression(false);
207 if (!LHS
.isInvalid())
208 LHS
= Actions
.ActOnUnaryOp(getCurScope(), ExtLoc
, tok::kw___extension__
,
211 return ParseRHSOfBinaryExpression(move(LHS
), prec::Comma
);
214 /// ParseAssignmentExpression - Parse an expr that doesn't include commas.
216 ExprResult
Parser::ParseAssignmentExpression() {
217 if (Tok
.is(tok::code_completion
)) {
218 Actions
.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression
);
219 ConsumeCodeCompletionToken();
222 if (Tok
.is(tok::kw_throw
))
223 return ParseThrowExpression();
225 ExprResult
LHS(ParseCastExpression(false));
226 return ParseRHSOfBinaryExpression(move(LHS
), prec::Assignment
);
229 /// ParseAssignmentExprWithObjCMessageExprStart - Parse an assignment expression
230 /// where part of an objc message send has already been parsed. In this case
231 /// LBracLoc indicates the location of the '[' of the message send, and either
232 /// ReceiverName or ReceiverExpr is non-null indicating the receiver of the
235 /// Since this handles full assignment-expression's, it handles postfix
236 /// expressions and other binary operators for these expressions as well.
238 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc
,
239 SourceLocation SuperLoc
,
240 ParsedType ReceiverType
,
241 Expr
*ReceiverExpr
) {
243 = ParseObjCMessageExpressionBody(LBracLoc
, SuperLoc
,
244 ReceiverType
, ReceiverExpr
);
245 R
= ParsePostfixExpressionSuffix(R
);
246 return ParseRHSOfBinaryExpression(R
, prec::Assignment
);
250 ExprResult
Parser::ParseConstantExpression() {
251 // C++ [basic.def.odr]p2:
252 // An expression is potentially evaluated unless it appears where an
253 // integral constant expression is required (see 5.19) [...].
254 EnterExpressionEvaluationContext
Unevaluated(Actions
,
257 ExprResult
LHS(ParseCastExpression(false));
258 return ParseRHSOfBinaryExpression(LHS
, prec::Conditional
);
261 /// ParseRHSOfBinaryExpression - Parse a binary expression that starts with
262 /// LHS and has a precedence of at least MinPrec.
264 Parser::ParseRHSOfBinaryExpression(ExprResult LHS
, prec::Level MinPrec
) {
265 prec::Level NextTokPrec
= getBinOpPrecedence(Tok
.getKind(),
266 GreaterThanIsOperator
,
267 getLang().CPlusPlus0x
);
268 SourceLocation ColonLoc
;
271 // If this token has a lower precedence than we are allowed to parse (e.g.
272 // because we are called recursively, or because the token is not a binop),
274 if (NextTokPrec
< MinPrec
)
277 // Consume the operator, saving the operator token for error reporting.
281 // Special case handling for the ternary operator.
282 ExprResult
TernaryMiddle(true);
283 if (NextTokPrec
== prec::Conditional
) {
284 if (Tok
.isNot(tok::colon
)) {
285 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
286 ColonProtectionRAIIObject
X(*this);
288 // Handle this production specially:
289 // logical-OR-expression '?' expression ':' conditional-expression
290 // In particular, the RHS of the '?' is 'expression', not
291 // 'logical-OR-expression' as we might expect.
292 TernaryMiddle
= ParseExpression();
293 if (TernaryMiddle
.isInvalid()) {
298 // Special case handling of "X ? Y : Z" where Y is empty:
299 // logical-OR-expression '?' ':' conditional-expression [GNU]
301 Diag(Tok
, diag::ext_gnu_conditional_expr
);
304 if (Tok
.is(tok::colon
)) {
306 ColonLoc
= ConsumeToken();
308 // Otherwise, we're missing a ':'. Assume that this was a typo that the
309 // user forgot. If we're not in a macro instantion, we can suggest a
310 // fixit hint. If there were two spaces before the current token,
311 // suggest inserting the colon in between them, otherwise insert ": ".
312 SourceLocation FILoc
= Tok
.getLocation();
313 const char *FIText
= ": ";
314 if (FILoc
.isFileID()) {
315 const SourceManager
&SM
= PP
.getSourceManager();
316 bool IsInvalid
= false;
317 const char *SourcePtr
=
318 SM
.getCharacterData(FILoc
.getFileLocWithOffset(-1), &IsInvalid
);
319 if (!IsInvalid
&& *SourcePtr
== ' ') {
321 SM
.getCharacterData(FILoc
.getFileLocWithOffset(-2), &IsInvalid
);
322 if (!IsInvalid
&& *SourcePtr
== ' ') {
323 FILoc
= FILoc
.getFileLocWithOffset(-1);
329 Diag(Tok
, diag::err_expected_colon
)
330 << FixItHint::CreateInsertion(FILoc
, FIText
);
331 Diag(OpToken
, diag::note_matching
) << "?";
332 ColonLoc
= Tok
.getLocation();
336 // Code completion for the right-hand side of an assignment expression
337 // goes through a special hook that takes the left-hand side into account.
338 if (Tok
.is(tok::code_completion
) && NextTokPrec
== prec::Assignment
) {
339 Actions
.CodeCompleteAssignmentRHS(getCurScope(), LHS
.get());
340 ConsumeCodeCompletionToken();
344 // Parse another leaf here for the RHS of the operator.
345 // ParseCastExpression works here because all RHS expressions in C have it
346 // as a prefix, at least. However, in C++, an assignment-expression could
347 // be a throw-expression, which is not a valid cast-expression.
348 // Therefore we need some special-casing here.
349 // Also note that the third operand of the conditional operator is
350 // an assignment-expression in C++.
352 if (getLang().CPlusPlus
&& NextTokPrec
<= prec::Conditional
)
353 RHS
= ParseAssignmentExpression();
355 RHS
= ParseCastExpression(false);
360 // Remember the precedence of this operator and get the precedence of the
361 // operator immediately to the right of the RHS.
362 prec::Level ThisPrec
= NextTokPrec
;
363 NextTokPrec
= getBinOpPrecedence(Tok
.getKind(), GreaterThanIsOperator
,
364 getLang().CPlusPlus0x
);
366 // Assignment and conditional expressions are right-associative.
367 bool isRightAssoc
= ThisPrec
== prec::Conditional
||
368 ThisPrec
== prec::Assignment
;
370 // Get the precedence of the operator to the right of the RHS. If it binds
371 // more tightly with RHS than we do, evaluate it completely first.
372 if (ThisPrec
< NextTokPrec
||
373 (ThisPrec
== NextTokPrec
&& isRightAssoc
)) {
374 // If this is left-associative, only parse things on the RHS that bind
375 // more tightly than the current operator. If it is left-associative, it
376 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
377 // A=(B=(C=D)), where each paren is a level of recursion here.
378 // The function takes ownership of the RHS.
379 RHS
= ParseRHSOfBinaryExpression(RHS
,
380 static_cast<prec::Level
>(ThisPrec
+ !isRightAssoc
));
385 NextTokPrec
= getBinOpPrecedence(Tok
.getKind(), GreaterThanIsOperator
,
386 getLang().CPlusPlus0x
);
388 assert(NextTokPrec
<= ThisPrec
&& "Recursion didn't work!");
390 if (!LHS
.isInvalid()) {
391 // Combine the LHS and RHS into the LHS (e.g. build AST).
392 if (TernaryMiddle
.isInvalid()) {
393 // If we're using '>>' as an operator within a template
394 // argument list (in C++98), suggest the addition of
395 // parentheses so that the code remains well-formed in C++0x.
396 if (!GreaterThanIsOperator
&& OpToken
.is(tok::greatergreater
))
397 SuggestParentheses(OpToken
.getLocation(),
398 diag::warn_cxx0x_right_shift_in_template_arg
,
399 SourceRange(Actions
.getExprRange(LHS
.get()).getBegin(),
400 Actions
.getExprRange(RHS
.get()).getEnd()));
402 LHS
= Actions
.ActOnBinOp(getCurScope(), OpToken
.getLocation(),
403 OpToken
.getKind(), LHS
.take(), RHS
.take());
405 LHS
= Actions
.ActOnConditionalOp(OpToken
.getLocation(), ColonLoc
,
406 LHS
.take(), TernaryMiddle
.take(),
412 /// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
413 /// true, parse a unary-expression. isAddressOfOperand exists because an
414 /// id-expression that is the operand of address-of gets special treatment
415 /// due to member pointers.
417 ExprResult
Parser::ParseCastExpression(bool isUnaryExpression
,
418 bool isAddressOfOperand
,
419 ParsedType TypeOfCast
) {
421 ExprResult Res
= ParseCastExpression(isUnaryExpression
,
426 Diag(Tok
, diag::err_expected_expression
);
430 /// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
431 /// true, parse a unary-expression. isAddressOfOperand exists because an
432 /// id-expression that is the operand of address-of gets special treatment
433 /// due to member pointers. NotCastExpr is set to true if the token is not the
434 /// start of a cast-expression, and no diagnostic is emitted in this case.
436 /// cast-expression: [C99 6.5.4]
438 /// '(' type-name ')' cast-expression
440 /// unary-expression: [C99 6.5.3]
441 /// postfix-expression
442 /// '++' unary-expression
443 /// '--' unary-expression
444 /// unary-operator cast-expression
445 /// 'sizeof' unary-expression
446 /// 'sizeof' '(' type-name ')'
447 /// [GNU] '__alignof' unary-expression
448 /// [GNU] '__alignof' '(' type-name ')'
449 /// [C++0x] 'alignof' '(' type-id ')'
450 /// [GNU] '&&' identifier
451 /// [C++] new-expression
452 /// [C++] delete-expression
453 /// [C++0x] 'noexcept' '(' expression ')'
455 /// unary-operator: one of
456 /// '&' '*' '+' '-' '~' '!'
457 /// [GNU] '__extension__' '__real' '__imag'
459 /// primary-expression: [C99 6.5.1]
461 /// [C++] id-expression
464 /// [C++] boolean-literal [C++ 2.13.5]
465 /// [C++0x] 'nullptr' [C++0x 2.14.7]
466 /// '(' expression ')'
467 /// '__func__' [C99 6.4.2.2]
468 /// [GNU] '__FUNCTION__'
469 /// [GNU] '__PRETTY_FUNCTION__'
470 /// [GNU] '(' compound-statement ')'
471 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
472 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
473 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
475 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
477 /// [OBJC] '[' objc-message-expr ']'
478 /// [OBJC] '@selector' '(' objc-selector-arg ')'
479 /// [OBJC] '@protocol' '(' identifier ')'
480 /// [OBJC] '@encode' '(' type-name ')'
481 /// [OBJC] objc-string-literal
482 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
483 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
484 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
485 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
486 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
487 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
488 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
489 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
490 /// [C++] 'this' [C++ 9.3.2]
491 /// [G++] unary-type-trait '(' type-id ')'
492 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
493 /// [clang] '^' block-literal
495 /// constant: [C99 6.4.4]
497 /// floating-constant
498 /// enumeration-constant -> identifier
499 /// character-constant
501 /// id-expression: [C++ 5.1]
505 /// unqualified-id: [C++ 5.1]
507 /// operator-function-id
508 /// conversion-function-id
512 /// new-expression: [C++ 5.3.4]
513 /// '::'[opt] 'new' new-placement[opt] new-type-id
514 /// new-initializer[opt]
515 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
516 /// new-initializer[opt]
518 /// delete-expression: [C++ 5.3.5]
519 /// '::'[opt] 'delete' cast-expression
520 /// '::'[opt] 'delete' '[' ']' cast-expression
522 /// [GNU] unary-type-trait:
523 /// '__has_nothrow_assign'
524 /// '__has_nothrow_copy'
525 /// '__has_nothrow_constructor'
526 /// '__has_trivial_assign' [TODO]
527 /// '__has_trivial_copy' [TODO]
528 /// '__has_trivial_constructor'
529 /// '__has_trivial_destructor'
530 /// '__has_virtual_destructor'
531 /// '__is_abstract' [TODO]
533 /// '__is_empty' [TODO]
536 /// '__is_polymorphic'
539 /// [GNU] binary-type-trait:
540 /// '__is_base_of' [TODO]
542 ExprResult
Parser::ParseCastExpression(bool isUnaryExpression
,
543 bool isAddressOfOperand
,
545 ParsedType TypeOfCast
) {
547 tok::TokenKind SavedKind
= Tok
.getKind();
550 // This handles all of cast-expression, unary-expression, postfix-expression,
551 // and primary-expression. We handle them together like this for efficiency
552 // and to simplify handling of an expression starting with a '(' token: which
553 // may be one of a parenthesized expression, cast-expression, compound literal
554 // expression, or statement expression.
556 // If the parsed tokens consist of a primary-expression, the cases below
557 // break out of the switch; at the end we call ParsePostfixExpressionSuffix
558 // to handle the postfix expression suffixes. Cases that cannot be followed
559 // by postfix exprs should return without invoking
560 // ParsePostfixExpressionSuffix.
563 // If this expression is limited to being a unary-expression, the parent can
564 // not start a cast expression.
565 ParenParseOption ParenExprType
=
566 (isUnaryExpression
&& !getLang().CPlusPlus
)? CompoundLiteral
: CastExpr
;
568 SourceLocation LParenLoc
= Tok
.getLocation();
569 SourceLocation RParenLoc
;
572 // The inside of the parens don't need to be a colon protected scope, and
573 // isn't immediately a message send.
574 ColonProtectionRAIIObject
X(*this, false);
576 Res
= ParseParenExpression(ParenExprType
, false/*stopIfCastExr*/,
577 TypeOfCast
, CastTy
, RParenLoc
);
580 switch (ParenExprType
) {
581 case SimpleExpr
: break; // Nothing else to do.
582 case CompoundStmt
: break; // Nothing else to do.
583 case CompoundLiteral
:
584 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
585 // postfix-expression exist, parse them now.
588 // We have parsed the cast-expression and no postfix-expr pieces are
596 // primary-expression
597 case tok::numeric_constant
:
598 // constant: integer-constant
599 // constant: floating-constant
601 Res
= Actions
.ActOnNumericConstant(Tok
);
607 return ParseCXXBoolLiteral();
609 case tok::kw_nullptr
:
610 return Actions
.ActOnCXXNullPtrLiteral(ConsumeToken());
612 case tok::identifier
: { // primary-expression: identifier
613 // unqualified-id: identifier
614 // constant: enumeration-constant
615 // Turn a potentially qualified name into a annot_typename or
616 // annot_cxxscope if it would be valid. This handles things like x::y, etc.
617 if (getLang().CPlusPlus
) {
618 // Avoid the unnecessary parse-time lookup in the common case
619 // where the syntax forbids a type.
620 const Token
&Next
= NextToken();
621 if (Next
.is(tok::coloncolon
) ||
622 (!ColonIsSacred
&& Next
.is(tok::colon
)) ||
623 Next
.is(tok::less
) ||
624 Next
.is(tok::l_paren
)) {
625 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
626 if (TryAnnotateTypeOrScopeToken())
628 if (!Tok
.is(tok::identifier
))
629 return ParseCastExpression(isUnaryExpression
, isAddressOfOperand
);
633 // Consume the identifier so that we can see if it is followed by a '(' or
635 IdentifierInfo
&II
= *Tok
.getIdentifierInfo();
636 SourceLocation ILoc
= ConsumeToken();
638 // Support 'Class.property' and 'super.property' notation.
639 if (getLang().ObjC1
&& Tok
.is(tok::period
) &&
640 (Actions
.getTypeName(II
, ILoc
, getCurScope()) ||
641 // Allow the base to be 'super' if in an objc-method.
642 (&II
== Ident_super
&& getCurScope()->isInObjcMethodScope()))) {
643 SourceLocation DotLoc
= ConsumeToken();
645 if (Tok
.isNot(tok::identifier
)) {
646 Diag(Tok
, diag::err_expected_property_name
);
649 IdentifierInfo
&PropertyName
= *Tok
.getIdentifierInfo();
650 SourceLocation PropertyLoc
= ConsumeToken();
652 Res
= Actions
.ActOnClassPropertyRefExpr(II
, PropertyName
,
657 // In an Objective-C method, if we have "super" followed by an identifier,
658 // the token sequence is ill-formed. However, if there's a ':' or ']' after
659 // that identifier, this is probably a message send with a missing open
660 // bracket. Treat it as such.
661 if (getLang().ObjC1
&& &II
== Ident_super
&& !InMessageExpression
&&
662 getCurScope()->isInObjcMethodScope() &&
663 ((Tok
.is(tok::identifier
) &&
664 (NextToken().is(tok::colon
) || NextToken().is(tok::r_square
))) ||
665 Tok
.is(tok::code_completion
))) {
666 Res
= ParseObjCMessageExpressionBody(SourceLocation(), ILoc
, ParsedType(),
671 // If we have an Objective-C class name followed by an identifier and
672 // either ':' or ']', this is an Objective-C class message send that's
673 // missing the opening '['. Recovery appropriately.
674 if (getLang().ObjC1
&& Tok
.is(tok::identifier
) && !InMessageExpression
) {
675 const Token
& Next
= NextToken();
676 if (Next
.is(tok::colon
) || Next
.is(tok::r_square
))
677 if (ParsedType Typ
= Actions
.getTypeName(II
, ILoc
, getCurScope()))
678 if (Typ
.get()->isObjCObjectOrInterfaceType()) {
679 // Fake up a Declarator to use with ActOnTypeName.
681 DS
.SetRangeStart(ILoc
);
682 DS
.SetRangeEnd(ILoc
);
683 const char *PrevSpec
= 0;
685 DS
.SetTypeSpecType(TST_typename
, ILoc
, PrevSpec
, DiagID
, Typ
);
687 Declarator
DeclaratorInfo(DS
, Declarator::TypeNameContext
);
688 TypeResult Ty
= Actions
.ActOnTypeName(getCurScope(),
693 Res
= ParseObjCMessageExpressionBody(SourceLocation(),
700 // Make sure to pass down the right value for isAddressOfOperand.
701 if (isAddressOfOperand
&& isPostfixExpressionSuffixStart())
702 isAddressOfOperand
= false;
704 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
705 // need to know whether or not this identifier is a function designator or
708 CXXScopeSpec ScopeSpec
;
709 Name
.setIdentifier(&II
, ILoc
);
710 Res
= Actions
.ActOnIdExpression(getCurScope(), ScopeSpec
, Name
,
711 Tok
.is(tok::l_paren
), isAddressOfOperand
);
714 case tok::char_constant
: // constant: character-constant
715 Res
= Actions
.ActOnCharacterConstant(Tok
);
718 case tok::kw___func__
: // primary-expression: __func__ [C99 6.4.2.2]
719 case tok::kw___FUNCTION__
: // primary-expression: __FUNCTION__ [GNU]
720 case tok::kw___PRETTY_FUNCTION__
: // primary-expression: __P..Y_F..N__ [GNU]
721 Res
= Actions
.ActOnPredefinedExpr(Tok
.getLocation(), SavedKind
);
724 case tok::string_literal
: // primary-expression: string-literal
725 case tok::wide_string_literal
:
726 Res
= ParseStringLiteralExpression();
728 case tok::kw___builtin_va_arg
:
729 case tok::kw___builtin_offsetof
:
730 case tok::kw___builtin_choose_expr
:
731 return ParseBuiltinPrimaryExpression();
733 return Actions
.ActOnGNUNullExpr(ConsumeToken());
735 case tok::plusplus
: // unary-expression: '++' unary-expression [C99]
736 case tok::minusminus
: { // unary-expression: '--' unary-expression [C99]
737 // C++ [expr.unary] has:
739 // ++ cast-expression
740 // -- cast-expression
741 SourceLocation SavedLoc
= ConsumeToken();
742 Res
= ParseCastExpression(!getLang().CPlusPlus
);
743 if (!Res
.isInvalid())
744 Res
= Actions
.ActOnUnaryOp(getCurScope(), SavedLoc
, SavedKind
, Res
.get());
747 case tok::amp
: { // unary-expression: '&' cast-expression
748 // Special treatment because of member pointers
749 SourceLocation SavedLoc
= ConsumeToken();
750 Res
= ParseCastExpression(false, true);
751 if (!Res
.isInvalid())
752 Res
= Actions
.ActOnUnaryOp(getCurScope(), SavedLoc
, SavedKind
, Res
.get());
756 case tok::star
: // unary-expression: '*' cast-expression
757 case tok::plus
: // unary-expression: '+' cast-expression
758 case tok::minus
: // unary-expression: '-' cast-expression
759 case tok::tilde
: // unary-expression: '~' cast-expression
760 case tok::exclaim
: // unary-expression: '!' cast-expression
761 case tok::kw___real
: // unary-expression: '__real' cast-expression [GNU]
762 case tok::kw___imag
: { // unary-expression: '__imag' cast-expression [GNU]
763 SourceLocation SavedLoc
= ConsumeToken();
764 Res
= ParseCastExpression(false);
765 if (!Res
.isInvalid())
766 Res
= Actions
.ActOnUnaryOp(getCurScope(), SavedLoc
, SavedKind
, Res
.get());
770 case tok::kw___extension__
:{//unary-expression:'__extension__' cast-expr [GNU]
771 // __extension__ silences extension warnings in the subexpression.
772 ExtensionRAIIObject
O(Diags
); // Use RAII to do this.
773 SourceLocation SavedLoc
= ConsumeToken();
774 Res
= ParseCastExpression(false);
775 if (!Res
.isInvalid())
776 Res
= Actions
.ActOnUnaryOp(getCurScope(), SavedLoc
, SavedKind
, Res
.get());
779 case tok::kw_sizeof
: // unary-expression: 'sizeof' unary-expression
780 // unary-expression: 'sizeof' '(' type-name ')'
781 case tok::kw_alignof
:
782 case tok::kw___alignof
: // unary-expression: '__alignof' unary-expression
783 // unary-expression: '__alignof' '(' type-name ')'
784 // unary-expression: 'alignof' '(' type-id ')'
785 return ParseSizeofAlignofExpression();
786 case tok::ampamp
: { // unary-expression: '&&' identifier
787 SourceLocation AmpAmpLoc
= ConsumeToken();
788 if (Tok
.isNot(tok::identifier
))
789 return ExprError(Diag(Tok
, diag::err_expected_ident
));
791 Diag(AmpAmpLoc
, diag::ext_gnu_address_of_label
);
792 Res
= Actions
.ActOnAddrLabel(AmpAmpLoc
, Tok
.getLocation(),
793 Tok
.getIdentifierInfo());
797 case tok::kw_const_cast
:
798 case tok::kw_dynamic_cast
:
799 case tok::kw_reinterpret_cast
:
800 case tok::kw_static_cast
:
801 Res
= ParseCXXCasts();
804 Res
= ParseCXXTypeid();
806 case tok::kw___uuidof
:
807 Res
= ParseCXXUuidof();
810 Res
= ParseCXXThis();
813 case tok::annot_typename
:
814 if (isStartOfObjCClassMessageMissingOpenBracket()) {
815 ParsedType Type
= getTypeAnnotation(Tok
);
817 // Fake up a Declarator to use with ActOnTypeName.
819 DS
.SetRangeStart(Tok
.getLocation());
820 DS
.SetRangeEnd(Tok
.getLastLoc());
822 const char *PrevSpec
= 0;
824 DS
.SetTypeSpecType(TST_typename
, Tok
.getAnnotationEndLoc(),
825 PrevSpec
, DiagID
, Type
);
827 Declarator
DeclaratorInfo(DS
, Declarator::TypeNameContext
);
828 TypeResult Ty
= Actions
.ActOnTypeName(getCurScope(), DeclaratorInfo
);
833 Res
= ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
840 case tok::kw_wchar_t
:
841 case tok::kw_char16_t
:
842 case tok::kw_char32_t
:
848 case tok::kw_unsigned
:
852 case tok::kw_typename
:
854 case tok::kw___vector
: {
855 if (!getLang().CPlusPlus
) {
856 Diag(Tok
, diag::err_expected_expression
);
860 if (SavedKind
== tok::kw_typename
) {
861 // postfix-expression: typename-specifier '(' expression-list[opt] ')'
862 if (TryAnnotateTypeOrScopeToken())
866 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
869 ParseCXXSimpleTypeSpecifier(DS
);
870 if (Tok
.isNot(tok::l_paren
))
871 return ExprError(Diag(Tok
, diag::err_expected_lparen_after_type
)
872 << DS
.getSourceRange());
874 Res
= ParseCXXTypeConstructExpression(DS
);
878 case tok::annot_cxxscope
: { // [C++] id-expression: qualified-id
879 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
880 // (We can end up in this situation after tentative parsing.)
881 if (TryAnnotateTypeOrScopeToken())
883 if (!Tok
.is(tok::annot_cxxscope
))
884 return ParseCastExpression(isUnaryExpression
, isAddressOfOperand
,
885 NotCastExpr
, TypeOfCast
);
887 Token Next
= NextToken();
888 if (Next
.is(tok::annot_template_id
)) {
889 TemplateIdAnnotation
*TemplateId
890 = static_cast<TemplateIdAnnotation
*>(Next
.getAnnotationValue());
891 if (TemplateId
->Kind
== TNK_Type_template
) {
892 // We have a qualified template-id that we know refers to a
893 // type, translate it into a type and continue parsing as a
896 ParseOptionalCXXScopeSpecifier(SS
, ParsedType(), false);
897 AnnotateTemplateIdTokenAsType(&SS
);
898 return ParseCastExpression(isUnaryExpression
, isAddressOfOperand
,
899 NotCastExpr
, TypeOfCast
);
903 // Parse as an id-expression.
904 Res
= ParseCXXIdExpression(isAddressOfOperand
);
908 case tok::annot_template_id
: { // [C++] template-id
909 TemplateIdAnnotation
*TemplateId
910 = static_cast<TemplateIdAnnotation
*>(Tok
.getAnnotationValue());
911 if (TemplateId
->Kind
== TNK_Type_template
) {
912 // We have a template-id that we know refers to a type,
913 // translate it into a type and continue parsing as a cast
915 AnnotateTemplateIdTokenAsType();
916 return ParseCastExpression(isUnaryExpression
, isAddressOfOperand
,
917 NotCastExpr
, TypeOfCast
);
920 // Fall through to treat the template-id as an id-expression.
923 case tok::kw_operator
: // [C++] id-expression: operator/conversion-function-id
924 Res
= ParseCXXIdExpression(isAddressOfOperand
);
927 case tok::coloncolon
: {
928 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
929 // annotates the token, tail recurse.
930 if (TryAnnotateTypeOrScopeToken())
932 if (!Tok
.is(tok::coloncolon
))
933 return ParseCastExpression(isUnaryExpression
, isAddressOfOperand
);
935 // ::new -> [C++] new-expression
936 // ::delete -> [C++] delete-expression
937 SourceLocation CCLoc
= ConsumeToken();
938 if (Tok
.is(tok::kw_new
))
939 return ParseCXXNewExpression(true, CCLoc
);
940 if (Tok
.is(tok::kw_delete
))
941 return ParseCXXDeleteExpression(true, CCLoc
);
943 // This is not a type name or scope specifier, it is an invalid expression.
944 Diag(CCLoc
, diag::err_expected_expression
);
948 case tok::kw_new
: // [C++] new-expression
949 return ParseCXXNewExpression(false, Tok
.getLocation());
951 case tok::kw_delete
: // [C++] delete-expression
952 return ParseCXXDeleteExpression(false, Tok
.getLocation());
954 case tok::kw_noexcept
: { // [C++0x] 'noexcept' '(' expression ')'
955 SourceLocation KeyLoc
= ConsumeToken();
956 SourceLocation LParen
= Tok
.getLocation();
957 if (ExpectAndConsume(tok::l_paren
,
958 diag::err_expected_lparen_after
, "noexcept"))
960 // C++ [expr.unary.noexcept]p1:
961 // The noexcept operator determines whether the evaluation of its operand,
962 // which is an unevaluated operand, can throw an exception.
963 EnterExpressionEvaluationContext
Unevaluated(Actions
, Sema::Unevaluated
);
964 ExprResult Result
= ParseExpression();
965 SourceLocation RParen
= MatchRHSPunctuation(tok::r_paren
, LParen
);
966 if (!Result
.isInvalid())
967 Result
= Actions
.ActOnNoexceptExpr(KeyLoc
, LParen
, Result
.take(), RParen
);
971 case tok::kw___is_pod
: // [GNU] unary-type-trait
972 case tok::kw___is_class
:
973 case tok::kw___is_enum
:
974 case tok::kw___is_union
:
975 case tok::kw___is_empty
:
976 case tok::kw___is_polymorphic
:
977 case tok::kw___is_abstract
:
978 case tok::kw___is_literal
:
979 case tok::kw___has_trivial_constructor
:
980 case tok::kw___has_trivial_copy
:
981 case tok::kw___has_trivial_assign
:
982 case tok::kw___has_trivial_destructor
:
983 case tok::kw___has_nothrow_assign
:
984 case tok::kw___has_nothrow_copy
:
985 case tok::kw___has_nothrow_constructor
:
986 case tok::kw___has_virtual_destructor
:
987 return ParseUnaryTypeTrait();
989 case tok::kw___builtin_types_compatible_p
:
990 case tok::kw___is_base_of
:
991 return ParseBinaryTypeTrait();
994 SourceLocation AtLoc
= ConsumeToken();
995 return ParseObjCAtExpression(AtLoc
);
998 return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression());
999 case tok::code_completion
:
1000 Actions
.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression
);
1001 ConsumeCodeCompletionToken();
1002 return ParseCastExpression(isUnaryExpression
, isAddressOfOperand
,
1003 NotCastExpr
, TypeOfCast
);
1005 // These can be followed by postfix-expr pieces.
1006 if (getLang().ObjC1
)
1007 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression());
1014 // These can be followed by postfix-expr pieces.
1015 return ParsePostfixExpressionSuffix(Res
);
1018 /// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
1019 /// is parsed, this method parses any suffixes that apply.
1021 /// postfix-expression: [C99 6.5.2]
1022 /// primary-expression
1023 /// postfix-expression '[' expression ']'
1024 /// postfix-expression '(' argument-expression-list[opt] ')'
1025 /// postfix-expression '.' identifier
1026 /// postfix-expression '->' identifier
1027 /// postfix-expression '++'
1028 /// postfix-expression '--'
1029 /// '(' type-name ')' '{' initializer-list '}'
1030 /// '(' type-name ')' '{' initializer-list ',' '}'
1032 /// argument-expression-list: [C99 6.5.2]
1033 /// argument-expression ...[opt]
1034 /// argument-expression-list ',' assignment-expression ...[opt]
1037 Parser::ParsePostfixExpressionSuffix(ExprResult LHS
) {
1038 // Now that the primary-expression piece of the postfix-expression has been
1039 // parsed, see if there are any postfix-expression pieces here.
1042 switch (Tok
.getKind()) {
1043 case tok::code_completion
:
1044 if (InMessageExpression
)
1047 Actions
.CodeCompletePostfixExpression(getCurScope(), LHS
);
1048 ConsumeCodeCompletionToken();
1052 case tok::identifier
:
1053 // If we see identifier: after an expression, and we're not already in a
1054 // message send, then this is probably a message send with a missing
1055 // opening bracket '['.
1056 if (getLang().ObjC1
&& !InMessageExpression
&&
1057 (NextToken().is(tok::colon
) || NextToken().is(tok::r_square
))) {
1058 LHS
= ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1059 ParsedType(), LHS
.get());
1063 // Fall through; this isn't a message send.
1065 default: // Not a postfix-expression suffix.
1067 case tok::l_square
: { // postfix-expression: p-e '[' expression ']'
1068 // If we have a array postfix expression that starts on a new line and
1069 // Objective-C is enabled, it is highly likely that the user forgot a
1070 // semicolon after the base expression and that the array postfix-expr is
1071 // actually another message send. In this case, do some look-ahead to see
1072 // if the contents of the square brackets are obviously not a valid
1073 // expression and recover by pretending there is no suffix.
1074 if (getLang().ObjC1
&& Tok
.isAtStartOfLine() &&
1075 isSimpleObjCMessageExpression())
1078 Loc
= ConsumeBracket();
1079 ExprResult
Idx(ParseExpression());
1081 SourceLocation RLoc
= Tok
.getLocation();
1083 if (!LHS
.isInvalid() && !Idx
.isInvalid() && Tok
.is(tok::r_square
)) {
1084 LHS
= Actions
.ActOnArraySubscriptExpr(getCurScope(), LHS
.take(), Loc
,
1090 MatchRHSPunctuation(tok::r_square
, Loc
);
1094 case tok::l_paren
: { // p-e: p-e '(' argument-expression-list[opt] ')'
1095 InMessageExpressionRAIIObject
InMessage(*this, false);
1097 ExprVector
ArgExprs(Actions
);
1098 CommaLocsTy CommaLocs
;
1100 Loc
= ConsumeParen();
1102 if (Tok
.is(tok::code_completion
)) {
1103 Actions
.CodeCompleteCall(getCurScope(), LHS
.get(), 0, 0);
1104 ConsumeCodeCompletionToken();
1107 if (Tok
.isNot(tok::r_paren
)) {
1108 if (ParseExpressionList(ArgExprs
, CommaLocs
, &Sema::CodeCompleteCall
,
1110 SkipUntil(tok::r_paren
);
1116 if (LHS
.isInvalid()) {
1117 SkipUntil(tok::r_paren
);
1118 } else if (Tok
.isNot(tok::r_paren
)) {
1119 MatchRHSPunctuation(tok::r_paren
, Loc
);
1122 assert((ArgExprs
.size() == 0 ||
1123 ArgExprs
.size()-1 == CommaLocs
.size())&&
1124 "Unexpected number of commas!");
1125 LHS
= Actions
.ActOnCallExpr(getCurScope(), LHS
.take(), Loc
,
1126 move_arg(ArgExprs
), Tok
.getLocation());
1134 // postfix-expression: p-e '->' template[opt] id-expression
1135 // postfix-expression: p-e '.' template[opt] id-expression
1136 tok::TokenKind OpKind
= Tok
.getKind();
1137 SourceLocation OpLoc
= ConsumeToken(); // Eat the "." or "->" token.
1140 ParsedType ObjectType
;
1141 bool MayBePseudoDestructor
= false;
1142 if (getLang().CPlusPlus
&& !LHS
.isInvalid()) {
1143 LHS
= Actions
.ActOnStartCXXMemberReference(getCurScope(), LHS
.take(),
1144 OpLoc
, OpKind
, ObjectType
,
1145 MayBePseudoDestructor
);
1146 if (LHS
.isInvalid())
1149 ParseOptionalCXXScopeSpecifier(SS
, ObjectType
, false,
1150 &MayBePseudoDestructor
);
1151 if (SS
.isNotEmpty())
1152 ObjectType
= ParsedType();
1155 if (Tok
.is(tok::code_completion
)) {
1156 // Code completion for a member access expression.
1157 Actions
.CodeCompleteMemberReferenceExpr(getCurScope(), LHS
.get(),
1158 OpLoc
, OpKind
== tok::arrow
);
1160 ConsumeCodeCompletionToken();
1163 if (MayBePseudoDestructor
&& !LHS
.isInvalid()) {
1164 LHS
= ParseCXXPseudoDestructor(LHS
.take(), OpLoc
, OpKind
, SS
,
1169 // Either the action has told is that this cannot be a
1170 // pseudo-destructor expression (based on the type of base
1171 // expression), or we didn't see a '~' in the right place. We
1172 // can still parse a destructor name here, but in that case it
1173 // names a real destructor.
1175 if (ParseUnqualifiedId(SS
,
1176 /*EnteringContext=*/false,
1177 /*AllowDestructorName=*/true,
1178 /*AllowConstructorName=*/false,
1183 if (!LHS
.isInvalid())
1184 LHS
= Actions
.ActOnMemberAccessExpr(getCurScope(), LHS
.take(), OpLoc
,
1185 OpKind
, SS
, Name
, ObjCImpDecl
,
1186 Tok
.is(tok::l_paren
));
1189 case tok::plusplus
: // postfix-expression: postfix-expression '++'
1190 case tok::minusminus
: // postfix-expression: postfix-expression '--'
1191 if (!LHS
.isInvalid()) {
1192 LHS
= Actions
.ActOnPostfixUnaryOp(getCurScope(), Tok
.getLocation(),
1193 Tok
.getKind(), LHS
.take());
1201 /// ParseExprAfterTypeofSizeofAlignof - We parsed a typeof/sizeof/alignof and
1202 /// we are at the start of an expression or a parenthesized type-id.
1203 /// OpTok is the operand token (typeof/sizeof/alignof). Returns the expression
1204 /// (isCastExpr == false) or the type (isCastExpr == true).
1206 /// unary-expression: [C99 6.5.3]
1207 /// 'sizeof' unary-expression
1208 /// 'sizeof' '(' type-name ')'
1209 /// [GNU] '__alignof' unary-expression
1210 /// [GNU] '__alignof' '(' type-name ')'
1211 /// [C++0x] 'alignof' '(' type-id ')'
1213 /// [GNU] typeof-specifier:
1214 /// typeof ( expressions )
1215 /// typeof ( type-name )
1216 /// [GNU/C++] typeof unary-expression
1219 Parser::ParseExprAfterTypeofSizeofAlignof(const Token
&OpTok
,
1222 SourceRange
&CastRange
) {
1224 assert((OpTok
.is(tok::kw_typeof
) || OpTok
.is(tok::kw_sizeof
) ||
1225 OpTok
.is(tok::kw___alignof
) || OpTok
.is(tok::kw_alignof
)) &&
1226 "Not a typeof/sizeof/alignof expression!");
1230 // If the operand doesn't start with an '(', it must be an expression.
1231 if (Tok
.isNot(tok::l_paren
)) {
1233 if (OpTok
.is(tok::kw_typeof
) && !getLang().CPlusPlus
) {
1234 Diag(Tok
,diag::err_expected_lparen_after_id
) << OpTok
.getIdentifierInfo();
1238 // C++0x [expr.sizeof]p1:
1239 // [...] The operand is either an expression, which is an unevaluated
1240 // operand (Clause 5) [...]
1242 // The GNU typeof and alignof extensions also behave as unevaluated
1244 EnterExpressionEvaluationContext
Unevaluated(Actions
,
1246 Operand
= ParseCastExpression(true/*isUnaryExpression*/);
1248 // If it starts with a '(', we know that it is either a parenthesized
1249 // type-name, or it is a unary-expression that starts with a compound
1250 // literal, or starts with a primary-expression that is a parenthesized
1252 ParenParseOption ExprType
= CastExpr
;
1253 SourceLocation LParenLoc
= Tok
.getLocation(), RParenLoc
;
1255 // C++0x [expr.sizeof]p1:
1256 // [...] The operand is either an expression, which is an unevaluated
1257 // operand (Clause 5) [...]
1259 // The GNU typeof and alignof extensions also behave as unevaluated
1261 EnterExpressionEvaluationContext
Unevaluated(Actions
,
1263 Operand
= ParseParenExpression(ExprType
, true/*stopIfCastExpr*/,
1264 ParsedType(), CastTy
, RParenLoc
);
1265 CastRange
= SourceRange(LParenLoc
, RParenLoc
);
1267 // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1269 if (ExprType
== CastExpr
) {
1274 if (getLang().CPlusPlus
|| OpTok
.isNot(tok::kw_typeof
)) {
1275 // GNU typeof in C requires the expression to be parenthesized. Not so for
1276 // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1277 // the start of a unary-expression, but doesn't include any postfix
1278 // pieces. Parse these now if present.
1279 if (!Operand
.isInvalid())
1280 Operand
= ParsePostfixExpressionSuffix(Operand
.get());
1284 // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
1286 return move(Operand
);
1290 /// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression.
1291 /// unary-expression: [C99 6.5.3]
1292 /// 'sizeof' unary-expression
1293 /// 'sizeof' '(' type-name ')'
1294 /// [GNU] '__alignof' unary-expression
1295 /// [GNU] '__alignof' '(' type-name ')'
1296 /// [C++0x] 'alignof' '(' type-id ')'
1297 ExprResult
Parser::ParseSizeofAlignofExpression() {
1298 assert((Tok
.is(tok::kw_sizeof
) || Tok
.is(tok::kw___alignof
)
1299 || Tok
.is(tok::kw_alignof
)) &&
1300 "Not a sizeof/alignof expression!");
1306 SourceRange CastRange
;
1307 ExprResult Operand
= ParseExprAfterTypeofSizeofAlignof(OpTok
,
1313 return Actions
.ActOnSizeOfAlignOfExpr(OpTok
.getLocation(),
1314 OpTok
.is(tok::kw_sizeof
),
1316 CastTy
.getAsOpaquePtr(),
1319 // If we get here, the operand to the sizeof/alignof was an expresion.
1320 if (!Operand
.isInvalid())
1321 Operand
= Actions
.ActOnSizeOfAlignOfExpr(OpTok
.getLocation(),
1322 OpTok
.is(tok::kw_sizeof
),
1324 Operand
.release(), CastRange
);
1325 return move(Operand
);
1328 /// ParseBuiltinPrimaryExpression
1330 /// primary-expression: [C99 6.5.1]
1331 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1332 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
1333 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
1335 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
1337 /// [GNU] offsetof-member-designator:
1338 /// [GNU] identifier
1339 /// [GNU] offsetof-member-designator '.' identifier
1340 /// [GNU] offsetof-member-designator '[' expression ']'
1342 ExprResult
Parser::ParseBuiltinPrimaryExpression() {
1344 const IdentifierInfo
*BuiltinII
= Tok
.getIdentifierInfo();
1346 tok::TokenKind T
= Tok
.getKind();
1347 SourceLocation StartLoc
= ConsumeToken(); // Eat the builtin identifier.
1349 // All of these start with an open paren.
1350 if (Tok
.isNot(tok::l_paren
))
1351 return ExprError(Diag(Tok
, diag::err_expected_lparen_after_id
)
1354 SourceLocation LParenLoc
= ConsumeParen();
1358 default: assert(0 && "Not a builtin primary expression!");
1359 case tok::kw___builtin_va_arg
: {
1360 ExprResult
Expr(ParseAssignmentExpression());
1362 if (ExpectAndConsume(tok::comma
, diag::err_expected_comma
, "",tok::r_paren
))
1365 TypeResult Ty
= ParseTypeName();
1367 if (Tok
.isNot(tok::r_paren
)) {
1368 Diag(Tok
, diag::err_expected_rparen
);
1372 if (Expr
.isInvalid() || Ty
.isInvalid())
1375 Res
= Actions
.ActOnVAArg(StartLoc
, Expr
.take(), Ty
.get(), ConsumeParen());
1378 case tok::kw___builtin_offsetof
: {
1379 SourceLocation TypeLoc
= Tok
.getLocation();
1380 TypeResult Ty
= ParseTypeName();
1381 if (Ty
.isInvalid()) {
1382 SkipUntil(tok::r_paren
);
1386 if (ExpectAndConsume(tok::comma
, diag::err_expected_comma
, "",tok::r_paren
))
1389 // We must have at least one identifier here.
1390 if (Tok
.isNot(tok::identifier
)) {
1391 Diag(Tok
, diag::err_expected_ident
);
1392 SkipUntil(tok::r_paren
);
1396 // Keep track of the various subcomponents we see.
1397 llvm::SmallVector
<Sema::OffsetOfComponent
, 4> Comps
;
1399 Comps
.push_back(Sema::OffsetOfComponent());
1400 Comps
.back().isBrackets
= false;
1401 Comps
.back().U
.IdentInfo
= Tok
.getIdentifierInfo();
1402 Comps
.back().LocStart
= Comps
.back().LocEnd
= ConsumeToken();
1404 // FIXME: This loop leaks the index expressions on error.
1406 if (Tok
.is(tok::period
)) {
1407 // offsetof-member-designator: offsetof-member-designator '.' identifier
1408 Comps
.push_back(Sema::OffsetOfComponent());
1409 Comps
.back().isBrackets
= false;
1410 Comps
.back().LocStart
= ConsumeToken();
1412 if (Tok
.isNot(tok::identifier
)) {
1413 Diag(Tok
, diag::err_expected_ident
);
1414 SkipUntil(tok::r_paren
);
1417 Comps
.back().U
.IdentInfo
= Tok
.getIdentifierInfo();
1418 Comps
.back().LocEnd
= ConsumeToken();
1420 } else if (Tok
.is(tok::l_square
)) {
1421 // offsetof-member-designator: offsetof-member-design '[' expression ']'
1422 Comps
.push_back(Sema::OffsetOfComponent());
1423 Comps
.back().isBrackets
= true;
1424 Comps
.back().LocStart
= ConsumeBracket();
1425 Res
= ParseExpression();
1426 if (Res
.isInvalid()) {
1427 SkipUntil(tok::r_paren
);
1430 Comps
.back().U
.E
= Res
.release();
1432 Comps
.back().LocEnd
=
1433 MatchRHSPunctuation(tok::r_square
, Comps
.back().LocStart
);
1435 if (Tok
.isNot(tok::r_paren
)) {
1436 MatchRHSPunctuation(tok::r_paren
, LParenLoc
);
1438 } else if (Ty
.isInvalid()) {
1441 Res
= Actions
.ActOnBuiltinOffsetOf(getCurScope(), StartLoc
, TypeLoc
,
1442 Ty
.get(), &Comps
[0],
1443 Comps
.size(), ConsumeParen());
1450 case tok::kw___builtin_choose_expr
: {
1451 ExprResult
Cond(ParseAssignmentExpression());
1452 if (Cond
.isInvalid()) {
1453 SkipUntil(tok::r_paren
);
1456 if (ExpectAndConsume(tok::comma
, diag::err_expected_comma
, "",tok::r_paren
))
1459 ExprResult
Expr1(ParseAssignmentExpression());
1460 if (Expr1
.isInvalid()) {
1461 SkipUntil(tok::r_paren
);
1464 if (ExpectAndConsume(tok::comma
, diag::err_expected_comma
, "",tok::r_paren
))
1467 ExprResult
Expr2(ParseAssignmentExpression());
1468 if (Expr2
.isInvalid()) {
1469 SkipUntil(tok::r_paren
);
1472 if (Tok
.isNot(tok::r_paren
)) {
1473 Diag(Tok
, diag::err_expected_rparen
);
1476 Res
= Actions
.ActOnChooseExpr(StartLoc
, Cond
.take(), Expr1
.take(),
1477 Expr2
.take(), ConsumeParen());
1482 if (Res
.isInvalid())
1485 // These can be followed by postfix-expr pieces because they are
1486 // primary-expressions.
1487 return ParsePostfixExpressionSuffix(Res
.take());
1490 /// ParseParenExpression - This parses the unit that starts with a '(' token,
1491 /// based on what is allowed by ExprType. The actual thing parsed is returned
1492 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
1493 /// not the parsed cast-expression.
1495 /// primary-expression: [C99 6.5.1]
1496 /// '(' expression ')'
1497 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
1498 /// postfix-expression: [C99 6.5.2]
1499 /// '(' type-name ')' '{' initializer-list '}'
1500 /// '(' type-name ')' '{' initializer-list ',' '}'
1501 /// cast-expression: [C99 6.5.4]
1502 /// '(' type-name ')' cast-expression
1505 Parser::ParseParenExpression(ParenParseOption
&ExprType
, bool stopIfCastExpr
,
1506 ParsedType TypeOfCast
, ParsedType
&CastTy
,
1507 SourceLocation
&RParenLoc
) {
1508 assert(Tok
.is(tok::l_paren
) && "Not a paren expr!");
1509 GreaterThanIsOperatorScope
G(GreaterThanIsOperator
, true);
1510 SourceLocation OpenLoc
= ConsumeParen();
1511 ExprResult
Result(true);
1512 bool isAmbiguousTypeId
;
1513 CastTy
= ParsedType();
1515 if (Tok
.is(tok::code_completion
)) {
1516 Actions
.CodeCompleteOrdinaryName(getCurScope(),
1517 ExprType
>= CompoundLiteral
? Sema::PCC_ParenthesizedExpression
1518 : Sema::PCC_Expression
);
1519 ConsumeCodeCompletionToken();
1523 if (ExprType
>= CompoundStmt
&& Tok
.is(tok::l_brace
)) {
1524 Diag(Tok
, diag::ext_gnu_statement_expr
);
1525 ParsedAttributes attrs
;
1526 StmtResult
Stmt(ParseCompoundStatement(attrs
, true));
1527 ExprType
= CompoundStmt
;
1529 // If the substmt parsed correctly, build the AST node.
1530 if (!Stmt
.isInvalid() && Tok
.is(tok::r_paren
))
1531 Result
= Actions
.ActOnStmtExpr(OpenLoc
, Stmt
.take(), Tok
.getLocation());
1533 } else if (ExprType
>= CompoundLiteral
&&
1534 isTypeIdInParens(isAmbiguousTypeId
)) {
1536 // Otherwise, this is a compound literal expression or cast expression.
1538 // In C++, if the type-id is ambiguous we disambiguate based on context.
1539 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
1540 // in which case we should treat it as type-id.
1541 // if stopIfCastExpr is false, we need to determine the context past the
1542 // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
1543 if (isAmbiguousTypeId
&& !stopIfCastExpr
)
1544 return ParseCXXAmbiguousParenExpression(ExprType
, CastTy
,
1545 OpenLoc
, RParenLoc
);
1550 InMessageExpressionRAIIObject
InMessage(*this, false);
1551 Ty
= ParseTypeName();
1554 // If our type is followed by an identifier and either ':' or ']', then
1555 // this is probably an Objective-C message send where the leading '[' is
1556 // missing. Recover as if that were the case.
1557 if (!Ty
.isInvalid() && Tok
.is(tok::identifier
) && !InMessageExpression
&&
1558 getLang().ObjC1
&& !Ty
.get().get().isNull() &&
1559 (NextToken().is(tok::colon
) || NextToken().is(tok::r_square
)) &&
1560 Ty
.get().get()->isObjCObjectOrInterfaceType()) {
1561 Result
= ParseObjCMessageExpressionBody(SourceLocation(),
1566 if (Tok
.is(tok::r_paren
))
1567 RParenLoc
= ConsumeParen();
1569 MatchRHSPunctuation(tok::r_paren
, OpenLoc
);
1571 if (Tok
.is(tok::l_brace
)) {
1572 ExprType
= CompoundLiteral
;
1573 return ParseCompoundLiteralExpression(Ty
.get(), OpenLoc
, RParenLoc
);
1576 if (ExprType
== CastExpr
) {
1577 // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
1584 // Note that this doesn't parse the subsequent cast-expression, it just
1585 // returns the parsed type to the callee.
1587 return ExprResult();
1589 // Reject the cast of super idiom in ObjC.
1590 if (Tok
.is(tok::identifier
) && getLang().ObjC1
&&
1591 Tok
.getIdentifierInfo() == Ident_super
&&
1592 getCurScope()->isInObjcMethodScope() &&
1593 GetLookAheadToken(1).isNot(tok::period
)) {
1594 Diag(Tok
.getLocation(), diag::err_illegal_super_cast
)
1595 << SourceRange(OpenLoc
, RParenLoc
);
1599 // Parse the cast-expression that follows it next.
1600 // TODO: For cast expression with CastTy.
1601 Result
= ParseCastExpression(false, false, CastTy
);
1602 if (!Result
.isInvalid())
1603 Result
= Actions
.ActOnCastExpr(getCurScope(), OpenLoc
, CastTy
,
1604 RParenLoc
, Result
.take());
1605 return move(Result
);
1608 Diag(Tok
, diag::err_expected_lbrace_in_compound_literal
);
1611 } else if (TypeOfCast
) {
1612 // Parse the expression-list.
1613 InMessageExpressionRAIIObject
InMessage(*this, false);
1615 ExprVector
ArgExprs(Actions
);
1616 CommaLocsTy CommaLocs
;
1618 if (!ParseExpressionList(ArgExprs
, CommaLocs
)) {
1619 ExprType
= SimpleExpr
;
1620 Result
= Actions
.ActOnParenOrParenListExpr(OpenLoc
, Tok
.getLocation(),
1621 move_arg(ArgExprs
), TypeOfCast
);
1624 InMessageExpressionRAIIObject
InMessage(*this, false);
1626 Result
= ParseExpression();
1627 ExprType
= SimpleExpr
;
1628 if (!Result
.isInvalid() && Tok
.is(tok::r_paren
))
1629 Result
= Actions
.ActOnParenExpr(OpenLoc
, Tok
.getLocation(), Result
.take());
1633 if (Result
.isInvalid()) {
1634 SkipUntil(tok::r_paren
);
1638 if (Tok
.is(tok::r_paren
))
1639 RParenLoc
= ConsumeParen();
1641 MatchRHSPunctuation(tok::r_paren
, OpenLoc
);
1643 return move(Result
);
1646 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
1647 /// and we are at the left brace.
1649 /// postfix-expression: [C99 6.5.2]
1650 /// '(' type-name ')' '{' initializer-list '}'
1651 /// '(' type-name ')' '{' initializer-list ',' '}'
1654 Parser::ParseCompoundLiteralExpression(ParsedType Ty
,
1655 SourceLocation LParenLoc
,
1656 SourceLocation RParenLoc
) {
1657 assert(Tok
.is(tok::l_brace
) && "Not a compound literal!");
1658 if (!getLang().C99
) // Compound literals don't exist in C90.
1659 Diag(LParenLoc
, diag::ext_c99_compound_literal
);
1660 ExprResult Result
= ParseInitializer();
1661 if (!Result
.isInvalid() && Ty
)
1662 return Actions
.ActOnCompoundLiteral(LParenLoc
, Ty
, RParenLoc
, Result
.take());
1663 return move(Result
);
1666 /// ParseStringLiteralExpression - This handles the various token types that
1667 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
1668 /// translation phase #6].
1670 /// primary-expression: [C99 6.5.1]
1672 ExprResult
Parser::ParseStringLiteralExpression() {
1673 assert(isTokenStringLiteral() && "Not a string literal!");
1675 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
1676 // considered to be strings for concatenation purposes.
1677 llvm::SmallVector
<Token
, 4> StringToks
;
1680 StringToks
.push_back(Tok
);
1681 ConsumeStringToken();
1682 } while (isTokenStringLiteral());
1684 // Pass the set of string tokens, ready for concatenation, to the actions.
1685 return Actions
.ActOnStringLiteral(&StringToks
[0], StringToks
.size());
1688 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1690 /// argument-expression-list:
1691 /// assignment-expression
1692 /// argument-expression-list , assignment-expression
1694 /// [C++] expression-list:
1695 /// [C++] assignment-expression ...[opt]
1696 /// [C++] expression-list , assignment-expression ...[opt]
1698 bool Parser::ParseExpressionList(llvm::SmallVectorImpl
<Expr
*> &Exprs
,
1699 llvm::SmallVectorImpl
<SourceLocation
> &CommaLocs
,
1700 void (Sema::*Completer
)(Scope
*S
,
1706 if (Tok
.is(tok::code_completion
)) {
1708 (Actions
.*Completer
)(getCurScope(), Data
, Exprs
.data(), Exprs
.size());
1709 ConsumeCodeCompletionToken();
1712 ExprResult
Expr(ParseAssignmentExpression());
1713 if (Tok
.is(tok::ellipsis
))
1714 Expr
= Actions
.ActOnPackExpansion(Expr
.get(), ConsumeToken());
1715 if (Expr
.isInvalid())
1718 Exprs
.push_back(Expr
.release());
1720 if (Tok
.isNot(tok::comma
))
1722 // Move to the next argument, remember where the comma was.
1723 CommaLocs
.push_back(ConsumeToken());
1727 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
1729 /// [clang] block-id:
1730 /// [clang] specifier-qualifier-list block-declarator
1732 void Parser::ParseBlockId() {
1733 if (Tok
.is(tok::code_completion
)) {
1734 Actions
.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type
);
1735 ConsumeCodeCompletionToken();
1738 // Parse the specifier-qualifier-list piece.
1740 ParseSpecifierQualifierList(DS
);
1742 // Parse the block-declarator.
1743 Declarator
DeclaratorInfo(DS
, Declarator::BlockLiteralContext
);
1744 ParseDeclarator(DeclaratorInfo
);
1746 // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes.
1747 DeclaratorInfo
.addAttributes(DS
.takeAttributes());
1749 MaybeParseGNUAttributes(DeclaratorInfo
);
1751 // Inform sema that we are starting a block.
1752 Actions
.ActOnBlockArguments(DeclaratorInfo
, getCurScope());
1755 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
1756 /// like ^(int x){ return x+1; }
1759 /// [clang] '^' block-args[opt] compound-statement
1760 /// [clang] '^' block-id compound-statement
1761 /// [clang] block-args:
1762 /// [clang] '(' parameter-list ')'
1764 ExprResult
Parser::ParseBlockLiteralExpression() {
1765 assert(Tok
.is(tok::caret
) && "block literal starts with ^");
1766 SourceLocation CaretLoc
= ConsumeToken();
1768 PrettyStackTraceLoc
CrashInfo(PP
.getSourceManager(), CaretLoc
,
1769 "block literal parsing");
1771 // Enter a scope to hold everything within the block. This includes the
1772 // argument decls, decls within the compound expression, etc. This also
1773 // allows determining whether a variable reference inside the block is
1774 // within or outside of the block.
1775 ParseScope
BlockScope(this, Scope::BlockScope
| Scope::FnScope
|
1776 Scope::BreakScope
| Scope::ContinueScope
|
1779 // Inform sema that we are starting a block.
1780 Actions
.ActOnBlockStart(CaretLoc
, getCurScope());
1782 // Parse the return type if present.
1784 Declarator
ParamInfo(DS
, Declarator::BlockLiteralContext
);
1785 // FIXME: Since the return type isn't actually parsed, it can't be used to
1786 // fill ParamInfo with an initial valid range, so do it manually.
1787 ParamInfo
.SetSourceRange(SourceRange(Tok
.getLocation(), Tok
.getLocation()));
1789 // If this block has arguments, parse them. There is no ambiguity here with
1790 // the expression case, because the expression case requires a parameter list.
1791 if (Tok
.is(tok::l_paren
)) {
1792 ParseParenDeclarator(ParamInfo
);
1793 // Parse the pieces after the identifier as if we had "int(...)".
1794 // SetIdentifier sets the source range end, but in this case we're past
1796 SourceLocation Tmp
= ParamInfo
.getSourceRange().getEnd();
1797 ParamInfo
.SetIdentifier(0, CaretLoc
);
1798 ParamInfo
.SetRangeEnd(Tmp
);
1799 if (ParamInfo
.isInvalidType()) {
1800 // If there was an error parsing the arguments, they may have
1801 // tried to use ^(x+y) which requires an argument list. Just
1802 // skip the whole block literal.
1803 Actions
.ActOnBlockError(CaretLoc
, getCurScope());
1807 MaybeParseGNUAttributes(ParamInfo
);
1809 // Inform sema that we are starting a block.
1810 Actions
.ActOnBlockArguments(ParamInfo
, getCurScope());
1811 } else if (!Tok
.is(tok::l_brace
)) {
1814 // Otherwise, pretend we saw (void).
1815 ParamInfo
.AddTypeInfo(DeclaratorChunk::getFunction(ParsedAttributes(),
1819 false, SourceLocation(),
1825 MaybeParseGNUAttributes(ParamInfo
);
1827 // Inform sema that we are starting a block.
1828 Actions
.ActOnBlockArguments(ParamInfo
, getCurScope());
1832 ExprResult
Result(true);
1833 if (!Tok
.is(tok::l_brace
)) {
1834 // Saw something like: ^expr
1835 Diag(Tok
, diag::err_expected_expression
);
1836 Actions
.ActOnBlockError(CaretLoc
, getCurScope());
1840 StmtResult
Stmt(ParseCompoundStatementBody());
1841 if (!Stmt
.isInvalid())
1842 Result
= Actions
.ActOnBlockStmtExpr(CaretLoc
, Stmt
.take(), getCurScope());
1844 Actions
.ActOnBlockError(CaretLoc
, getCurScope());
1845 return move(Result
);