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