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