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