clang  7.0.0svn
ParseExpr.cpp
Go to the documentation of this file.
1 //===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// Provides the Expression parsing implementation.
12 ///
13 /// Expressions in C99 basically consist of a bunch of binary operators with
14 /// unary operators and other random stuff at the leaves.
15 ///
16 /// In the C99 grammar, these unary operators bind tightest and are represented
17 /// as the 'cast-expression' production. Everything else is either a binary
18 /// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
19 /// handled by ParseCastExpression, the higher level pieces are handled by
20 /// ParseBinaryExpression.
21 ///
22 //===----------------------------------------------------------------------===//
23 
24 #include "clang/Parse/Parser.h"
25 #include "clang/AST/ASTContext.h"
28 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/Scope.h"
32 #include "llvm/ADT/SmallVector.h"
33 using namespace clang;
34 
35 /// Simple precedence-based parser for binary/ternary operators.
36 ///
37 /// Note: we diverge from the C99 grammar when parsing the assignment-expression
38 /// production. C99 specifies that the LHS of an assignment operator should be
39 /// parsed as a unary-expression, but consistency dictates that it be a
40 /// conditional-expession. In practice, the important thing here is that the
41 /// LHS of an assignment has to be an l-value, which productions between
42 /// unary-expression and conditional-expression don't produce. Because we want
43 /// consistency, we parse the LHS as a conditional-expression, then check for
44 /// l-value-ness in semantic analysis stages.
45 ///
46 /// \verbatim
47 /// pm-expression: [C++ 5.5]
48 /// cast-expression
49 /// pm-expression '.*' cast-expression
50 /// pm-expression '->*' cast-expression
51 ///
52 /// multiplicative-expression: [C99 6.5.5]
53 /// Note: in C++, apply pm-expression instead of cast-expression
54 /// cast-expression
55 /// multiplicative-expression '*' cast-expression
56 /// multiplicative-expression '/' cast-expression
57 /// multiplicative-expression '%' cast-expression
58 ///
59 /// additive-expression: [C99 6.5.6]
60 /// multiplicative-expression
61 /// additive-expression '+' multiplicative-expression
62 /// additive-expression '-' multiplicative-expression
63 ///
64 /// shift-expression: [C99 6.5.7]
65 /// additive-expression
66 /// shift-expression '<<' additive-expression
67 /// shift-expression '>>' additive-expression
68 ///
69 /// compare-expression: [C++20 expr.spaceship]
70 /// shift-expression
71 /// compare-expression '<=>' shift-expression
72 ///
73 /// relational-expression: [C99 6.5.8]
74 /// compare-expression
75 /// relational-expression '<' compare-expression
76 /// relational-expression '>' compare-expression
77 /// relational-expression '<=' compare-expression
78 /// relational-expression '>=' compare-expression
79 ///
80 /// equality-expression: [C99 6.5.9]
81 /// relational-expression
82 /// equality-expression '==' relational-expression
83 /// equality-expression '!=' relational-expression
84 ///
85 /// AND-expression: [C99 6.5.10]
86 /// equality-expression
87 /// AND-expression '&' equality-expression
88 ///
89 /// exclusive-OR-expression: [C99 6.5.11]
90 /// AND-expression
91 /// exclusive-OR-expression '^' AND-expression
92 ///
93 /// inclusive-OR-expression: [C99 6.5.12]
94 /// exclusive-OR-expression
95 /// inclusive-OR-expression '|' exclusive-OR-expression
96 ///
97 /// logical-AND-expression: [C99 6.5.13]
98 /// inclusive-OR-expression
99 /// logical-AND-expression '&&' inclusive-OR-expression
100 ///
101 /// logical-OR-expression: [C99 6.5.14]
102 /// logical-AND-expression
103 /// logical-OR-expression '||' logical-AND-expression
104 ///
105 /// conditional-expression: [C99 6.5.15]
106 /// logical-OR-expression
107 /// logical-OR-expression '?' expression ':' conditional-expression
108 /// [GNU] logical-OR-expression '?' ':' conditional-expression
109 /// [C++] the third operand is an assignment-expression
110 ///
111 /// assignment-expression: [C99 6.5.16]
112 /// conditional-expression
113 /// unary-expression assignment-operator assignment-expression
114 /// [C++] throw-expression [C++ 15]
115 ///
116 /// assignment-operator: one of
117 /// = *= /= %= += -= <<= >>= &= ^= |=
118 ///
119 /// expression: [C99 6.5.17]
120 /// assignment-expression ...[opt]
121 /// expression ',' assignment-expression ...[opt]
122 /// \endverbatim
124  ExprResult LHS(ParseAssignmentExpression(isTypeCast));
125  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
126 }
127 
128 /// This routine is called when the '@' is seen and consumed.
129 /// Current token is an Identifier and is not a 'try'. This
130 /// routine is necessary to disambiguate \@try-statement from,
131 /// for example, \@encode-expression.
132 ///
134 Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
135  ExprResult LHS(ParseObjCAtExpression(AtLoc));
136  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
137 }
138 
139 /// This routine is called when a leading '__extension__' is seen and
140 /// consumed. This is necessary because the token gets consumed in the
141 /// process of disambiguating between an expression and a declaration.
143 Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
144  ExprResult LHS(true);
145  {
146  // Silence extension warnings in the sub-expression
147  ExtensionRAIIObject O(Diags);
148 
149  LHS = ParseCastExpression(false);
150  }
151 
152  if (!LHS.isInvalid())
153  LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
154  LHS.get());
155 
156  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
157 }
158 
159 /// Parse an expr that doesn't include (top-level) commas.
161  if (Tok.is(tok::code_completion)) {
163  cutOffParsing();
164  return ExprError();
165  }
166 
167  if (Tok.is(tok::kw_throw))
168  return ParseThrowExpression();
169  if (Tok.is(tok::kw_co_yield))
170  return ParseCoyieldExpression();
171 
172  ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false,
173  /*isAddressOfOperand=*/false,
174  isTypeCast);
175  return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
176 }
177 
178 /// Parse an assignment expression where part of an Objective-C message
179 /// send has already been parsed.
180 ///
181 /// In this case \p LBracLoc indicates the location of the '[' of the message
182 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
183 /// the receiver of the message.
184 ///
185 /// Since this handles full assignment-expression's, it handles postfix
186 /// expressions and other binary operators for these expressions as well.
188 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
189  SourceLocation SuperLoc,
190  ParsedType ReceiverType,
191  Expr *ReceiverExpr) {
192  ExprResult R
193  = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
194  ReceiverType, ReceiverExpr);
195  R = ParsePostfixExpressionSuffix(R);
196  return ParseRHSOfBinaryExpression(R, prec::Assignment);
197 }
198 
201  assert(Actions.ExprEvalContexts.back().Context ==
203  "Call this function only if your ExpressionEvaluationContext is "
204  "already ConstantEvaluated");
205  ExprResult LHS(ParseCastExpression(false, false, isTypeCast));
206  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
207  return Actions.ActOnConstantExpression(Res);
208 }
209 
211  // C++03 [basic.def.odr]p2:
212  // An expression is potentially evaluated unless it appears where an
213  // integral constant expression is required (see 5.19) [...].
214  // C++98 and C++11 have no such rule, but this is only a defect in C++98.
215  EnterExpressionEvaluationContext ConstantEvaluated(
217  return ParseConstantExpressionInExprEvalContext(isTypeCast);
218 }
219 
220 /// Parse a constraint-expression.
221 ///
222 /// \verbatim
223 /// constraint-expression: [Concepts TS temp.constr.decl p1]
224 /// logical-or-expression
225 /// \endverbatim
227  // FIXME: this may erroneously consume a function-body as the braced
228  // initializer list of a compound literal
229  //
230  // FIXME: this may erroneously consume a parenthesized rvalue reference
231  // declarator as a parenthesized address-of-label expression
232  ExprResult LHS(ParseCastExpression(/*isUnaryExpression=*/false));
233  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
234 
235  return Res;
236 }
237 
238 bool Parser::isNotExpressionStart() {
239  tok::TokenKind K = Tok.getKind();
240  if (K == tok::l_brace || K == tok::r_brace ||
241  K == tok::kw_for || K == tok::kw_while ||
242  K == tok::kw_if || K == tok::kw_else ||
243  K == tok::kw_goto || K == tok::kw_try)
244  return true;
245  // If this is a decl-specifier, we can't be at the start of an expression.
246  return isKnownToBeDeclarationSpecifier();
247 }
248 
249 /// We've parsed something that could plausibly be intended to be a template
250 /// name (\p LHS) followed by a '<' token, and the following code can't possibly
251 /// be an expression. Determine if this is likely to be a template-id and if so,
252 /// diagnose it.
253 bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
254  TentativeParsingAction TPA(*this);
255  // FIXME: We could look at the token sequence in a lot more detail here.
256  if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater,
258  TPA.Commit();
259 
261  ParseGreaterThanInTemplateList(Greater, true, false);
263  Less, Greater);
264  return true;
265  }
266 
267  // There's no matching '>' token, this probably isn't supposed to be
268  // interpreted as a template-id. Parse it as an (ill-formed) comparison.
269  TPA.Revert();
270  return false;
271 }
272 
273 bool Parser::isFoldOperator(prec::Level Level) const {
274  return Level > prec::Unknown && Level != prec::Conditional &&
275  Level != prec::Spaceship;
276 }
277 
278 bool Parser::isFoldOperator(tok::TokenKind Kind) const {
279  return isFoldOperator(getBinOpPrecedence(Kind, GreaterThanIsOperator, true));
280 }
281 
282 /// Parse a binary expression that starts with \p LHS and has a
283 /// precedence of at least \p MinPrec.
285 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
286  prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
287  GreaterThanIsOperator,
288  getLangOpts().CPlusPlus11);
290 
291  while (1) {
292  // If this token has a lower precedence than we are allowed to parse (e.g.
293  // because we are called recursively, or because the token is not a binop),
294  // then we are done!
295  if (NextTokPrec < MinPrec)
296  return LHS;
297 
298  // Consume the operator, saving the operator token for error reporting.
299  Token OpToken = Tok;
300  ConsumeToken();
301 
302  if (OpToken.is(tok::caretcaret)) {
303  return ExprError(Diag(Tok, diag::err_opencl_logical_exclusive_or));
304  }
305  // Bail out when encountering a comma followed by a token which can't
306  // possibly be the start of an expression. For instance:
307  // int f() { return 1, }
308  // We can't do this before consuming the comma, because
309  // isNotExpressionStart() looks at the token stream.
310  if (OpToken.is(tok::comma) && isNotExpressionStart()) {
311  PP.EnterToken(Tok);
312  Tok = OpToken;
313  return LHS;
314  }
315 
316  // If a '<' token is followed by a type that can be a template argument and
317  // cannot be an expression, then this is ill-formed, but might be intended
318  // to be a template-id.
319  if (OpToken.is(tok::less) && Actions.mightBeIntendedToBeTemplateName(LHS) &&
320  (isKnownToBeDeclarationSpecifier() ||
321  Tok.isOneOf(tok::greater, tok::greatergreater,
322  tok::greatergreatergreater)) &&
323  diagnoseUnknownTemplateId(LHS, OpToken.getLocation()))
324  return ExprError();
325 
326  // If the next token is an ellipsis, then this is a fold-expression. Leave
327  // it alone so we can handle it in the paren expression.
328  if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
329  // FIXME: We can't check this via lookahead before we consume the token
330  // because that tickles a lexer bug.
331  PP.EnterToken(Tok);
332  Tok = OpToken;
333  return LHS;
334  }
335 
336  // Special case handling for the ternary operator.
337  ExprResult TernaryMiddle(true);
338  if (NextTokPrec == prec::Conditional) {
339  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
340  // Parse a braced-init-list here for error recovery purposes.
341  SourceLocation BraceLoc = Tok.getLocation();
342  TernaryMiddle = ParseBraceInitializer();
343  if (!TernaryMiddle.isInvalid()) {
344  Diag(BraceLoc, diag::err_init_list_bin_op)
345  << /*RHS*/ 1 << PP.getSpelling(OpToken)
346  << Actions.getExprRange(TernaryMiddle.get());
347  TernaryMiddle = ExprError();
348  }
349  } else if (Tok.isNot(tok::colon)) {
350  // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
352 
353  // Handle this production specially:
354  // logical-OR-expression '?' expression ':' conditional-expression
355  // In particular, the RHS of the '?' is 'expression', not
356  // 'logical-OR-expression' as we might expect.
357  TernaryMiddle = ParseExpression();
358  } else {
359  // Special case handling of "X ? Y : Z" where Y is empty:
360  // logical-OR-expression '?' ':' conditional-expression [GNU]
361  TernaryMiddle = nullptr;
362  Diag(Tok, diag::ext_gnu_conditional_expr);
363  }
364 
365  if (TernaryMiddle.isInvalid()) {
366  Actions.CorrectDelayedTyposInExpr(LHS);
367  LHS = ExprError();
368  TernaryMiddle = nullptr;
369  }
370 
371  if (!TryConsumeToken(tok::colon, ColonLoc)) {
372  // Otherwise, we're missing a ':'. Assume that this was a typo that
373  // the user forgot. If we're not in a macro expansion, we can suggest
374  // a fixit hint. If there were two spaces before the current token,
375  // suggest inserting the colon in between them, otherwise insert ": ".
376  SourceLocation FILoc = Tok.getLocation();
377  const char *FIText = ": ";
378  const SourceManager &SM = PP.getSourceManager();
379  if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
380  assert(FILoc.isFileID());
381  bool IsInvalid = false;
382  const char *SourcePtr =
383  SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
384  if (!IsInvalid && *SourcePtr == ' ') {
385  SourcePtr =
386  SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
387  if (!IsInvalid && *SourcePtr == ' ') {
388  FILoc = FILoc.getLocWithOffset(-1);
389  FIText = ":";
390  }
391  }
392  }
393 
394  Diag(Tok, diag::err_expected)
395  << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
396  Diag(OpToken, diag::note_matching) << tok::question;
397  ColonLoc = Tok.getLocation();
398  }
399  }
400 
401  // Code completion for the right-hand side of an assignment expression
402  // goes through a special hook that takes the left-hand side into account.
403  if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
404  Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
405  cutOffParsing();
406  return ExprError();
407  }
408 
409  // Parse another leaf here for the RHS of the operator.
410  // ParseCastExpression works here because all RHS expressions in C have it
411  // as a prefix, at least. However, in C++, an assignment-expression could
412  // be a throw-expression, which is not a valid cast-expression.
413  // Therefore we need some special-casing here.
414  // Also note that the third operand of the conditional operator is
415  // an assignment-expression in C++, and in C++11, we can have a
416  // braced-init-list on the RHS of an assignment. For better diagnostics,
417  // parse as if we were allowed braced-init-lists everywhere, and check that
418  // they only appear on the RHS of assignments later.
419  ExprResult RHS;
420  bool RHSIsInitList = false;
421  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
422  RHS = ParseBraceInitializer();
423  RHSIsInitList = true;
424  } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
426  else
427  RHS = ParseCastExpression(false);
428 
429  if (RHS.isInvalid()) {
430  // FIXME: Errors generated by the delayed typo correction should be
431  // printed before errors from parsing the RHS, not after.
432  Actions.CorrectDelayedTyposInExpr(LHS);
433  if (TernaryMiddle.isUsable())
434  TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
435  LHS = ExprError();
436  }
437 
438  // Remember the precedence of this operator and get the precedence of the
439  // operator immediately to the right of the RHS.
440  prec::Level ThisPrec = NextTokPrec;
441  NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
442  getLangOpts().CPlusPlus11);
443 
444  // Assignment and conditional expressions are right-associative.
445  bool isRightAssoc = ThisPrec == prec::Conditional ||
446  ThisPrec == prec::Assignment;
447 
448  // Get the precedence of the operator to the right of the RHS. If it binds
449  // more tightly with RHS than we do, evaluate it completely first.
450  if (ThisPrec < NextTokPrec ||
451  (ThisPrec == NextTokPrec && isRightAssoc)) {
452  if (!RHS.isInvalid() && RHSIsInitList) {
453  Diag(Tok, diag::err_init_list_bin_op)
454  << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
455  RHS = ExprError();
456  }
457  // If this is left-associative, only parse things on the RHS that bind
458  // more tightly than the current operator. If it is left-associative, it
459  // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
460  // A=(B=(C=D)), where each paren is a level of recursion here.
461  // The function takes ownership of the RHS.
462  RHS = ParseRHSOfBinaryExpression(RHS,
463  static_cast<prec::Level>(ThisPrec + !isRightAssoc));
464  RHSIsInitList = false;
465 
466  if (RHS.isInvalid()) {
467  // FIXME: Errors generated by the delayed typo correction should be
468  // printed before errors from ParseRHSOfBinaryExpression, not after.
469  Actions.CorrectDelayedTyposInExpr(LHS);
470  if (TernaryMiddle.isUsable())
471  TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
472  LHS = ExprError();
473  }
474 
475  NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
476  getLangOpts().CPlusPlus11);
477  }
478 
479  if (!RHS.isInvalid() && RHSIsInitList) {
480  if (ThisPrec == prec::Assignment) {
481  Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
482  << Actions.getExprRange(RHS.get());
483  } else if (ColonLoc.isValid()) {
484  Diag(ColonLoc, diag::err_init_list_bin_op)
485  << /*RHS*/1 << ":"
486  << Actions.getExprRange(RHS.get());
487  LHS = ExprError();
488  } else {
489  Diag(OpToken, diag::err_init_list_bin_op)
490  << /*RHS*/1 << PP.getSpelling(OpToken)
491  << Actions.getExprRange(RHS.get());
492  LHS = ExprError();
493  }
494  }
495 
496  ExprResult OrigLHS = LHS;
497  if (!LHS.isInvalid()) {
498  // Combine the LHS and RHS into the LHS (e.g. build AST).
499  if (TernaryMiddle.isInvalid()) {
500  // If we're using '>>' as an operator within a template
501  // argument list (in C++98), suggest the addition of
502  // parentheses so that the code remains well-formed in C++0x.
503  if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
504  SuggestParentheses(OpToken.getLocation(),
505  diag::warn_cxx11_right_shift_in_template_arg,
506  SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
507  Actions.getExprRange(RHS.get()).getEnd()));
508 
509  LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
510  OpToken.getKind(), LHS.get(), RHS.get());
511 
512  } else {
513  LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
514  LHS.get(), TernaryMiddle.get(),
515  RHS.get());
516  }
517  // In this case, ActOnBinOp or ActOnConditionalOp performed the
518  // CorrectDelayedTyposInExpr check.
519  if (!getLangOpts().CPlusPlus)
520  continue;
521  }
522 
523  // Ensure potential typos aren't left undiagnosed.
524  if (LHS.isInvalid()) {
525  Actions.CorrectDelayedTyposInExpr(OrigLHS);
526  Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
527  Actions.CorrectDelayedTyposInExpr(RHS);
528  }
529  }
530 }
531 
532 /// Parse a cast-expression, or, if \p isUnaryExpression is true,
533 /// parse a unary-expression.
534 ///
535 /// \p isAddressOfOperand exists because an id-expression that is the
536 /// operand of address-of gets special treatment due to member pointers.
537 ///
538 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
539  bool isAddressOfOperand,
540  TypeCastState isTypeCast,
541  bool isVectorLiteral) {
542  bool NotCastExpr;
543  ExprResult Res = ParseCastExpression(isUnaryExpression,
544  isAddressOfOperand,
545  NotCastExpr,
546  isTypeCast,
547  isVectorLiteral);
548  if (NotCastExpr)
549  Diag(Tok, diag::err_expected_expression);
550  return Res;
551 }
552 
553 namespace {
554 class CastExpressionIdValidator : public CorrectionCandidateCallback {
555  public:
556  CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
557  : NextToken(Next), AllowNonTypes(AllowNonTypes) {
558  WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
559  }
560 
561  bool ValidateCandidate(const TypoCorrection &candidate) override {
562  NamedDecl *ND = candidate.getCorrectionDecl();
563  if (!ND)
564  return candidate.isKeyword();
565 
566  if (isa<TypeDecl>(ND))
567  return WantTypeSpecifiers;
568 
569  if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
570  return false;
571 
572  if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
573  return true;
574 
575  for (auto *C : candidate) {
576  NamedDecl *ND = C->getUnderlyingDecl();
577  if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
578  return true;
579  }
580  return false;
581  }
582 
583  private:
585  bool AllowNonTypes;
586 };
587 }
588 
589 /// Parse a cast-expression, or, if \pisUnaryExpression is true, parse
590 /// a unary-expression.
591 ///
592 /// \p isAddressOfOperand exists because an id-expression that is the operand
593 /// of address-of gets special treatment due to member pointers. NotCastExpr
594 /// is set to true if the token is not the start of a cast-expression, and no
595 /// diagnostic is emitted in this case and no tokens are consumed.
596 ///
597 /// \verbatim
598 /// cast-expression: [C99 6.5.4]
599 /// unary-expression
600 /// '(' type-name ')' cast-expression
601 ///
602 /// unary-expression: [C99 6.5.3]
603 /// postfix-expression
604 /// '++' unary-expression
605 /// '--' unary-expression
606 /// [Coro] 'co_await' cast-expression
607 /// unary-operator cast-expression
608 /// 'sizeof' unary-expression
609 /// 'sizeof' '(' type-name ')'
610 /// [C++11] 'sizeof' '...' '(' identifier ')'
611 /// [GNU] '__alignof' unary-expression
612 /// [GNU] '__alignof' '(' type-name ')'
613 /// [C11] '_Alignof' '(' type-name ')'
614 /// [C++11] 'alignof' '(' type-id ')'
615 /// [GNU] '&&' identifier
616 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
617 /// [C++] new-expression
618 /// [C++] delete-expression
619 ///
620 /// unary-operator: one of
621 /// '&' '*' '+' '-' '~' '!'
622 /// [GNU] '__extension__' '__real' '__imag'
623 ///
624 /// primary-expression: [C99 6.5.1]
625 /// [C99] identifier
626 /// [C++] id-expression
627 /// constant
628 /// string-literal
629 /// [C++] boolean-literal [C++ 2.13.5]
630 /// [C++11] 'nullptr' [C++11 2.14.7]
631 /// [C++11] user-defined-literal
632 /// '(' expression ')'
633 /// [C11] generic-selection
634 /// '__func__' [C99 6.4.2.2]
635 /// [GNU] '__FUNCTION__'
636 /// [MS] '__FUNCDNAME__'
637 /// [MS] 'L__FUNCTION__'
638 /// [GNU] '__PRETTY_FUNCTION__'
639 /// [GNU] '(' compound-statement ')'
640 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
641 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
642 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
643 /// assign-expr ')'
644 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
645 /// [GNU] '__null'
646 /// [OBJC] '[' objc-message-expr ']'
647 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
648 /// [OBJC] '\@protocol' '(' identifier ')'
649 /// [OBJC] '\@encode' '(' type-name ')'
650 /// [OBJC] objc-string-literal
651 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
652 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
653 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
654 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
655 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
656 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
657 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
658 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
659 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
660 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
661 /// [C++] 'this' [C++ 9.3.2]
662 /// [G++] unary-type-trait '(' type-id ')'
663 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
664 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
665 /// [clang] '^' block-literal
666 ///
667 /// constant: [C99 6.4.4]
668 /// integer-constant
669 /// floating-constant
670 /// enumeration-constant -> identifier
671 /// character-constant
672 ///
673 /// id-expression: [C++ 5.1]
674 /// unqualified-id
675 /// qualified-id
676 ///
677 /// unqualified-id: [C++ 5.1]
678 /// identifier
679 /// operator-function-id
680 /// conversion-function-id
681 /// '~' class-name
682 /// template-id
683 ///
684 /// new-expression: [C++ 5.3.4]
685 /// '::'[opt] 'new' new-placement[opt] new-type-id
686 /// new-initializer[opt]
687 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
688 /// new-initializer[opt]
689 ///
690 /// delete-expression: [C++ 5.3.5]
691 /// '::'[opt] 'delete' cast-expression
692 /// '::'[opt] 'delete' '[' ']' cast-expression
693 ///
694 /// [GNU/Embarcadero] unary-type-trait:
695 /// '__is_arithmetic'
696 /// '__is_floating_point'
697 /// '__is_integral'
698 /// '__is_lvalue_expr'
699 /// '__is_rvalue_expr'
700 /// '__is_complete_type'
701 /// '__is_void'
702 /// '__is_array'
703 /// '__is_function'
704 /// '__is_reference'
705 /// '__is_lvalue_reference'
706 /// '__is_rvalue_reference'
707 /// '__is_fundamental'
708 /// '__is_object'
709 /// '__is_scalar'
710 /// '__is_compound'
711 /// '__is_pointer'
712 /// '__is_member_object_pointer'
713 /// '__is_member_function_pointer'
714 /// '__is_member_pointer'
715 /// '__is_const'
716 /// '__is_volatile'
717 /// '__is_trivial'
718 /// '__is_standard_layout'
719 /// '__is_signed'
720 /// '__is_unsigned'
721 ///
722 /// [GNU] unary-type-trait:
723 /// '__has_nothrow_assign'
724 /// '__has_nothrow_copy'
725 /// '__has_nothrow_constructor'
726 /// '__has_trivial_assign' [TODO]
727 /// '__has_trivial_copy' [TODO]
728 /// '__has_trivial_constructor'
729 /// '__has_trivial_destructor'
730 /// '__has_virtual_destructor'
731 /// '__is_abstract' [TODO]
732 /// '__is_class'
733 /// '__is_empty' [TODO]
734 /// '__is_enum'
735 /// '__is_final'
736 /// '__is_pod'
737 /// '__is_polymorphic'
738 /// '__is_sealed' [MS]
739 /// '__is_trivial'
740 /// '__is_union'
741 /// '__has_unique_object_representations'
742 ///
743 /// [Clang] unary-type-trait:
744 /// '__is_aggregate'
745 /// '__trivially_copyable'
746 ///
747 /// binary-type-trait:
748 /// [GNU] '__is_base_of'
749 /// [MS] '__is_convertible_to'
750 /// '__is_convertible'
751 /// '__is_same'
752 ///
753 /// [Embarcadero] array-type-trait:
754 /// '__array_rank'
755 /// '__array_extent'
756 ///
757 /// [Embarcadero] expression-trait:
758 /// '__is_lvalue_expr'
759 /// '__is_rvalue_expr'
760 /// \endverbatim
761 ///
762 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
763  bool isAddressOfOperand,
764  bool &NotCastExpr,
765  TypeCastState isTypeCast,
766  bool isVectorLiteral) {
767  ExprResult Res;
768  tok::TokenKind SavedKind = Tok.getKind();
769  NotCastExpr = false;
770 
771  // This handles all of cast-expression, unary-expression, postfix-expression,
772  // and primary-expression. We handle them together like this for efficiency
773  // and to simplify handling of an expression starting with a '(' token: which
774  // may be one of a parenthesized expression, cast-expression, compound literal
775  // expression, or statement expression.
776  //
777  // If the parsed tokens consist of a primary-expression, the cases below
778  // break out of the switch; at the end we call ParsePostfixExpressionSuffix
779  // to handle the postfix expression suffixes. Cases that cannot be followed
780  // by postfix exprs should return without invoking
781  // ParsePostfixExpressionSuffix.
782  switch (SavedKind) {
783  case tok::l_paren: {
784  // If this expression is limited to being a unary-expression, the parent can
785  // not start a cast expression.
786  ParenParseOption ParenExprType =
787  (isUnaryExpression && !getLangOpts().CPlusPlus) ? CompoundLiteral
788  : CastExpr;
789  ParsedType CastTy;
790  SourceLocation RParenLoc;
791  Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
792  isTypeCast == IsTypeCast, CastTy, RParenLoc);
793 
794  if (isVectorLiteral)
795  return Res;
796 
797  switch (ParenExprType) {
798  case SimpleExpr: break; // Nothing else to do.
799  case CompoundStmt: break; // Nothing else to do.
800  case CompoundLiteral:
801  // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
802  // postfix-expression exist, parse them now.
803  break;
804  case CastExpr:
805  // We have parsed the cast-expression and no postfix-expr pieces are
806  // following.
807  return Res;
808  }
809 
810  break;
811  }
812 
813  // primary-expression
814  case tok::numeric_constant:
815  // constant: integer-constant
816  // constant: floating-constant
817 
818  Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
819  ConsumeToken();
820  break;
821 
822  case tok::kw_true:
823  case tok::kw_false:
824  Res = ParseCXXBoolLiteral();
825  break;
826 
827  case tok::kw___objc_yes:
828  case tok::kw___objc_no:
829  return ParseObjCBoolLiteral();
830 
831  case tok::kw_nullptr:
832  Diag(Tok, diag::warn_cxx98_compat_nullptr);
833  return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
834 
835  case tok::annot_primary_expr:
836  assert(Res.get() == nullptr && "Stray primary-expression annotation?");
837  Res = getExprAnnotation(Tok);
838  ConsumeAnnotationToken();
839  break;
840 
841  case tok::kw___super:
842  case tok::kw_decltype:
843  // Annotate the token and tail recurse.
845  return ExprError();
846  assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
847  return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
848 
849  case tok::identifier: { // primary-expression: identifier
850  // unqualified-id: identifier
851  // constant: enumeration-constant
852  // Turn a potentially qualified name into a annot_typename or
853  // annot_cxxscope if it would be valid. This handles things like x::y, etc.
854  if (getLangOpts().CPlusPlus) {
855  // Avoid the unnecessary parse-time lookup in the common case
856  // where the syntax forbids a type.
857  const Token &Next = NextToken();
858 
859  // If this identifier was reverted from a token ID, and the next token
860  // is a parenthesis, this is likely to be a use of a type trait. Check
861  // those tokens.
862  if (Next.is(tok::l_paren) &&
863  Tok.is(tok::identifier) &&
864  Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
865  IdentifierInfo *II = Tok.getIdentifierInfo();
866  // Build up the mapping of revertible type traits, for future use.
867  if (RevertibleTypeTraits.empty()) {
868 #define RTT_JOIN(X,Y) X##Y
869 #define REVERTIBLE_TYPE_TRAIT(Name) \
870  RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
871  = RTT_JOIN(tok::kw_,Name)
872 
873  REVERTIBLE_TYPE_TRAIT(__is_abstract);
874  REVERTIBLE_TYPE_TRAIT(__is_aggregate);
875  REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
876  REVERTIBLE_TYPE_TRAIT(__is_array);
877  REVERTIBLE_TYPE_TRAIT(__is_assignable);
878  REVERTIBLE_TYPE_TRAIT(__is_base_of);
879  REVERTIBLE_TYPE_TRAIT(__is_class);
880  REVERTIBLE_TYPE_TRAIT(__is_complete_type);
881  REVERTIBLE_TYPE_TRAIT(__is_compound);
882  REVERTIBLE_TYPE_TRAIT(__is_const);
883  REVERTIBLE_TYPE_TRAIT(__is_constructible);
884  REVERTIBLE_TYPE_TRAIT(__is_convertible);
885  REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
886  REVERTIBLE_TYPE_TRAIT(__is_destructible);
887  REVERTIBLE_TYPE_TRAIT(__is_empty);
888  REVERTIBLE_TYPE_TRAIT(__is_enum);
889  REVERTIBLE_TYPE_TRAIT(__is_floating_point);
890  REVERTIBLE_TYPE_TRAIT(__is_final);
891  REVERTIBLE_TYPE_TRAIT(__is_function);
892  REVERTIBLE_TYPE_TRAIT(__is_fundamental);
893  REVERTIBLE_TYPE_TRAIT(__is_integral);
894  REVERTIBLE_TYPE_TRAIT(__is_interface_class);
895  REVERTIBLE_TYPE_TRAIT(__is_literal);
896  REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
897  REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
898  REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
899  REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
900  REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
901  REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
902  REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
903  REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
904  REVERTIBLE_TYPE_TRAIT(__is_object);
905  REVERTIBLE_TYPE_TRAIT(__is_pod);
906  REVERTIBLE_TYPE_TRAIT(__is_pointer);
907  REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
908  REVERTIBLE_TYPE_TRAIT(__is_reference);
909  REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
910  REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
911  REVERTIBLE_TYPE_TRAIT(__is_same);
912  REVERTIBLE_TYPE_TRAIT(__is_scalar);
913  REVERTIBLE_TYPE_TRAIT(__is_sealed);
914  REVERTIBLE_TYPE_TRAIT(__is_signed);
915  REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
916  REVERTIBLE_TYPE_TRAIT(__is_trivial);
917  REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
918  REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
919  REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
920  REVERTIBLE_TYPE_TRAIT(__is_union);
921  REVERTIBLE_TYPE_TRAIT(__is_unsigned);
922  REVERTIBLE_TYPE_TRAIT(__is_void);
923  REVERTIBLE_TYPE_TRAIT(__is_volatile);
924 #undef REVERTIBLE_TYPE_TRAIT
925 #undef RTT_JOIN
926  }
927 
928  // If we find that this is in fact the name of a type trait,
929  // update the token kind in place and parse again to treat it as
930  // the appropriate kind of type trait.
931  llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
932  = RevertibleTypeTraits.find(II);
933  if (Known != RevertibleTypeTraits.end()) {
934  Tok.setKind(Known->second);
935  return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
936  NotCastExpr, isTypeCast);
937  }
938  }
939 
940  if ((!ColonIsSacred && Next.is(tok::colon)) ||
941  Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
942  tok::l_brace)) {
943  // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
945  return ExprError();
946  if (!Tok.is(tok::identifier))
947  return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
948  }
949  }
950 
951  // Consume the identifier so that we can see if it is followed by a '(' or
952  // '.'.
953  IdentifierInfo &II = *Tok.getIdentifierInfo();
954  SourceLocation ILoc = ConsumeToken();
955 
956  // Support 'Class.property' and 'super.property' notation.
957  if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
958  (Actions.getTypeName(II, ILoc, getCurScope()) ||
959  // Allow the base to be 'super' if in an objc-method.
960  (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
961  ConsumeToken();
962 
963  if (Tok.is(tok::code_completion) && &II != Ident_super) {
964  Actions.CodeCompleteObjCClassPropertyRefExpr(
965  getCurScope(), II, ILoc, ExprStatementTokLoc == ILoc);
966  cutOffParsing();
967  return ExprError();
968  }
969  // Allow either an identifier or the keyword 'class' (in C++).
970  if (Tok.isNot(tok::identifier) &&
971  !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
972  Diag(Tok, diag::err_expected_property_name);
973  return ExprError();
974  }
975  IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
976  SourceLocation PropertyLoc = ConsumeToken();
977 
978  Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
979  ILoc, PropertyLoc);
980  break;
981  }
982 
983  // In an Objective-C method, if we have "super" followed by an identifier,
984  // the token sequence is ill-formed. However, if there's a ':' or ']' after
985  // that identifier, this is probably a message send with a missing open
986  // bracket. Treat it as such.
987  if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
988  getCurScope()->isInObjcMethodScope() &&
989  ((Tok.is(tok::identifier) &&
990  (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
991  Tok.is(tok::code_completion))) {
992  Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, nullptr,
993  nullptr);
994  break;
995  }
996 
997  // If we have an Objective-C class name followed by an identifier
998  // and either ':' or ']', this is an Objective-C class message
999  // send that's missing the opening '['. Recovery
1000  // appropriately. Also take this path if we're performing code
1001  // completion after an Objective-C class name.
1002  if (getLangOpts().ObjC1 &&
1003  ((Tok.is(tok::identifier) && !InMessageExpression) ||
1004  Tok.is(tok::code_completion))) {
1005  const Token& Next = NextToken();
1006  if (Tok.is(tok::code_completion) ||
1007  Next.is(tok::colon) || Next.is(tok::r_square))
1008  if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
1009  if (Typ.get()->isObjCObjectOrInterfaceType()) {
1010  // Fake up a Declarator to use with ActOnTypeName.
1011  DeclSpec DS(AttrFactory);
1012  DS.SetRangeStart(ILoc);
1013  DS.SetRangeEnd(ILoc);
1014  const char *PrevSpec = nullptr;
1015  unsigned DiagID;
1016  DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
1017  Actions.getASTContext().getPrintingPolicy());
1018 
1019  Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1020  TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
1021  DeclaratorInfo);
1022  if (Ty.isInvalid())
1023  break;
1024 
1025  Res = ParseObjCMessageExpressionBody(SourceLocation(),
1026  SourceLocation(),
1027  Ty.get(), nullptr);
1028  break;
1029  }
1030  }
1031 
1032  // Make sure to pass down the right value for isAddressOfOperand.
1033  if (isAddressOfOperand && isPostfixExpressionSuffixStart())
1034  isAddressOfOperand = false;
1035 
1036  // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
1037  // need to know whether or not this identifier is a function designator or
1038  // not.
1039  UnqualifiedId Name;
1040  CXXScopeSpec ScopeSpec;
1041  SourceLocation TemplateKWLoc;
1043  auto Validator = llvm::make_unique<CastExpressionIdValidator>(
1044  Tok, isTypeCast != NotTypeCast, isTypeCast != IsTypeCast);
1045  Validator->IsAddressOfOperand = isAddressOfOperand;
1046  if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
1047  Validator->WantExpressionKeywords = false;
1048  Validator->WantRemainingKeywords = false;
1049  } else {
1050  Validator->WantRemainingKeywords = Tok.isNot(tok::r_paren);
1051  }
1052  Name.setIdentifier(&II, ILoc);
1053  Res = Actions.ActOnIdExpression(
1054  getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
1055  isAddressOfOperand, std::move(Validator),
1056  /*IsInlineAsmIdentifier=*/false,
1057  Tok.is(tok::r_paren) ? nullptr : &Replacement);
1058  if (!Res.isInvalid() && !Res.get()) {
1059  UnconsumeToken(Replacement);
1060  return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1061  NotCastExpr, isTypeCast);
1062  }
1063  break;
1064  }
1065  case tok::char_constant: // constant: character-constant
1066  case tok::wide_char_constant:
1067  case tok::utf8_char_constant:
1068  case tok::utf16_char_constant:
1069  case tok::utf32_char_constant:
1070  Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
1071  ConsumeToken();
1072  break;
1073  case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
1074  case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
1075  case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
1076  case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
1077  case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
1078  case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
1079  Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
1080  ConsumeToken();
1081  break;
1082  case tok::string_literal: // primary-expression: string-literal
1083  case tok::wide_string_literal:
1084  case tok::utf8_string_literal:
1085  case tok::utf16_string_literal:
1086  case tok::utf32_string_literal:
1087  Res = ParseStringLiteralExpression(true);
1088  break;
1089  case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
1090  Res = ParseGenericSelectionExpression();
1091  break;
1092  case tok::kw___builtin_available:
1093  return ParseAvailabilityCheckExpr(Tok.getLocation());
1094  case tok::kw___builtin_va_arg:
1095  case tok::kw___builtin_offsetof:
1096  case tok::kw___builtin_choose_expr:
1097  case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1098  case tok::kw___builtin_convertvector:
1099  return ParseBuiltinPrimaryExpression();
1100  case tok::kw___null:
1101  return Actions.ActOnGNUNullExpr(ConsumeToken());
1102 
1103  case tok::plusplus: // unary-expression: '++' unary-expression [C99]
1104  case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
1105  // C++ [expr.unary] has:
1106  // unary-expression:
1107  // ++ cast-expression
1108  // -- cast-expression
1109  Token SavedTok = Tok;
1110  ConsumeToken();
1111  // One special case is implicitly handled here: if the preceding tokens are
1112  // an ambiguous cast expression, such as "(T())++", then we recurse to
1113  // determine whether the '++' is prefix or postfix.
1114  Res = ParseCastExpression(!getLangOpts().CPlusPlus,
1115  /*isAddressOfOperand*/false, NotCastExpr,
1116  NotTypeCast);
1117  if (NotCastExpr) {
1118  // If we return with NotCastExpr = true, we must not consume any tokens,
1119  // so put the token back where we found it.
1120  assert(Res.isInvalid());
1121  UnconsumeToken(SavedTok);
1122  return ExprError();
1123  }
1124  if (!Res.isInvalid())
1125  Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
1126  SavedKind, Res.get());
1127  return Res;
1128  }
1129  case tok::amp: { // unary-expression: '&' cast-expression
1130  // Special treatment because of member pointers
1131  SourceLocation SavedLoc = ConsumeToken();
1132  Res = ParseCastExpression(false, true);
1133  if (!Res.isInvalid())
1134  Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1135  return Res;
1136  }
1137 
1138  case tok::star: // unary-expression: '*' cast-expression
1139  case tok::plus: // unary-expression: '+' cast-expression
1140  case tok::minus: // unary-expression: '-' cast-expression
1141  case tok::tilde: // unary-expression: '~' cast-expression
1142  case tok::exclaim: // unary-expression: '!' cast-expression
1143  case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
1144  case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
1145  SourceLocation SavedLoc = ConsumeToken();
1146  Res = ParseCastExpression(false);
1147  if (!Res.isInvalid())
1148  Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1149  return Res;
1150  }
1151 
1152  case tok::kw_co_await: { // unary-expression: 'co_await' cast-expression
1153  SourceLocation CoawaitLoc = ConsumeToken();
1154  Res = ParseCastExpression(false);
1155  if (!Res.isInvalid())
1156  Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1157  return Res;
1158  }
1159 
1160  case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1161  // __extension__ silences extension warnings in the subexpression.
1162  ExtensionRAIIObject O(Diags); // Use RAII to do this.
1163  SourceLocation SavedLoc = ConsumeToken();
1164  Res = ParseCastExpression(false);
1165  if (!Res.isInvalid())
1166  Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1167  return Res;
1168  }
1169  case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
1170  if (!getLangOpts().C11)
1171  Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
1172  // fallthrough
1173  case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
1174  case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
1175  // unary-expression: '__alignof' '(' type-name ')'
1176  case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
1177  // unary-expression: 'sizeof' '(' type-name ')'
1178  case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
1179  // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1180  case tok::kw___builtin_omp_required_simd_align:
1181  return ParseUnaryExprOrTypeTraitExpression();
1182  case tok::ampamp: { // unary-expression: '&&' identifier
1183  SourceLocation AmpAmpLoc = ConsumeToken();
1184  if (Tok.isNot(tok::identifier))
1185  return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1186 
1187  if (getCurScope()->getFnParent() == nullptr)
1188  return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1189 
1190  Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1191  LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1192  Tok.getLocation());
1193  Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1194  ConsumeToken();
1195  return Res;
1196  }
1197  case tok::kw_const_cast:
1198  case tok::kw_dynamic_cast:
1199  case tok::kw_reinterpret_cast:
1200  case tok::kw_static_cast:
1201  Res = ParseCXXCasts();
1202  break;
1203  case tok::kw_typeid:
1204  Res = ParseCXXTypeid();
1205  break;
1206  case tok::kw___uuidof:
1207  Res = ParseCXXUuidof();
1208  break;
1209  case tok::kw_this:
1210  Res = ParseCXXThis();
1211  break;
1212 
1213  case tok::annot_typename:
1214  if (isStartOfObjCClassMessageMissingOpenBracket()) {
1216 
1217  // Fake up a Declarator to use with ActOnTypeName.
1218  DeclSpec DS(AttrFactory);
1219  DS.SetRangeStart(Tok.getLocation());
1220  DS.SetRangeEnd(Tok.getLastLoc());
1221 
1222  const char *PrevSpec = nullptr;
1223  unsigned DiagID;
1224  DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1225  PrevSpec, DiagID, Type,
1226  Actions.getASTContext().getPrintingPolicy());
1227 
1228  Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1229  TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1230  if (Ty.isInvalid())
1231  break;
1232 
1233  ConsumeAnnotationToken();
1234  Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1235  Ty.get(), nullptr);
1236  break;
1237  }
1238  // Fall through
1239 
1240  case tok::annot_decltype:
1241  case tok::kw_char:
1242  case tok::kw_wchar_t:
1243  case tok::kw_char8_t:
1244  case tok::kw_char16_t:
1245  case tok::kw_char32_t:
1246  case tok::kw_bool:
1247  case tok::kw_short:
1248  case tok::kw_int:
1249  case tok::kw_long:
1250  case tok::kw___int64:
1251  case tok::kw___int128:
1252  case tok::kw_signed:
1253  case tok::kw_unsigned:
1254  case tok::kw_half:
1255  case tok::kw_float:
1256  case tok::kw_double:
1257  case tok::kw__Float16:
1258  case tok::kw___float128:
1259  case tok::kw_void:
1260  case tok::kw_typename:
1261  case tok::kw_typeof:
1262  case tok::kw___vector:
1263 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1264 #include "clang/Basic/OpenCLImageTypes.def"
1265  {
1266  if (!getLangOpts().CPlusPlus) {
1267  Diag(Tok, diag::err_expected_expression);
1268  return ExprError();
1269  }
1270 
1271  if (SavedKind == tok::kw_typename) {
1272  // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1273  // typename-specifier braced-init-list
1275  return ExprError();
1276 
1277  if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1278  // We are trying to parse a simple-type-specifier but might not get such
1279  // a token after error recovery.
1280  return ExprError();
1281  }
1282 
1283  // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1284  // simple-type-specifier braced-init-list
1285  //
1286  DeclSpec DS(AttrFactory);
1287 
1288  ParseCXXSimpleTypeSpecifier(DS);
1289  if (Tok.isNot(tok::l_paren) &&
1290  (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1291  return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1292  << DS.getSourceRange());
1293 
1294  if (Tok.is(tok::l_brace))
1295  Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1296 
1297  Res = ParseCXXTypeConstructExpression(DS);
1298  break;
1299  }
1300 
1301  case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1302  // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1303  // (We can end up in this situation after tentative parsing.)
1305  return ExprError();
1306  if (!Tok.is(tok::annot_cxxscope))
1307  return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1308  NotCastExpr, isTypeCast);
1309 
1310  Token Next = NextToken();
1311  if (Next.is(tok::annot_template_id)) {
1312  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1313  if (TemplateId->Kind == TNK_Type_template) {
1314  // We have a qualified template-id that we know refers to a
1315  // type, translate it into a type and continue parsing as a
1316  // cast expression.
1317  CXXScopeSpec SS;
1318  ParseOptionalCXXScopeSpecifier(SS, nullptr,
1319  /*EnteringContext=*/false);
1320  AnnotateTemplateIdTokenAsType();
1321  return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1322  NotCastExpr, isTypeCast);
1323  }
1324  }
1325 
1326  // Parse as an id-expression.
1327  Res = ParseCXXIdExpression(isAddressOfOperand);
1328  break;
1329  }
1330 
1331  case tok::annot_template_id: { // [C++] template-id
1332  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1333  if (TemplateId->Kind == TNK_Type_template) {
1334  // We have a template-id that we know refers to a type,
1335  // translate it into a type and continue parsing as a cast
1336  // expression.
1337  AnnotateTemplateIdTokenAsType();
1338  return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1339  NotCastExpr, isTypeCast);
1340  }
1341 
1342  // Fall through to treat the template-id as an id-expression.
1343  LLVM_FALLTHROUGH;
1344  }
1345 
1346  case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1347  Res = ParseCXXIdExpression(isAddressOfOperand);
1348  break;
1349 
1350  case tok::coloncolon: {
1351  // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1352  // annotates the token, tail recurse.
1354  return ExprError();
1355  if (!Tok.is(tok::coloncolon))
1356  return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
1357 
1358  // ::new -> [C++] new-expression
1359  // ::delete -> [C++] delete-expression
1360  SourceLocation CCLoc = ConsumeToken();
1361  if (Tok.is(tok::kw_new))
1362  return ParseCXXNewExpression(true, CCLoc);
1363  if (Tok.is(tok::kw_delete))
1364  return ParseCXXDeleteExpression(true, CCLoc);
1365 
1366  // This is not a type name or scope specifier, it is an invalid expression.
1367  Diag(CCLoc, diag::err_expected_expression);
1368  return ExprError();
1369  }
1370 
1371  case tok::kw_new: // [C++] new-expression
1372  return ParseCXXNewExpression(false, Tok.getLocation());
1373 
1374  case tok::kw_delete: // [C++] delete-expression
1375  return ParseCXXDeleteExpression(false, Tok.getLocation());
1376 
1377  case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1378  Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1379  SourceLocation KeyLoc = ConsumeToken();
1380  BalancedDelimiterTracker T(*this, tok::l_paren);
1381 
1382  if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1383  return ExprError();
1384  // C++11 [expr.unary.noexcept]p1:
1385  // The noexcept operator determines whether the evaluation of its operand,
1386  // which is an unevaluated operand, can throw an exception.
1390 
1391  T.consumeClose();
1392 
1393  if (!Result.isInvalid())
1394  Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
1395  Result.get(), T.getCloseLocation());
1396  return Result;
1397  }
1398 
1399 #define TYPE_TRAIT(N,Spelling,K) \
1400  case tok::kw_##Spelling:
1401 #include "clang/Basic/TokenKinds.def"
1402  return ParseTypeTrait();
1403 
1404  case tok::kw___array_rank:
1405  case tok::kw___array_extent:
1406  return ParseArrayTypeTrait();
1407 
1408  case tok::kw___is_lvalue_expr:
1409  case tok::kw___is_rvalue_expr:
1410  return ParseExpressionTrait();
1411 
1412  case tok::at: {
1413  SourceLocation AtLoc = ConsumeToken();
1414  return ParseObjCAtExpression(AtLoc);
1415  }
1416  case tok::caret:
1417  Res = ParseBlockLiteralExpression();
1418  break;
1419  case tok::code_completion: {
1420  Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1421  cutOffParsing();
1422  return ExprError();
1423  }
1424  case tok::l_square:
1425  if (getLangOpts().CPlusPlus11) {
1426  if (getLangOpts().ObjC1) {
1427  // C++11 lambda expressions and Objective-C message sends both start with a
1428  // square bracket. There are three possibilities here:
1429  // we have a valid lambda expression, we have an invalid lambda
1430  // expression, or we have something that doesn't appear to be a lambda.
1431  // If we're in the last case, we fall back to ParseObjCMessageExpression.
1432  Res = TryParseLambdaExpression();
1433  if (!Res.isInvalid() && !Res.get())
1434  Res = ParseObjCMessageExpression();
1435  break;
1436  }
1437  Res = ParseLambdaExpression();
1438  break;
1439  }
1440  if (getLangOpts().ObjC1) {
1441  Res = ParseObjCMessageExpression();
1442  break;
1443  }
1444  // FALL THROUGH.
1445  default:
1446  NotCastExpr = true;
1447  return ExprError();
1448  }
1449 
1450  // Check to see whether Res is a function designator only. If it is and we
1451  // are compiling for OpenCL, we need to return an error as this implies
1452  // that the address of the function is being taken, which is illegal in CL.
1453 
1454  // These can be followed by postfix-expr pieces.
1455  Res = ParsePostfixExpressionSuffix(Res);
1456  if (getLangOpts().OpenCL)
1457  if (Expr *PostfixExpr = Res.get()) {
1458  QualType Ty = PostfixExpr->getType();
1459  if (!Ty.isNull() && Ty->isFunctionType()) {
1460  Diag(PostfixExpr->getExprLoc(),
1461  diag::err_opencl_taking_function_address_parser);
1462  return ExprError();
1463  }
1464  }
1465 
1466  return Res;
1467 }
1468 
1469 /// Once the leading part of a postfix-expression is parsed, this
1470 /// method parses any suffixes that apply.
1471 ///
1472 /// \verbatim
1473 /// postfix-expression: [C99 6.5.2]
1474 /// primary-expression
1475 /// postfix-expression '[' expression ']'
1476 /// postfix-expression '[' braced-init-list ']'
1477 /// postfix-expression '(' argument-expression-list[opt] ')'
1478 /// postfix-expression '.' identifier
1479 /// postfix-expression '->' identifier
1480 /// postfix-expression '++'
1481 /// postfix-expression '--'
1482 /// '(' type-name ')' '{' initializer-list '}'
1483 /// '(' type-name ')' '{' initializer-list ',' '}'
1484 ///
1485 /// argument-expression-list: [C99 6.5.2]
1486 /// argument-expression ...[opt]
1487 /// argument-expression-list ',' assignment-expression ...[opt]
1488 /// \endverbatim
1489 ExprResult
1490 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1491  // Now that the primary-expression piece of the postfix-expression has been
1492  // parsed, see if there are any postfix-expression pieces here.
1493  SourceLocation Loc;
1494  while (1) {
1495  switch (Tok.getKind()) {
1496  case tok::code_completion:
1497  if (InMessageExpression)
1498  return LHS;
1499 
1500  Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
1501  cutOffParsing();
1502  return ExprError();
1503 
1504  case tok::identifier:
1505  // If we see identifier: after an expression, and we're not already in a
1506  // message send, then this is probably a message send with a missing
1507  // opening bracket '['.
1508  if (getLangOpts().ObjC1 && !InMessageExpression &&
1509  (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1510  LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1511  nullptr, LHS.get());
1512  break;
1513  }
1514  // Fall through; this isn't a message send.
1515  LLVM_FALLTHROUGH;
1516 
1517  default: // Not a postfix-expression suffix.
1518  return LHS;
1519  case tok::l_square: { // postfix-expression: p-e '[' expression ']'
1520  // If we have a array postfix expression that starts on a new line and
1521  // Objective-C is enabled, it is highly likely that the user forgot a
1522  // semicolon after the base expression and that the array postfix-expr is
1523  // actually another message send. In this case, do some look-ahead to see
1524  // if the contents of the square brackets are obviously not a valid
1525  // expression and recover by pretending there is no suffix.
1526  if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
1527  isSimpleObjCMessageExpression())
1528  return LHS;
1529 
1530  // Reject array indices starting with a lambda-expression. '[[' is
1531  // reserved for attributes.
1532  if (CheckProhibitedCXX11Attribute()) {
1533  (void)Actions.CorrectDelayedTyposInExpr(LHS);
1534  return ExprError();
1535  }
1536 
1537  BalancedDelimiterTracker T(*this, tok::l_square);
1538  T.consumeOpen();
1539  Loc = T.getOpenLocation();
1540  ExprResult Idx, Length;
1542  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1543  Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1544  Idx = ParseBraceInitializer();
1545  } else if (getLangOpts().OpenMP) {
1546  ColonProtectionRAIIObject RAII(*this);
1547  // Parse [: or [ expr or [ expr :
1548  if (!Tok.is(tok::colon)) {
1549  // [ expr
1550  Idx = ParseExpression();
1551  }
1552  if (Tok.is(tok::colon)) {
1553  // Consume ':'
1554  ColonLoc = ConsumeToken();
1555  if (Tok.isNot(tok::r_square))
1556  Length = ParseExpression();
1557  }
1558  } else
1559  Idx = ParseExpression();
1560 
1561  SourceLocation RLoc = Tok.getLocation();
1562 
1563  ExprResult OrigLHS = LHS;
1564  if (!LHS.isInvalid() && !Idx.isInvalid() && !Length.isInvalid() &&
1565  Tok.is(tok::r_square)) {
1566  if (ColonLoc.isValid()) {
1567  LHS = Actions.ActOnOMPArraySectionExpr(LHS.get(), Loc, Idx.get(),
1568  ColonLoc, Length.get(), RLoc);
1569  } else {
1570  LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1571  Idx.get(), RLoc);
1572  }
1573  } else {
1574  LHS = ExprError();
1575  }
1576  if (LHS.isInvalid()) {
1577  (void)Actions.CorrectDelayedTyposInExpr(OrigLHS);
1578  (void)Actions.CorrectDelayedTyposInExpr(Idx);
1579  (void)Actions.CorrectDelayedTyposInExpr(Length);
1580  LHS = ExprError();
1581  Idx = ExprError();
1582  }
1583 
1584  // Match the ']'.
1585  T.consumeClose();
1586  break;
1587  }
1588 
1589  case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
1590  case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
1591  // '(' argument-expression-list[opt] ')'
1592  tok::TokenKind OpKind = Tok.getKind();
1593  InMessageExpressionRAIIObject InMessage(*this, false);
1594 
1595  Expr *ExecConfig = nullptr;
1596 
1597  BalancedDelimiterTracker PT(*this, tok::l_paren);
1598 
1599  if (OpKind == tok::lesslessless) {
1600  ExprVector ExecConfigExprs;
1601  CommaLocsTy ExecConfigCommaLocs;
1602  SourceLocation OpenLoc = ConsumeToken();
1603 
1604  if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1605  (void)Actions.CorrectDelayedTyposInExpr(LHS);
1606  LHS = ExprError();
1607  }
1608 
1609  SourceLocation CloseLoc;
1610  if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1611  } else if (LHS.isInvalid()) {
1612  SkipUntil(tok::greatergreatergreater, StopAtSemi);
1613  } else {
1614  // There was an error closing the brackets
1615  Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1616  Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1617  SkipUntil(tok::greatergreatergreater, StopAtSemi);
1618  LHS = ExprError();
1619  }
1620 
1621  if (!LHS.isInvalid()) {
1622  if (ExpectAndConsume(tok::l_paren))
1623  LHS = ExprError();
1624  else
1625  Loc = PrevTokLocation;
1626  }
1627 
1628  if (!LHS.isInvalid()) {
1629  ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1630  OpenLoc,
1631  ExecConfigExprs,
1632  CloseLoc);
1633  if (ECResult.isInvalid())
1634  LHS = ExprError();
1635  else
1636  ExecConfig = ECResult.get();
1637  }
1638  } else {
1639  PT.consumeOpen();
1640  Loc = PT.getOpenLocation();
1641  }
1642 
1643  ExprVector ArgExprs;
1644  CommaLocsTy CommaLocs;
1645 
1646  if (Tok.is(tok::code_completion)) {
1647  Actions.CodeCompleteCall(getCurScope(), LHS.get(), None);
1648  cutOffParsing();
1649  return ExprError();
1650  }
1651 
1652  if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1653  if (Tok.isNot(tok::r_paren)) {
1654  if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
1655  Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
1656  })) {
1657  (void)Actions.CorrectDelayedTyposInExpr(LHS);
1658  LHS = ExprError();
1659  } else if (LHS.isInvalid()) {
1660  for (auto &E : ArgExprs)
1661  Actions.CorrectDelayedTyposInExpr(E);
1662  }
1663  }
1664  }
1665 
1666  // Match the ')'.
1667  if (LHS.isInvalid()) {
1668  SkipUntil(tok::r_paren, StopAtSemi);
1669  } else if (Tok.isNot(tok::r_paren)) {
1670  bool HadDelayedTypo = false;
1671  if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
1672  HadDelayedTypo = true;
1673  for (auto &E : ArgExprs)
1674  if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
1675  HadDelayedTypo = true;
1676  // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
1677  // instead of PT.consumeClose() to avoid emitting extra diagnostics for
1678  // the unmatched l_paren.
1679  if (HadDelayedTypo)
1680  SkipUntil(tok::r_paren, StopAtSemi);
1681  else
1682  PT.consumeClose();
1683  LHS = ExprError();
1684  } else {
1685  assert((ArgExprs.size() == 0 ||
1686  ArgExprs.size()-1 == CommaLocs.size())&&
1687  "Unexpected number of commas!");
1688  LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc,
1689  ArgExprs, Tok.getLocation(),
1690  ExecConfig);
1691  PT.consumeClose();
1692  }
1693 
1694  break;
1695  }
1696  case tok::arrow:
1697  case tok::period: {
1698  // postfix-expression: p-e '->' template[opt] id-expression
1699  // postfix-expression: p-e '.' template[opt] id-expression
1700  tok::TokenKind OpKind = Tok.getKind();
1701  SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
1702 
1703  CXXScopeSpec SS;
1704  ParsedType ObjectType;
1705  bool MayBePseudoDestructor = false;
1706  Expr* OrigLHS = !LHS.isInvalid() ? LHS.get() : nullptr;
1707 
1708  if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
1709  Expr *Base = OrigLHS;
1710  const Type* BaseType = Base->getType().getTypePtrOrNull();
1711  if (BaseType && Tok.is(tok::l_paren) &&
1712  (BaseType->isFunctionType() ||
1713  BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
1714  Diag(OpLoc, diag::err_function_is_not_record)
1715  << OpKind << Base->getSourceRange()
1716  << FixItHint::CreateRemoval(OpLoc);
1717  return ParsePostfixExpressionSuffix(Base);
1718  }
1719 
1720  LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
1721  OpLoc, OpKind, ObjectType,
1722  MayBePseudoDestructor);
1723  if (LHS.isInvalid())
1724  break;
1725 
1726  ParseOptionalCXXScopeSpecifier(SS, ObjectType,
1727  /*EnteringContext=*/false,
1728  &MayBePseudoDestructor);
1729  if (SS.isNotEmpty())
1730  ObjectType = nullptr;
1731  }
1732 
1733  if (Tok.is(tok::code_completion)) {
1734  tok::TokenKind CorrectedOpKind =
1735  OpKind == tok::arrow ? tok::period : tok::arrow;
1736  ExprResult CorrectedLHS(/*IsInvalid=*/true);
1737  if (getLangOpts().CPlusPlus && OrigLHS) {
1738  const bool DiagsAreSuppressed = Diags.getSuppressAllDiagnostics();
1739  Diags.setSuppressAllDiagnostics(true);
1740  CorrectedLHS = Actions.ActOnStartCXXMemberReference(
1741  getCurScope(), OrigLHS, OpLoc, CorrectedOpKind, ObjectType,
1742  MayBePseudoDestructor);
1743  Diags.setSuppressAllDiagnostics(DiagsAreSuppressed);
1744  }
1745 
1746  Expr *Base = LHS.get();
1747  Expr *CorrectedBase = CorrectedLHS.get();
1748 
1749  // Code completion for a member access expression.
1750  Actions.CodeCompleteMemberReferenceExpr(
1751  getCurScope(), Base, CorrectedBase, OpLoc, OpKind == tok::arrow,
1752  Base && ExprStatementTokLoc == Base->getLocStart());
1753 
1754  cutOffParsing();
1755  return ExprError();
1756  }
1757 
1758  if (MayBePseudoDestructor && !LHS.isInvalid()) {
1759  LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
1760  ObjectType);
1761  break;
1762  }
1763 
1764  // Either the action has told us that this cannot be a
1765  // pseudo-destructor expression (based on the type of base
1766  // expression), or we didn't see a '~' in the right place. We
1767  // can still parse a destructor name here, but in that case it
1768  // names a real destructor.
1769  // Allow explicit constructor calls in Microsoft mode.
1770  // FIXME: Add support for explicit call of template constructor.
1771  SourceLocation TemplateKWLoc;
1772  UnqualifiedId Name;
1773  if (getLangOpts().ObjC2 && OpKind == tok::period &&
1774  Tok.is(tok::kw_class)) {
1775  // Objective-C++:
1776  // After a '.' in a member access expression, treat the keyword
1777  // 'class' as if it were an identifier.
1778  //
1779  // This hack allows property access to the 'class' method because it is
1780  // such a common method name. For other C++ keywords that are
1781  // Objective-C method names, one must use the message send syntax.
1782  IdentifierInfo *Id = Tok.getIdentifierInfo();
1783  SourceLocation Loc = ConsumeToken();
1784  Name.setIdentifier(Id, Loc);
1785  } else if (ParseUnqualifiedId(SS,
1786  /*EnteringContext=*/false,
1787  /*AllowDestructorName=*/true,
1788  /*AllowConstructorName=*/
1789  getLangOpts().MicrosoftExt,
1790  /*AllowDeductionGuide=*/false,
1791  ObjectType, &TemplateKWLoc, Name)) {
1792  (void)Actions.CorrectDelayedTyposInExpr(LHS);
1793  LHS = ExprError();
1794  }
1795 
1796  if (!LHS.isInvalid())
1797  LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
1798  OpKind, SS, TemplateKWLoc, Name,
1799  CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
1800  : nullptr);
1801  break;
1802  }
1803  case tok::plusplus: // postfix-expression: postfix-expression '++'
1804  case tok::minusminus: // postfix-expression: postfix-expression '--'
1805  if (!LHS.isInvalid()) {
1806  LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1807  Tok.getKind(), LHS.get());
1808  }
1809  ConsumeToken();
1810  break;
1811  }
1812  }
1813 }
1814 
1815 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1816 /// vec_step and we are at the start of an expression or a parenthesized
1817 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1818 /// expression (isCastExpr == false) or the type (isCastExpr == true).
1819 ///
1820 /// \verbatim
1821 /// unary-expression: [C99 6.5.3]
1822 /// 'sizeof' unary-expression
1823 /// 'sizeof' '(' type-name ')'
1824 /// [GNU] '__alignof' unary-expression
1825 /// [GNU] '__alignof' '(' type-name ')'
1826 /// [C11] '_Alignof' '(' type-name ')'
1827 /// [C++0x] 'alignof' '(' type-id ')'
1828 ///
1829 /// [GNU] typeof-specifier:
1830 /// typeof ( expressions )
1831 /// typeof ( type-name )
1832 /// [GNU/C++] typeof unary-expression
1833 ///
1834 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
1835 /// vec_step ( expressions )
1836 /// vec_step ( type-name )
1837 /// \endverbatim
1838 ExprResult
1839 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1840  bool &isCastExpr,
1841  ParsedType &CastTy,
1842  SourceRange &CastRange) {
1843 
1844  assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
1845  tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
1846  tok::kw___builtin_omp_required_simd_align) &&
1847  "Not a typeof/sizeof/alignof/vec_step expression!");
1848 
1849  ExprResult Operand;
1850 
1851  // If the operand doesn't start with an '(', it must be an expression.
1852  if (Tok.isNot(tok::l_paren)) {
1853  // If construct allows a form without parenthesis, user may forget to put
1854  // pathenthesis around type name.
1855  if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1856  tok::kw__Alignof)) {
1857  if (isTypeIdUnambiguously()) {
1858  DeclSpec DS(AttrFactory);
1859  ParseSpecifierQualifierList(DS);
1860  Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1861  ParseDeclarator(DeclaratorInfo);
1862 
1863  SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
1864  SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
1865  Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
1866  << OpTok.getName()
1867  << FixItHint::CreateInsertion(LParenLoc, "(")
1868  << FixItHint::CreateInsertion(RParenLoc, ")");
1869  isCastExpr = true;
1870  return ExprEmpty();
1871  }
1872  }
1873 
1874  isCastExpr = false;
1875  if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
1876  Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
1877  << tok::l_paren;
1878  return ExprError();
1879  }
1880 
1881  Operand = ParseCastExpression(true/*isUnaryExpression*/);
1882  } else {
1883  // If it starts with a '(', we know that it is either a parenthesized
1884  // type-name, or it is a unary-expression that starts with a compound
1885  // literal, or starts with a primary-expression that is a parenthesized
1886  // expression.
1887  ParenParseOption ExprType = CastExpr;
1888  SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1889 
1890  Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1891  false, CastTy, RParenLoc);
1892  CastRange = SourceRange(LParenLoc, RParenLoc);
1893 
1894  // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1895  // a type.
1896  if (ExprType == CastExpr) {
1897  isCastExpr = true;
1898  return ExprEmpty();
1899  }
1900 
1901  if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1902  // GNU typeof in C requires the expression to be parenthesized. Not so for
1903  // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1904  // the start of a unary-expression, but doesn't include any postfix
1905  // pieces. Parse these now if present.
1906  if (!Operand.isInvalid())
1907  Operand = ParsePostfixExpressionSuffix(Operand.get());
1908  }
1909  }
1910 
1911  // If we get here, the operand to the typeof/sizeof/alignof was an expression.
1912  isCastExpr = false;
1913  return Operand;
1914 }
1915 
1916 
1917 /// Parse a sizeof or alignof expression.
1918 ///
1919 /// \verbatim
1920 /// unary-expression: [C99 6.5.3]
1921 /// 'sizeof' unary-expression
1922 /// 'sizeof' '(' type-name ')'
1923 /// [C++11] 'sizeof' '...' '(' identifier ')'
1924 /// [GNU] '__alignof' unary-expression
1925 /// [GNU] '__alignof' '(' type-name ')'
1926 /// [C11] '_Alignof' '(' type-name ')'
1927 /// [C++11] 'alignof' '(' type-id ')'
1928 /// \endverbatim
1929 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1930  assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1931  tok::kw__Alignof, tok::kw_vec_step,
1932  tok::kw___builtin_omp_required_simd_align) &&
1933  "Not a sizeof/alignof/vec_step expression!");
1934  Token OpTok = Tok;
1935  ConsumeToken();
1936 
1937  // [C++11] 'sizeof' '...' '(' identifier ')'
1938  if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1939  SourceLocation EllipsisLoc = ConsumeToken();
1940  SourceLocation LParenLoc, RParenLoc;
1941  IdentifierInfo *Name = nullptr;
1942  SourceLocation NameLoc;
1943  if (Tok.is(tok::l_paren)) {
1944  BalancedDelimiterTracker T(*this, tok::l_paren);
1945  T.consumeOpen();
1946  LParenLoc = T.getOpenLocation();
1947  if (Tok.is(tok::identifier)) {
1948  Name = Tok.getIdentifierInfo();
1949  NameLoc = ConsumeToken();
1950  T.consumeClose();
1951  RParenLoc = T.getCloseLocation();
1952  if (RParenLoc.isInvalid())
1953  RParenLoc = PP.getLocForEndOfToken(NameLoc);
1954  } else {
1955  Diag(Tok, diag::err_expected_parameter_pack);
1956  SkipUntil(tok::r_paren, StopAtSemi);
1957  }
1958  } else if (Tok.is(tok::identifier)) {
1959  Name = Tok.getIdentifierInfo();
1960  NameLoc = ConsumeToken();
1961  LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1962  RParenLoc = PP.getLocForEndOfToken(NameLoc);
1963  Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1964  << Name
1965  << FixItHint::CreateInsertion(LParenLoc, "(")
1966  << FixItHint::CreateInsertion(RParenLoc, ")");
1967  } else {
1968  Diag(Tok, diag::err_sizeof_parameter_pack);
1969  }
1970 
1971  if (!Name)
1972  return ExprError();
1973 
1977 
1978  return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
1979  OpTok.getLocation(),
1980  *Name, NameLoc,
1981  RParenLoc);
1982  }
1983 
1984  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1985  Diag(OpTok, diag::warn_cxx98_compat_alignof);
1986 
1990 
1991  bool isCastExpr;
1992  ParsedType CastTy;
1993  SourceRange CastRange;
1994  ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
1995  isCastExpr,
1996  CastTy,
1997  CastRange);
1998 
1999  UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
2000  if (OpTok.isOneOf(tok::kw_alignof, tok::kw___alignof, tok::kw__Alignof))
2001  ExprKind = UETT_AlignOf;
2002  else if (OpTok.is(tok::kw_vec_step))
2003  ExprKind = UETT_VecStep;
2004  else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
2005  ExprKind = UETT_OpenMPRequiredSimdAlign;
2006 
2007  if (isCastExpr)
2008  return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2009  ExprKind,
2010  /*isType=*/true,
2011  CastTy.getAsOpaquePtr(),
2012  CastRange);
2013 
2014  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2015  Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
2016 
2017  // If we get here, the operand to the sizeof/alignof was an expression.
2018  if (!Operand.isInvalid())
2019  Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2020  ExprKind,
2021  /*isType=*/false,
2022  Operand.get(),
2023  CastRange);
2024  return Operand;
2025 }
2026 
2027 /// ParseBuiltinPrimaryExpression
2028 ///
2029 /// \verbatim
2030 /// primary-expression: [C99 6.5.1]
2031 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
2032 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
2033 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
2034 /// assign-expr ')'
2035 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
2036 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
2037 ///
2038 /// [GNU] offsetof-member-designator:
2039 /// [GNU] identifier
2040 /// [GNU] offsetof-member-designator '.' identifier
2041 /// [GNU] offsetof-member-designator '[' expression ']'
2042 /// \endverbatim
2043 ExprResult Parser::ParseBuiltinPrimaryExpression() {
2044  ExprResult Res;
2045  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
2046 
2047  tok::TokenKind T = Tok.getKind();
2048  SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
2049 
2050  // All of these start with an open paren.
2051  if (Tok.isNot(tok::l_paren))
2052  return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
2053  << tok::l_paren);
2054 
2055  BalancedDelimiterTracker PT(*this, tok::l_paren);
2056  PT.consumeOpen();
2057 
2058  // TODO: Build AST.
2059 
2060  switch (T) {
2061  default: llvm_unreachable("Not a builtin primary expression!");
2062  case tok::kw___builtin_va_arg: {
2064 
2065  if (ExpectAndConsume(tok::comma)) {
2066  SkipUntil(tok::r_paren, StopAtSemi);
2067  Expr = ExprError();
2068  }
2069 
2070  TypeResult Ty = ParseTypeName();
2071 
2072  if (Tok.isNot(tok::r_paren)) {
2073  Diag(Tok, diag::err_expected) << tok::r_paren;
2074  Expr = ExprError();
2075  }
2076 
2077  if (Expr.isInvalid() || Ty.isInvalid())
2078  Res = ExprError();
2079  else
2080  Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
2081  break;
2082  }
2083  case tok::kw___builtin_offsetof: {
2084  SourceLocation TypeLoc = Tok.getLocation();
2085  TypeResult Ty = ParseTypeName();
2086  if (Ty.isInvalid()) {
2087  SkipUntil(tok::r_paren, StopAtSemi);
2088  return ExprError();
2089  }
2090 
2091  if (ExpectAndConsume(tok::comma)) {
2092  SkipUntil(tok::r_paren, StopAtSemi);
2093  return ExprError();
2094  }
2095 
2096  // We must have at least one identifier here.
2097  if (Tok.isNot(tok::identifier)) {
2098  Diag(Tok, diag::err_expected) << tok::identifier;
2099  SkipUntil(tok::r_paren, StopAtSemi);
2100  return ExprError();
2101  }
2102 
2103  // Keep track of the various subcomponents we see.
2105 
2106  Comps.push_back(Sema::OffsetOfComponent());
2107  Comps.back().isBrackets = false;
2108  Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2109  Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2110 
2111  // FIXME: This loop leaks the index expressions on error.
2112  while (1) {
2113  if (Tok.is(tok::period)) {
2114  // offsetof-member-designator: offsetof-member-designator '.' identifier
2115  Comps.push_back(Sema::OffsetOfComponent());
2116  Comps.back().isBrackets = false;
2117  Comps.back().LocStart = ConsumeToken();
2118 
2119  if (Tok.isNot(tok::identifier)) {
2120  Diag(Tok, diag::err_expected) << tok::identifier;
2121  SkipUntil(tok::r_paren, StopAtSemi);
2122  return ExprError();
2123  }
2124  Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2125  Comps.back().LocEnd = ConsumeToken();
2126 
2127  } else if (Tok.is(tok::l_square)) {
2128  if (CheckProhibitedCXX11Attribute())
2129  return ExprError();
2130 
2131  // offsetof-member-designator: offsetof-member-design '[' expression ']'
2132  Comps.push_back(Sema::OffsetOfComponent());
2133  Comps.back().isBrackets = true;
2134  BalancedDelimiterTracker ST(*this, tok::l_square);
2135  ST.consumeOpen();
2136  Comps.back().LocStart = ST.getOpenLocation();
2137  Res = ParseExpression();
2138  if (Res.isInvalid()) {
2139  SkipUntil(tok::r_paren, StopAtSemi);
2140  return Res;
2141  }
2142  Comps.back().U.E = Res.get();
2143 
2144  ST.consumeClose();
2145  Comps.back().LocEnd = ST.getCloseLocation();
2146  } else {
2147  if (Tok.isNot(tok::r_paren)) {
2148  PT.consumeClose();
2149  Res = ExprError();
2150  } else if (Ty.isInvalid()) {
2151  Res = ExprError();
2152  } else {
2153  PT.consumeClose();
2154  Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2155  Ty.get(), Comps,
2156  PT.getCloseLocation());
2157  }
2158  break;
2159  }
2160  }
2161  break;
2162  }
2163  case tok::kw___builtin_choose_expr: {
2165  if (Cond.isInvalid()) {
2166  SkipUntil(tok::r_paren, StopAtSemi);
2167  return Cond;
2168  }
2169  if (ExpectAndConsume(tok::comma)) {
2170  SkipUntil(tok::r_paren, StopAtSemi);
2171  return ExprError();
2172  }
2173 
2175  if (Expr1.isInvalid()) {
2176  SkipUntil(tok::r_paren, StopAtSemi);
2177  return Expr1;
2178  }
2179  if (ExpectAndConsume(tok::comma)) {
2180  SkipUntil(tok::r_paren, StopAtSemi);
2181  return ExprError();
2182  }
2183 
2185  if (Expr2.isInvalid()) {
2186  SkipUntil(tok::r_paren, StopAtSemi);
2187  return Expr2;
2188  }
2189  if (Tok.isNot(tok::r_paren)) {
2190  Diag(Tok, diag::err_expected) << tok::r_paren;
2191  return ExprError();
2192  }
2193  Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2194  Expr2.get(), ConsumeParen());
2195  break;
2196  }
2197  case tok::kw___builtin_astype: {
2198  // The first argument is an expression to be converted, followed by a comma.
2200  if (Expr.isInvalid()) {
2201  SkipUntil(tok::r_paren, StopAtSemi);
2202  return ExprError();
2203  }
2204 
2205  if (ExpectAndConsume(tok::comma)) {
2206  SkipUntil(tok::r_paren, StopAtSemi);
2207  return ExprError();
2208  }
2209 
2210  // Second argument is the type to bitcast to.
2211  TypeResult DestTy = ParseTypeName();
2212  if (DestTy.isInvalid())
2213  return ExprError();
2214 
2215  // Attempt to consume the r-paren.
2216  if (Tok.isNot(tok::r_paren)) {
2217  Diag(Tok, diag::err_expected) << tok::r_paren;
2218  SkipUntil(tok::r_paren, StopAtSemi);
2219  return ExprError();
2220  }
2221 
2222  Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2223  ConsumeParen());
2224  break;
2225  }
2226  case tok::kw___builtin_convertvector: {
2227  // The first argument is an expression to be converted, followed by a comma.
2229  if (Expr.isInvalid()) {
2230  SkipUntil(tok::r_paren, StopAtSemi);
2231  return ExprError();
2232  }
2233 
2234  if (ExpectAndConsume(tok::comma)) {
2235  SkipUntil(tok::r_paren, StopAtSemi);
2236  return ExprError();
2237  }
2238 
2239  // Second argument is the type to bitcast to.
2240  TypeResult DestTy = ParseTypeName();
2241  if (DestTy.isInvalid())
2242  return ExprError();
2243 
2244  // Attempt to consume the r-paren.
2245  if (Tok.isNot(tok::r_paren)) {
2246  Diag(Tok, diag::err_expected) << tok::r_paren;
2247  SkipUntil(tok::r_paren, StopAtSemi);
2248  return ExprError();
2249  }
2250 
2251  Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2252  ConsumeParen());
2253  break;
2254  }
2255  }
2256 
2257  if (Res.isInvalid())
2258  return ExprError();
2259 
2260  // These can be followed by postfix-expr pieces because they are
2261  // primary-expressions.
2262  return ParsePostfixExpressionSuffix(Res.get());
2263 }
2264 
2265 /// ParseParenExpression - This parses the unit that starts with a '(' token,
2266 /// based on what is allowed by ExprType. The actual thing parsed is returned
2267 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2268 /// not the parsed cast-expression.
2269 ///
2270 /// \verbatim
2271 /// primary-expression: [C99 6.5.1]
2272 /// '(' expression ')'
2273 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
2274 /// postfix-expression: [C99 6.5.2]
2275 /// '(' type-name ')' '{' initializer-list '}'
2276 /// '(' type-name ')' '{' initializer-list ',' '}'
2277 /// cast-expression: [C99 6.5.4]
2278 /// '(' type-name ')' cast-expression
2279 /// [ARC] bridged-cast-expression
2280 /// [ARC] bridged-cast-expression:
2281 /// (__bridge type-name) cast-expression
2282 /// (__bridge_transfer type-name) cast-expression
2283 /// (__bridge_retained type-name) cast-expression
2284 /// fold-expression: [C++1z]
2285 /// '(' cast-expression fold-operator '...' ')'
2286 /// '(' '...' fold-operator cast-expression ')'
2287 /// '(' cast-expression fold-operator '...'
2288 /// fold-operator cast-expression ')'
2289 /// \endverbatim
2290 ExprResult
2291 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2292  bool isTypeCast, ParsedType &CastTy,
2293  SourceLocation &RParenLoc) {
2294  assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2295  ColonProtectionRAIIObject ColonProtection(*this, false);
2296  BalancedDelimiterTracker T(*this, tok::l_paren);
2297  if (T.consumeOpen())
2298  return ExprError();
2299  SourceLocation OpenLoc = T.getOpenLocation();
2300 
2301  ExprResult Result(true);
2302  bool isAmbiguousTypeId;
2303  CastTy = nullptr;
2304 
2305  if (Tok.is(tok::code_completion)) {
2306  Actions.CodeCompleteOrdinaryName(getCurScope(),
2307  ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
2309  cutOffParsing();
2310  return ExprError();
2311  }
2312 
2313  // Diagnose use of bridge casts in non-arc mode.
2314  bool BridgeCast = (getLangOpts().ObjC2 &&
2315  Tok.isOneOf(tok::kw___bridge,
2316  tok::kw___bridge_transfer,
2317  tok::kw___bridge_retained,
2318  tok::kw___bridge_retain));
2319  if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2320  if (!TryConsumeToken(tok::kw___bridge)) {
2321  StringRef BridgeCastName = Tok.getName();
2322  SourceLocation BridgeKeywordLoc = ConsumeToken();
2323  if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2324  Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2325  << BridgeCastName
2326  << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2327  }
2328  BridgeCast = false;
2329  }
2330 
2331  // None of these cases should fall through with an invalid Result
2332  // unless they've already reported an error.
2333  if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2334  Diag(Tok, diag::ext_gnu_statement_expr);
2335 
2336  if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2337  Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2338  } else {
2339  // Find the nearest non-record decl context. Variables declared in a
2340  // statement expression behave as if they were declared in the enclosing
2341  // function, block, or other code construct.
2342  DeclContext *CodeDC = Actions.CurContext;
2343  while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
2344  CodeDC = CodeDC->getParent();
2345  assert(CodeDC && !CodeDC->isFileContext() &&
2346  "statement expr not in code context");
2347  }
2348  Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2349 
2350  Actions.ActOnStartStmtExpr();
2351 
2352  StmtResult Stmt(ParseCompoundStatement(true));
2353  ExprType = CompoundStmt;
2354 
2355  // If the substmt parsed correctly, build the AST node.
2356  if (!Stmt.isInvalid()) {
2357  Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
2358  } else {
2359  Actions.ActOnStmtExprError();
2360  }
2361  }
2362  } else if (ExprType >= CompoundLiteral && BridgeCast) {
2363  tok::TokenKind tokenKind = Tok.getKind();
2364  SourceLocation BridgeKeywordLoc = ConsumeToken();
2365 
2366  // Parse an Objective-C ARC ownership cast expression.
2368  if (tokenKind == tok::kw___bridge)
2369  Kind = OBC_Bridge;
2370  else if (tokenKind == tok::kw___bridge_transfer)
2371  Kind = OBC_BridgeTransfer;
2372  else if (tokenKind == tok::kw___bridge_retained)
2373  Kind = OBC_BridgeRetained;
2374  else {
2375  // As a hopefully temporary workaround, allow __bridge_retain as
2376  // a synonym for __bridge_retained, but only in system headers.
2377  assert(tokenKind == tok::kw___bridge_retain);
2378  Kind = OBC_BridgeRetained;
2379  if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2380  Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2381  << FixItHint::CreateReplacement(BridgeKeywordLoc,
2382  "__bridge_retained");
2383  }
2384 
2385  TypeResult Ty = ParseTypeName();
2386  T.consumeClose();
2387  ColonProtection.restore();
2388  RParenLoc = T.getCloseLocation();
2389  ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
2390 
2391  if (Ty.isInvalid() || SubExpr.isInvalid())
2392  return ExprError();
2393 
2394  return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2395  BridgeKeywordLoc, Ty.get(),
2396  RParenLoc, SubExpr.get());
2397  } else if (ExprType >= CompoundLiteral &&
2398  isTypeIdInParens(isAmbiguousTypeId)) {
2399 
2400  // Otherwise, this is a compound literal expression or cast expression.
2401 
2402  // In C++, if the type-id is ambiguous we disambiguate based on context.
2403  // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2404  // in which case we should treat it as type-id.
2405  // if stopIfCastExpr is false, we need to determine the context past the
2406  // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2407  if (isAmbiguousTypeId && !stopIfCastExpr) {
2408  ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2409  ColonProtection);
2410  RParenLoc = T.getCloseLocation();
2411  return res;
2412  }
2413 
2414  // Parse the type declarator.
2415  DeclSpec DS(AttrFactory);
2416  ParseSpecifierQualifierList(DS);
2417  Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
2418  ParseDeclarator(DeclaratorInfo);
2419 
2420  // If our type is followed by an identifier and either ':' or ']', then
2421  // this is probably an Objective-C message send where the leading '[' is
2422  // missing. Recover as if that were the case.
2423  if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2424  !InMessageExpression && getLangOpts().ObjC1 &&
2425  (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2426  TypeResult Ty;
2427  {
2428  InMessageExpressionRAIIObject InMessage(*this, false);
2429  Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2430  }
2431  Result = ParseObjCMessageExpressionBody(SourceLocation(),
2432  SourceLocation(),
2433  Ty.get(), nullptr);
2434  } else {
2435  // Match the ')'.
2436  T.consumeClose();
2437  ColonProtection.restore();
2438  RParenLoc = T.getCloseLocation();
2439  if (Tok.is(tok::l_brace)) {
2440  ExprType = CompoundLiteral;
2441  TypeResult Ty;
2442  {
2443  InMessageExpressionRAIIObject InMessage(*this, false);
2444  Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2445  }
2446  return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2447  }
2448 
2449  if (Tok.is(tok::l_paren)) {
2450  // This could be OpenCL vector Literals
2451  if (getLangOpts().OpenCL)
2452  {
2453  TypeResult Ty;
2454  {
2455  InMessageExpressionRAIIObject InMessage(*this, false);
2456  Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2457  }
2458  if(Ty.isInvalid())
2459  {
2460  return ExprError();
2461  }
2462  QualType QT = Ty.get().get().getCanonicalType();
2463  if (QT->isVectorType())
2464  {
2465  // We parsed '(' vector-type-name ')' followed by '('
2466 
2467  // Parse the cast-expression that follows it next.
2468  // isVectorLiteral = true will make sure we don't parse any
2469  // Postfix expression yet
2470  Result = ParseCastExpression(/*isUnaryExpression=*/false,
2471  /*isAddressOfOperand=*/false,
2472  /*isTypeCast=*/IsTypeCast,
2473  /*isVectorLiteral=*/true);
2474 
2475  if (!Result.isInvalid()) {
2476  Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2477  DeclaratorInfo, CastTy,
2478  RParenLoc, Result.get());
2479  }
2480 
2481  // After we performed the cast we can check for postfix-expr pieces.
2482  if (!Result.isInvalid()) {
2483  Result = ParsePostfixExpressionSuffix(Result);
2484  }
2485 
2486  return Result;
2487  }
2488  }
2489  }
2490 
2491  if (ExprType == CastExpr) {
2492  // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2493 
2494  if (DeclaratorInfo.isInvalidType())
2495  return ExprError();
2496 
2497  // Note that this doesn't parse the subsequent cast-expression, it just
2498  // returns the parsed type to the callee.
2499  if (stopIfCastExpr) {
2500  TypeResult Ty;
2501  {
2502  InMessageExpressionRAIIObject InMessage(*this, false);
2503  Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2504  }
2505  CastTy = Ty.get();
2506  return ExprResult();
2507  }
2508 
2509  // Reject the cast of super idiom in ObjC.
2510  if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
2511  Tok.getIdentifierInfo() == Ident_super &&
2513  GetLookAheadToken(1).isNot(tok::period)) {
2514  Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2515  << SourceRange(OpenLoc, RParenLoc);
2516  return ExprError();
2517  }
2518 
2519  // Parse the cast-expression that follows it next.
2520  // TODO: For cast expression with CastTy.
2521  Result = ParseCastExpression(/*isUnaryExpression=*/false,
2522  /*isAddressOfOperand=*/false,
2523  /*isTypeCast=*/IsTypeCast);
2524  if (!Result.isInvalid()) {
2525  Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2526  DeclaratorInfo, CastTy,
2527  RParenLoc, Result.get());
2528  }
2529  return Result;
2530  }
2531 
2532  Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2533  return ExprError();
2534  }
2535  } else if (Tok.is(tok::ellipsis) &&
2536  isFoldOperator(NextToken().getKind())) {
2537  return ParseFoldExpression(ExprResult(), T);
2538  } else if (isTypeCast) {
2539  // Parse the expression-list.
2540  InMessageExpressionRAIIObject InMessage(*this, false);
2541 
2542  ExprVector ArgExprs;
2543  CommaLocsTy CommaLocs;
2544 
2545  if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
2546  // FIXME: If we ever support comma expressions as operands to
2547  // fold-expressions, we'll need to allow multiple ArgExprs here.
2548  if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
2549  NextToken().is(tok::ellipsis))
2550  return ParseFoldExpression(ArgExprs[0], T);
2551 
2552  ExprType = SimpleExpr;
2553  Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2554  ArgExprs);
2555  }
2556  } else {
2557  InMessageExpressionRAIIObject InMessage(*this, false);
2558 
2559  Result = ParseExpression(MaybeTypeCast);
2560  if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
2561  // Correct typos in non-C++ code earlier so that implicit-cast-like
2562  // expressions are parsed correctly.
2563  Result = Actions.CorrectDelayedTyposInExpr(Result);
2564  }
2565  ExprType = SimpleExpr;
2566 
2567  if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis))
2568  return ParseFoldExpression(Result, T);
2569 
2570  // Don't build a paren expression unless we actually match a ')'.
2571  if (!Result.isInvalid() && Tok.is(tok::r_paren))
2572  Result =
2573  Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
2574  }
2575 
2576  // Match the ')'.
2577  if (Result.isInvalid()) {
2578  SkipUntil(tok::r_paren, StopAtSemi);
2579  return ExprError();
2580  }
2581 
2582  T.consumeClose();
2583  RParenLoc = T.getCloseLocation();
2584  return Result;
2585 }
2586 
2587 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2588 /// and we are at the left brace.
2589 ///
2590 /// \verbatim
2591 /// postfix-expression: [C99 6.5.2]
2592 /// '(' type-name ')' '{' initializer-list '}'
2593 /// '(' type-name ')' '{' initializer-list ',' '}'
2594 /// \endverbatim
2595 ExprResult
2596 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2597  SourceLocation LParenLoc,
2598  SourceLocation RParenLoc) {
2599  assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2600  if (!getLangOpts().C99) // Compound literals don't exist in C90.
2601  Diag(LParenLoc, diag::ext_c99_compound_literal);
2602  ExprResult Result = ParseInitializer();
2603  if (!Result.isInvalid() && Ty)
2604  return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
2605  return Result;
2606 }
2607 
2608 /// ParseStringLiteralExpression - This handles the various token types that
2609 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
2610 /// translation phase #6].
2611 ///
2612 /// \verbatim
2613 /// primary-expression: [C99 6.5.1]
2614 /// string-literal
2615 /// \verbatim
2616 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2617  assert(isTokenStringLiteral() && "Not a string literal!");
2618 
2619  // String concat. Note that keywords like __func__ and __FUNCTION__ are not
2620  // considered to be strings for concatenation purposes.
2621  SmallVector<Token, 4> StringToks;
2622 
2623  do {
2624  StringToks.push_back(Tok);
2625  ConsumeStringToken();
2626  } while (isTokenStringLiteral());
2627 
2628  // Pass the set of string tokens, ready for concatenation, to the actions.
2629  return Actions.ActOnStringLiteral(StringToks,
2630  AllowUserDefinedLiteral ? getCurScope()
2631  : nullptr);
2632 }
2633 
2634 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
2635 /// [C11 6.5.1.1].
2636 ///
2637 /// \verbatim
2638 /// generic-selection:
2639 /// _Generic ( assignment-expression , generic-assoc-list )
2640 /// generic-assoc-list:
2641 /// generic-association
2642 /// generic-assoc-list , generic-association
2643 /// generic-association:
2644 /// type-name : assignment-expression
2645 /// default : assignment-expression
2646 /// \endverbatim
2647 ExprResult Parser::ParseGenericSelectionExpression() {
2648  assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2649  SourceLocation KeyLoc = ConsumeToken();
2650 
2651  if (!getLangOpts().C11)
2652  Diag(KeyLoc, diag::ext_c11_generic_selection);
2653 
2654  BalancedDelimiterTracker T(*this, tok::l_paren);
2655  if (T.expectAndConsume())
2656  return ExprError();
2657 
2658  ExprResult ControllingExpr;
2659  {
2660  // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2661  // not evaluated."
2664  ControllingExpr =
2665  Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
2666  if (ControllingExpr.isInvalid()) {
2667  SkipUntil(tok::r_paren, StopAtSemi);
2668  return ExprError();
2669  }
2670  }
2671 
2672  if (ExpectAndConsume(tok::comma)) {
2673  SkipUntil(tok::r_paren, StopAtSemi);
2674  return ExprError();
2675  }
2676 
2677  SourceLocation DefaultLoc;
2678  TypeVector Types;
2679  ExprVector Exprs;
2680  do {
2681  ParsedType Ty;
2682  if (Tok.is(tok::kw_default)) {
2683  // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2684  // generic association."
2685  if (!DefaultLoc.isInvalid()) {
2686  Diag(Tok, diag::err_duplicate_default_assoc);
2687  Diag(DefaultLoc, diag::note_previous_default_assoc);
2688  SkipUntil(tok::r_paren, StopAtSemi);
2689  return ExprError();
2690  }
2691  DefaultLoc = ConsumeToken();
2692  Ty = nullptr;
2693  } else {
2695  TypeResult TR = ParseTypeName();
2696  if (TR.isInvalid()) {
2697  SkipUntil(tok::r_paren, StopAtSemi);
2698  return ExprError();
2699  }
2700  Ty = TR.get();
2701  }
2702  Types.push_back(Ty);
2703 
2704  if (ExpectAndConsume(tok::colon)) {
2705  SkipUntil(tok::r_paren, StopAtSemi);
2706  return ExprError();
2707  }
2708 
2709  // FIXME: These expressions should be parsed in a potentially potentially
2710  // evaluated context.
2711  ExprResult ER(
2712  Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
2713  if (ER.isInvalid()) {
2714  SkipUntil(tok::r_paren, StopAtSemi);
2715  return ExprError();
2716  }
2717  Exprs.push_back(ER.get());
2718  } while (TryConsumeToken(tok::comma));
2719 
2720  T.consumeClose();
2721  if (T.getCloseLocation().isInvalid())
2722  return ExprError();
2723 
2724  return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
2725  T.getCloseLocation(),
2726  ControllingExpr.get(),
2727  Types, Exprs);
2728 }
2729 
2730 /// Parse A C++1z fold-expression after the opening paren and optional
2731 /// left-hand-side expression.
2732 ///
2733 /// \verbatim
2734 /// fold-expression:
2735 /// ( cast-expression fold-operator ... )
2736 /// ( ... fold-operator cast-expression )
2737 /// ( cast-expression fold-operator ... fold-operator cast-expression )
2738 ExprResult Parser::ParseFoldExpression(ExprResult LHS,
2740  if (LHS.isInvalid()) {
2741  T.skipToEnd();
2742  return true;
2743  }
2744 
2745  tok::TokenKind Kind = tok::unknown;
2746  SourceLocation FirstOpLoc;
2747  if (LHS.isUsable()) {
2748  Kind = Tok.getKind();
2749  assert(isFoldOperator(Kind) && "missing fold-operator");
2750  FirstOpLoc = ConsumeToken();
2751  }
2752 
2753  assert(Tok.is(tok::ellipsis) && "not a fold-expression");
2754  SourceLocation EllipsisLoc = ConsumeToken();
2755 
2756  ExprResult RHS;
2757  if (Tok.isNot(tok::r_paren)) {
2758  if (!isFoldOperator(Tok.getKind()))
2759  return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
2760 
2761  if (Kind != tok::unknown && Tok.getKind() != Kind)
2762  Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
2763  << SourceRange(FirstOpLoc);
2764  Kind = Tok.getKind();
2765  ConsumeToken();
2766 
2767  RHS = ParseExpression();
2768  if (RHS.isInvalid()) {
2769  T.skipToEnd();
2770  return true;
2771  }
2772  }
2773 
2774  Diag(EllipsisLoc, getLangOpts().CPlusPlus17
2775  ? diag::warn_cxx14_compat_fold_expression
2776  : diag::ext_fold_expression);
2777 
2778  T.consumeClose();
2779  return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind,
2780  EllipsisLoc, RHS.get(), T.getCloseLocation());
2781 }
2782 
2783 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
2784 ///
2785 /// \verbatim
2786 /// argument-expression-list:
2787 /// assignment-expression
2788 /// argument-expression-list , assignment-expression
2789 ///
2790 /// [C++] expression-list:
2791 /// [C++] assignment-expression
2792 /// [C++] expression-list , assignment-expression
2793 ///
2794 /// [C++0x] expression-list:
2795 /// [C++0x] initializer-list
2796 ///
2797 /// [C++0x] initializer-list
2798 /// [C++0x] initializer-clause ...[opt]
2799 /// [C++0x] initializer-list , initializer-clause ...[opt]
2800 ///
2801 /// [C++0x] initializer-clause:
2802 /// [C++0x] assignment-expression
2803 /// [C++0x] braced-init-list
2804 /// \endverbatim
2805 bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
2807  llvm::function_ref<void()> Completer) {
2808  bool SawError = false;
2809  while (1) {
2810  if (Tok.is(tok::code_completion)) {
2811  if (Completer)
2812  Completer();
2813  else
2814  Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
2815  cutOffParsing();
2816  return true;
2817  }
2818 
2819  ExprResult Expr;
2820  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2821  Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2822  Expr = ParseBraceInitializer();
2823  } else
2824  Expr = ParseAssignmentExpression();
2825 
2826  if (Tok.is(tok::ellipsis))
2827  Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
2828  if (Expr.isInvalid()) {
2829  SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
2830  SawError = true;
2831  } else {
2832  Exprs.push_back(Expr.get());
2833  }
2834 
2835  if (Tok.isNot(tok::comma))
2836  break;
2837  // Move to the next argument, remember where the comma was.
2838  CommaLocs.push_back(ConsumeToken());
2839  }
2840  if (SawError) {
2841  // Ensure typos get diagnosed when errors were encountered while parsing the
2842  // expression list.
2843  for (auto &E : Exprs) {
2844  ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
2845  if (Expr.isUsable()) E = Expr.get();
2846  }
2847  }
2848  return SawError;
2849 }
2850 
2851 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
2852 /// used for misc language extensions.
2853 ///
2854 /// \verbatim
2855 /// simple-expression-list:
2856 /// assignment-expression
2857 /// simple-expression-list , assignment-expression
2858 /// \endverbatim
2859 bool
2860 Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
2861  SmallVectorImpl<SourceLocation> &CommaLocs) {
2862  while (1) {
2864  if (Expr.isInvalid())
2865  return true;
2866 
2867  Exprs.push_back(Expr.get());
2868 
2869  if (Tok.isNot(tok::comma))
2870  return false;
2871 
2872  // Move to the next argument, remember where the comma was.
2873  CommaLocs.push_back(ConsumeToken());
2874  }
2875 }
2876 
2877 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
2878 ///
2879 /// \verbatim
2880 /// [clang] block-id:
2881 /// [clang] specifier-qualifier-list block-declarator
2882 /// \endverbatim
2883 void Parser::ParseBlockId(SourceLocation CaretLoc) {
2884  if (Tok.is(tok::code_completion)) {
2885  Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
2886  return cutOffParsing();
2887  }
2888 
2889  // Parse the specifier-qualifier-list piece.
2890  DeclSpec DS(AttrFactory);
2891  ParseSpecifierQualifierList(DS);
2892 
2893  // Parse the block-declarator.
2895  DeclaratorInfo.setFunctionDefinitionKind(FDK_Definition);
2896  ParseDeclarator(DeclaratorInfo);
2897 
2898  MaybeParseGNUAttributes(DeclaratorInfo);
2899 
2900  // Inform sema that we are starting a block.
2901  Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
2902 }
2903 
2904 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
2905 /// like ^(int x){ return x+1; }
2906 ///
2907 /// \verbatim
2908 /// block-literal:
2909 /// [clang] '^' block-args[opt] compound-statement
2910 /// [clang] '^' block-id compound-statement
2911 /// [clang] block-args:
2912 /// [clang] '(' parameter-list ')'
2913 /// \endverbatim
2914 ExprResult Parser::ParseBlockLiteralExpression() {
2915  assert(Tok.is(tok::caret) && "block literal starts with ^");
2916  SourceLocation CaretLoc = ConsumeToken();
2917 
2918  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2919  "block literal parsing");
2920 
2921  // Enter a scope to hold everything within the block. This includes the
2922  // argument decls, decls within the compound expression, etc. This also
2923  // allows determining whether a variable reference inside the block is
2924  // within or outside of the block.
2925  ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2927 
2928  // Inform sema that we are starting a block.
2929  Actions.ActOnBlockStart(CaretLoc, getCurScope());
2930 
2931  // Parse the return type if present.
2932  DeclSpec DS(AttrFactory);
2935  // FIXME: Since the return type isn't actually parsed, it can't be used to
2936  // fill ParamInfo with an initial valid range, so do it manually.
2937  ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2938 
2939  // If this block has arguments, parse them. There is no ambiguity here with
2940  // the expression case, because the expression case requires a parameter list.
2941  if (Tok.is(tok::l_paren)) {
2942  ParseParenDeclarator(ParamInfo);
2943  // Parse the pieces after the identifier as if we had "int(...)".
2944  // SetIdentifier sets the source range end, but in this case we're past
2945  // that location.
2946  SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2947  ParamInfo.SetIdentifier(nullptr, CaretLoc);
2948  ParamInfo.SetRangeEnd(Tmp);
2949  if (ParamInfo.isInvalidType()) {
2950  // If there was an error parsing the arguments, they may have
2951  // tried to use ^(x+y) which requires an argument list. Just
2952  // skip the whole block literal.
2953  Actions.ActOnBlockError(CaretLoc, getCurScope());
2954  return ExprError();
2955  }
2956 
2957  MaybeParseGNUAttributes(ParamInfo);
2958 
2959  // Inform sema that we are starting a block.
2960  Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2961  } else if (!Tok.is(tok::l_brace)) {
2962  ParseBlockId(CaretLoc);
2963  } else {
2964  // Otherwise, pretend we saw (void).
2965  ParsedAttributes attrs(AttrFactory);
2966  SourceLocation NoLoc;
2967  ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true,
2968  /*IsAmbiguous=*/false,
2969  /*RParenLoc=*/NoLoc,
2970  /*ArgInfo=*/nullptr,
2971  /*NumArgs=*/0,
2972  /*EllipsisLoc=*/NoLoc,
2973  /*RParenLoc=*/NoLoc,
2974  /*TypeQuals=*/0,
2975  /*RefQualifierIsLvalueRef=*/true,
2976  /*RefQualifierLoc=*/NoLoc,
2977  /*ConstQualifierLoc=*/NoLoc,
2978  /*VolatileQualifierLoc=*/NoLoc,
2979  /*RestrictQualifierLoc=*/NoLoc,
2980  /*MutableLoc=*/NoLoc,
2981  EST_None,
2982  /*ESpecRange=*/SourceRange(),
2983  /*Exceptions=*/nullptr,
2984  /*ExceptionRanges=*/nullptr,
2985  /*NumExceptions=*/0,
2986  /*NoexceptExpr=*/nullptr,
2987  /*ExceptionSpecTokens=*/nullptr,
2988  /*DeclsInPrototype=*/None,
2989  CaretLoc, CaretLoc,
2990  ParamInfo),
2991  attrs, CaretLoc);
2992 
2993  MaybeParseGNUAttributes(ParamInfo);
2994 
2995  // Inform sema that we are starting a block.
2996  Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2997  }
2998 
2999 
3000  ExprResult Result(true);
3001  if (!Tok.is(tok::l_brace)) {
3002  // Saw something like: ^expr
3003  Diag(Tok, diag::err_expected_expression);
3004  Actions.ActOnBlockError(CaretLoc, getCurScope());
3005  return ExprError();
3006  }
3007 
3008  StmtResult Stmt(ParseCompoundStatementBody());
3009  BlockScope.Exit();
3010  if (!Stmt.isInvalid())
3011  Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
3012  else
3013  Actions.ActOnBlockError(CaretLoc, getCurScope());
3014  return Result;
3015 }
3016 
3017 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
3018 ///
3019 /// '__objc_yes'
3020 /// '__objc_no'
3021 ExprResult Parser::ParseObjCBoolLiteral() {
3022  tok::TokenKind Kind = Tok.getKind();
3023  return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
3024 }
3025 
3026 /// Validate availability spec list, emitting diagnostics if necessary. Returns
3027 /// true if invalid.
3029  ArrayRef<AvailabilitySpec> AvailSpecs) {
3030  llvm::SmallSet<StringRef, 4> Platforms;
3031  bool HasOtherPlatformSpec = false;
3032  bool Valid = true;
3033  for (const auto &Spec : AvailSpecs) {
3034  if (Spec.isOtherPlatformSpec()) {
3035  if (HasOtherPlatformSpec) {
3036  P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
3037  Valid = false;
3038  }
3039 
3040  HasOtherPlatformSpec = true;
3041  continue;
3042  }
3043 
3044  bool Inserted = Platforms.insert(Spec.getPlatform()).second;
3045  if (!Inserted) {
3046  // Rule out multiple version specs referring to the same platform.
3047  // For example, we emit an error for:
3048  // @available(macos 10.10, macos 10.11, *)
3049  StringRef Platform = Spec.getPlatform();
3050  P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
3051  << Spec.getEndLoc() << Platform;
3052  Valid = false;
3053  }
3054  }
3055 
3056  if (!HasOtherPlatformSpec) {
3057  SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
3058  P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
3059  << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
3060  return true;
3061  }
3062 
3063  return !Valid;
3064 }
3065 
3066 /// Parse availability query specification.
3067 ///
3068 /// availability-spec:
3069 /// '*'
3070 /// identifier version-tuple
3071 Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
3072  if (Tok.is(tok::star)) {
3073  return AvailabilitySpec(ConsumeToken());
3074  } else {
3075  // Parse the platform name.
3076  if (Tok.is(tok::code_completion)) {
3077  Actions.CodeCompleteAvailabilityPlatformName();
3078  cutOffParsing();
3079  return None;
3080  }
3081  if (Tok.isNot(tok::identifier)) {
3082  Diag(Tok, diag::err_avail_query_expected_platform_name);
3083  return None;
3084  }
3085 
3086  IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
3087  SourceRange VersionRange;
3088  VersionTuple Version = ParseVersionTuple(VersionRange);
3089 
3090  if (Version.empty())
3091  return None;
3092 
3093  StringRef GivenPlatform = PlatformIdentifier->Ident->getName();
3094  StringRef Platform =
3095  AvailabilityAttr::canonicalizePlatformName(GivenPlatform);
3096 
3097  if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
3098  Diag(PlatformIdentifier->Loc,
3099  diag::err_avail_query_unrecognized_platform_name)
3100  << GivenPlatform;
3101  return None;
3102  }
3103 
3104  return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
3105  VersionRange.getEnd());
3106  }
3107 }
3108 
3109 ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
3110  assert(Tok.is(tok::kw___builtin_available) ||
3111  Tok.isObjCAtKeyword(tok::objc_available));
3112 
3113  // Eat the available or __builtin_available.
3114  ConsumeToken();
3115 
3116  BalancedDelimiterTracker Parens(*this, tok::l_paren);
3117  if (Parens.expectAndConsume())
3118  return ExprError();
3119 
3121  bool HasError = false;
3122  while (true) {
3123  Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
3124  if (!Spec)
3125  HasError = true;
3126  else
3127  AvailSpecs.push_back(*Spec);
3128 
3129  if (!TryConsumeToken(tok::comma))
3130  break;
3131  }
3132 
3133  if (HasError) {
3134  SkipUntil(tok::r_paren, StopAtSemi);
3135  return ExprError();
3136  }
3137 
3138  CheckAvailabilitySpecList(*this, AvailSpecs);
3139 
3140  if (Parens.consumeClose())
3141  return ExprError();
3142 
3143  return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
3144  Parens.getCloseLocation());
3145 }
Defines the clang::ASTContext interface.
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
no exception specification
ExprResult ParseExpression(TypeCastState isTypeCast=NotTypeCast)
Simple precedence-based parser for binary/ternary operators.
Definition: ParseExpr.cpp:123
ParseScope - Introduces a new scope for parsing.
Definition: Parser.h:854
A (possibly-)qualified type.
Definition: Type.h:655
Simple class containing the result of Sema::CorrectTypo.
SourceRange getExprRange(Expr *E) const
Definition: SemaExpr.cpp:410
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?: operation.
Definition: SemaExpr.cpp:7255
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
ObjCBridgeCastKind
The kind of bridging performed by the Objective-C bridge cast.
Stmt - This represents one statement.
Definition: Stmt.h:66
Bridging via __bridge, which does nothing but reinterpret the bits.
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:95
void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS)
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:6263
static bool CheckAvailabilitySpecList(Parser &P, ArrayRef< AvailabilitySpec > AvailSpecs)
Validate availability spec list, emitting diagnostics if necessary.
Definition: ParseExpr.cpp:3028
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
StringRef P
IdentifierInfo * Ident
Definition: AttributeList.h:84
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer...
The base class of the type hierarchy.
Definition: Type.h:1421
SourceLocation getCloseLocation() const
This indicates that the scope corresponds to a function, which means that labels are set here...
Definition: Scope.h:47
TemplateNameKind Kind
The kind of template that Template refers to.
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:56
TypeCastState
TypeCastState - State whether an expression is or may be a type cast.
Definition: Parser.h:1471
void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2135
RAII object that enters a new expression evaluation context.
Definition: Sema.h:10731
void EnterToken(const Token &Tok)
Enters a token in the token stream to be lexed next.
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1764
bool isInObjcMethodScope() const
isInObjcMethodScope - Return true if this scope is, or is contained in, an Objective-C method body...
Definition: Scope.h:353
#define REVERTIBLE_TYPE_TRAIT(Name)
ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and restores it when destroyed...
tok::TokenKind getKind() const
Definition: Token.h:90
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:948
SourceLocation Loc
Definition: AttributeList.h:83
Information about a template-id annotation token.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:56
void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext)
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:616
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:327
One of these records is kept for each identifier that is lexed.
ExprResult ExprEmpty()
Definition: Ownership.h:289
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition: DeclSpec.h:2147
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:97
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ...
void * getAsOpaquePtr() const
Definition: Ownership.h:91
Code completion occurs where only a type is permitted.
Definition: Sema.h:10228
void SetSourceRange(SourceRange R)
Definition: DeclSpec.h:1892
bool isInvalidType() const
Definition: DeclSpec.h:2436
This is a scope that corresponds to a block/closure object.
Definition: Scope.h:71
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:920
static ParsedType getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition: Parser.h:621
PtrTy get() const
Definition: Ownership.h:174
bool isNot(T Kind) const
Definition: FormatToken.h:320
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the &#39;spelling&#39; of the token at the given location; does not go up to the spelling location or ...
Code completion occurs within an expression.
Definition: Sema.h:10213
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, 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...
If a crash happens while one of these objects are live, the message is printed out along with the spe...
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2788
Bridging via __bridge_transfer, which transfers ownership of an Objective-C pointer into ARC...
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:507
const char * getName() const
Definition: Token.h:166
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:609
bool isOneOf(A K1, B K2) const
Definition: FormatToken.h:313
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:614
virtual bool ValidateCandidate(const TypoCorrection &candidate)
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:12377
Expr - This represents one expression.
Definition: Expr.h:106
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, unsigned TypeQuals, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation ConstQualifierLoc, SourceLocation VolatileQualifierLoc, SourceLocation RestrictQualifierLoc, 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())
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:152
int Id
Definition: ASTDiff.cpp:191
const FunctionProtoType * T
This file defines the classes used to store parsed information about declaration-specifiers and decla...
bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, ParsedType ObjectType, SourceLocation *TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:124
bool isFileContext() const
Definition: DeclBase.h:1407
This is a compound statement scope.
Definition: Scope.h:130
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7)...
QualType getType() const
Definition: Expr.h:128
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1341
bool isInvalid() const
Definition: Ownership.h:170
SourceLocation getEnd() const
SourceLocation getOpenLocation() const
Wraps an identifier and optional source location for the identifier.
Definition: AttributeList.h:82
bool isUsable() const
Definition: Ownership.h:171
The result type of a method or function.
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:720
const SourceManager & SM
Definition: Format.cpp:1468
const LangOptions & getLangOpts() const
Definition: Parser.h:274
SourceManager & getSourceManager() const
Definition: Preprocessor.h:819
Kind
Stop skipping at semicolon.
Definition: Parser.h:928
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:157
Encodes a location in the source.
bool TryAnnotateTypeOrScopeToken()
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
Definition: Parser.cpp:1656
bool is(tok::TokenKind Kind) const
Definition: FormatToken.h:304
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:177
Represents the declaration of a label.
Definition: Decl.h:468
ExtensionRAIIObject - This saves the state of extension warnings when constructed and disables them...
bool isAtStartOfMacroExpansion(SourceLocation loc, SourceLocation *MacroBegin=nullptr) const
Returns true if the given MacroID location points at the first token of the macro expansion...
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
Scope * getCurScope() const
Definition: Parser.h:281
bool isVectorType() const
Definition: Type.h:6134
ExprResult ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast=NotTypeCast)
Definition: ParseExpr.cpp:200
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition: DeclSpec.h:2451
StringRef getName() const
Return the actual identifier string.
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:1888
bool isNot(tok::TokenKind K) const
Definition: Token.h:96
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1262
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input)
Definition: SemaExpr.cpp:12837
bool expectAndConsume(unsigned DiagID=diag::err_expected, const char *Msg="", tok::TokenKind SkipToTok=tok::unknown)
Definition: Parser.cpp:2243
bool isRecord() const
Definition: DeclBase.h:1415
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:118
ExprResult ParseConstraintExpression()
Parse a constraint-expression.
Definition: ParseExpr.cpp:226
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:97
Bridging via __bridge_retain, which makes an ARC object available as a +1 C pointer.
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:15150
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition: Parser.cpp:72
bool isFunctionType() const
Definition: Type.h:6045
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:1006
void SetRangeEnd(SourceLocation Loc)
SetRangeEnd - Set the end of the source range to Loc, unless it&#39;s invalid.
Definition: DeclSpec.h:1900
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast=NotTypeCast)
Parse an expr that doesn&#39;t include (top-level) commas.
Definition: ParseExpr.cpp:160
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:92
const Expr * Replacement
Definition: AttributeList.h:66
const Type * getTypePtrOrNull() const
Definition: Type.h:5829
bool mightBeIntendedToBeTemplateName(ExprResult E)
Determine whether it&#39;s plausible that E was intended to be a template-name.
Definition: Sema.h:1833
This is a scope that can contain a declaration.
Definition: Scope.h:59
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:750
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13462
ExprResult ParseConstantExpression(TypeCastState isTypeCast=NotTypeCast)
Definition: ParseExpr.cpp:210
Captures information about "declaration specifiers".
Definition: DeclSpec.h:228
ActionResult< Expr * > ExprResult
Definition: Ownership.h:267
SourceLocation ConsumeToken()
ConsumeToken - Consume the current &#39;peek token&#39; and lex the next one.
Definition: Parser.h:319
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:191
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:129
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:266
ExprResult ExprError()
Definition: Ownership.h:283
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:930
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition: Scope.h:229
prec::Level getBinOpPrecedence(tok::TokenKind Kind, bool GreaterThanIsOperator, bool CPlusPlus11)
Return the precedence of the specified binary operator token.
A trivial tuple used to represent a source range.
This represents a decl that may have a name.
Definition: Decl.h:248
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition: DeclSpec.h:1009
bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const
Definition: FormatToken.h:338
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:615
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:278
ParsedAttributes - A collection of parsed attributes.
SourceLocation ColonLoc
Location of &#39;:&#39;.
Definition: OpenMPClause.h:98
This class handles loading and caching of source files into memory.
Code completion occurs in a parenthesized expression, which might also be a type cast.
Definition: Sema.h:10231
One specifier in an expression.
Definition: Availability.h:31
TypeResult ParseTypeName(SourceRange *Range=nullptr, DeclaratorContext Context=DeclaratorContext::TypeNameContext, 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:44
Stop skipping at specified token, but don&#39;t skip the token itself.
Definition: Parser.h:930
A RAII object to temporarily push a declaration context.
Definition: Sema.h:705