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