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