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