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