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