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