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