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