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