clang  16.0.0git
ParseExpr.cpp
Go to the documentation of this file.
1 //===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// Provides the Expression parsing implementation.
11 ///
12 /// Expressions in C99 basically consist of a bunch of binary operators with
13 /// unary operators and other random stuff at the leaves.
14 ///
15 /// In the C99 grammar, these unary operators bind tightest and are represented
16 /// as the 'cast-expression' production. Everything else is either a binary
17 /// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
18 /// handled by ParseCastExpression, the higher level pieces are handled by
19 /// ParseBinaryExpression.
20 ///
21 //===----------------------------------------------------------------------===//
22 
23 #include "clang/Parse/Parser.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/ExprCXX.h"
28 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/Scope.h"
32 #include "llvm/ADT/SmallVector.h"
33 using namespace clang;
34 
35 /// Simple precedence-based parser for binary/ternary operators.
36 ///
37 /// Note: we diverge from the C99 grammar when parsing the assignment-expression
38 /// production. C99 specifies that the LHS of an assignment operator should be
39 /// parsed as a unary-expression, but consistency dictates that it be a
40 /// conditional-expession. In practice, the important thing here is that the
41 /// LHS of an assignment has to be an l-value, which productions between
42 /// unary-expression and conditional-expression don't produce. Because we want
43 /// consistency, we parse the LHS as a conditional-expression, then check for
44 /// l-value-ness in semantic analysis stages.
45 ///
46 /// \verbatim
47 /// pm-expression: [C++ 5.5]
48 /// cast-expression
49 /// pm-expression '.*' cast-expression
50 /// pm-expression '->*' cast-expression
51 ///
52 /// multiplicative-expression: [C99 6.5.5]
53 /// Note: in C++, apply pm-expression instead of cast-expression
54 /// cast-expression
55 /// multiplicative-expression '*' cast-expression
56 /// multiplicative-expression '/' cast-expression
57 /// multiplicative-expression '%' cast-expression
58 ///
59 /// additive-expression: [C99 6.5.6]
60 /// multiplicative-expression
61 /// additive-expression '+' multiplicative-expression
62 /// additive-expression '-' multiplicative-expression
63 ///
64 /// shift-expression: [C99 6.5.7]
65 /// additive-expression
66 /// shift-expression '<<' additive-expression
67 /// shift-expression '>>' additive-expression
68 ///
69 /// compare-expression: [C++20 expr.spaceship]
70 /// shift-expression
71 /// compare-expression '<=>' shift-expression
72 ///
73 /// relational-expression: [C99 6.5.8]
74 /// compare-expression
75 /// relational-expression '<' compare-expression
76 /// relational-expression '>' compare-expression
77 /// relational-expression '<=' compare-expression
78 /// relational-expression '>=' compare-expression
79 ///
80 /// equality-expression: [C99 6.5.9]
81 /// relational-expression
82 /// equality-expression '==' relational-expression
83 /// equality-expression '!=' relational-expression
84 ///
85 /// AND-expression: [C99 6.5.10]
86 /// equality-expression
87 /// AND-expression '&' equality-expression
88 ///
89 /// exclusive-OR-expression: [C99 6.5.11]
90 /// AND-expression
91 /// exclusive-OR-expression '^' AND-expression
92 ///
93 /// inclusive-OR-expression: [C99 6.5.12]
94 /// exclusive-OR-expression
95 /// inclusive-OR-expression '|' exclusive-OR-expression
96 ///
97 /// logical-AND-expression: [C99 6.5.13]
98 /// inclusive-OR-expression
99 /// logical-AND-expression '&&' inclusive-OR-expression
100 ///
101 /// logical-OR-expression: [C99 6.5.14]
102 /// logical-AND-expression
103 /// logical-OR-expression '||' logical-AND-expression
104 ///
105 /// conditional-expression: [C99 6.5.15]
106 /// logical-OR-expression
107 /// logical-OR-expression '?' expression ':' conditional-expression
108 /// [GNU] logical-OR-expression '?' ':' conditional-expression
109 /// [C++] the third operand is an assignment-expression
110 ///
111 /// assignment-expression: [C99 6.5.16]
112 /// conditional-expression
113 /// unary-expression assignment-operator assignment-expression
114 /// [C++] throw-expression [C++ 15]
115 ///
116 /// assignment-operator: one of
117 /// = *= /= %= += -= <<= >>= &= ^= |=
118 ///
119 /// expression: [C99 6.5.17]
120 /// assignment-expression ...[opt]
121 /// expression ',' assignment-expression ...[opt]
122 /// \endverbatim
124  ExprResult LHS(ParseAssignmentExpression(isTypeCast));
125  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
126 }
127 
128 /// This routine is called when the '@' is seen and consumed.
129 /// Current token is an Identifier and is not a 'try'. This
130 /// routine is necessary to disambiguate \@try-statement from,
131 /// for example, \@encode-expression.
132 ///
134 Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
135  ExprResult LHS(ParseObjCAtExpression(AtLoc));
136  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
137 }
138 
139 /// This routine is called when a leading '__extension__' is seen and
140 /// consumed. This is necessary because the token gets consumed in the
141 /// process of disambiguating between an expression and a declaration.
143 Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
144  ExprResult LHS(true);
145  {
146  // Silence extension warnings in the sub-expression
147  ExtensionRAIIObject O(Diags);
148 
149  LHS = ParseCastExpression(AnyCastExpr);
150  }
151 
152  if (!LHS.isInvalid())
153  LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
154  LHS.get());
155 
156  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
157 }
158 
159 /// Parse an expr that doesn't include (top-level) commas.
161  if (Tok.is(tok::code_completion)) {
162  cutOffParsing();
164  PreferredType.get(Tok.getLocation()));
165  return ExprError();
166  }
167 
168  if (Tok.is(tok::kw_throw))
169  return ParseThrowExpression();
170  if (Tok.is(tok::kw_co_yield))
171  return ParseCoyieldExpression();
172 
173  ExprResult LHS = ParseCastExpression(AnyCastExpr,
174  /*isAddressOfOperand=*/false,
175  isTypeCast);
176  return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
177 }
178 
179 /// Parse an assignment expression where part of an Objective-C message
180 /// send has already been parsed.
181 ///
182 /// In this case \p LBracLoc indicates the location of the '[' of the message
183 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
184 /// the receiver of the message.
185 ///
186 /// Since this handles full assignment-expression's, it handles postfix
187 /// expressions and other binary operators for these expressions as well.
189 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
190  SourceLocation SuperLoc,
191  ParsedType ReceiverType,
192  Expr *ReceiverExpr) {
193  ExprResult R
194  = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
195  ReceiverType, ReceiverExpr);
196  R = ParsePostfixExpressionSuffix(R);
197  return ParseRHSOfBinaryExpression(R, prec::Assignment);
198 }
199 
202  assert(Actions.ExprEvalContexts.back().Context ==
204  "Call this function only if your ExpressionEvaluationContext is "
205  "already ConstantEvaluated");
206  ExprResult LHS(ParseCastExpression(AnyCastExpr, false, isTypeCast));
207  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
208  return Actions.ActOnConstantExpression(Res);
209 }
210 
212  // C++03 [basic.def.odr]p2:
213  // An expression is potentially evaluated unless it appears where an
214  // integral constant expression is required (see 5.19) [...].
215  // C++98 and C++11 have no such rule, but this is only a defect in C++98.
216  EnterExpressionEvaluationContext ConstantEvaluated(
219 }
220 
222  EnterExpressionEvaluationContext ConstantEvaluated(
224  ExprResult LHS(ParseCastExpression(AnyCastExpr, false, NotTypeCast));
225  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
226  return Actions.ActOnCaseExpr(CaseLoc, Res);
227 }
228 
229 /// Parse a constraint-expression.
230 ///
231 /// \verbatim
232 /// constraint-expression: C++2a[temp.constr.decl]p1
233 /// logical-or-expression
234 /// \endverbatim
236  EnterExpressionEvaluationContext ConstantEvaluated(
238  ExprResult LHS(ParseCastExpression(AnyCastExpr));
239  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
240  if (Res.isUsable() && !Actions.CheckConstraintExpression(Res.get())) {
241  Actions.CorrectDelayedTyposInExpr(Res);
242  return ExprError();
243  }
244  return Res;
245 }
246 
247 /// \brief Parse a constraint-logical-and-expression.
248 ///
249 /// \verbatim
250 /// C++2a[temp.constr.decl]p1
251 /// constraint-logical-and-expression:
252 /// primary-expression
253 /// constraint-logical-and-expression '&&' primary-expression
254 ///
255 /// \endverbatim
257 Parser::ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause) {
258  EnterExpressionEvaluationContext ConstantEvaluated(
260  bool NotPrimaryExpression = false;
261  auto ParsePrimary = [&] () {
262  ExprResult E = ParseCastExpression(PrimaryExprOnly,
263  /*isAddressOfOperand=*/false,
264  /*isTypeCast=*/NotTypeCast,
265  /*isVectorLiteral=*/false,
266  &NotPrimaryExpression);
267  if (E.isInvalid())
268  return ExprError();
269  auto RecoverFromNonPrimary = [&] (ExprResult E, bool Note) {
270  E = ParsePostfixExpressionSuffix(E);
271  // Use InclusiveOr, the precedence just after '&&' to not parse the
272  // next arguments to the logical and.
273  E = ParseRHSOfBinaryExpression(E, prec::InclusiveOr);
274  if (!E.isInvalid())
275  Diag(E.get()->getExprLoc(),
276  Note
277  ? diag::note_unparenthesized_non_primary_expr_in_requires_clause
278  : diag::err_unparenthesized_non_primary_expr_in_requires_clause)
281  PP.getLocForEndOfToken(E.get()->getEndLoc()), ")")
282  << E.get()->getSourceRange();
283  return E;
284  };
285 
286  if (NotPrimaryExpression ||
287  // Check if the following tokens must be a part of a non-primary
288  // expression
289  getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
290  /*CPlusPlus11=*/true) > prec::LogicalAnd ||
291  // Postfix operators other than '(' (which will be checked for in
292  // CheckConstraintExpression).
293  Tok.isOneOf(tok::period, tok::plusplus, tok::minusminus) ||
294  (Tok.is(tok::l_square) && !NextToken().is(tok::l_square))) {
295  E = RecoverFromNonPrimary(E, /*Note=*/false);
296  if (E.isInvalid())
297  return ExprError();
298  NotPrimaryExpression = false;
299  }
300  bool PossibleNonPrimary;
301  bool IsConstraintExpr =
302  Actions.CheckConstraintExpression(E.get(), Tok, &PossibleNonPrimary,
303  IsTrailingRequiresClause);
304  if (!IsConstraintExpr || PossibleNonPrimary) {
305  // Atomic constraint might be an unparenthesized non-primary expression
306  // (such as a binary operator), in which case we might get here (e.g. in
307  // 'requires 0 + 1 && true' we would now be at '+', and parse and ignore
308  // the rest of the addition expression). Try to parse the rest of it here.
309  if (PossibleNonPrimary)
310  E = RecoverFromNonPrimary(E, /*Note=*/!IsConstraintExpr);
311  Actions.CorrectDelayedTyposInExpr(E);
312  return ExprError();
313  }
314  return E;
315  };
316  ExprResult LHS = ParsePrimary();
317  if (LHS.isInvalid())
318  return ExprError();
319  while (Tok.is(tok::ampamp)) {
320  SourceLocation LogicalAndLoc = ConsumeToken();
321  ExprResult RHS = ParsePrimary();
322  if (RHS.isInvalid()) {
323  Actions.CorrectDelayedTyposInExpr(LHS);
324  return ExprError();
325  }
326  ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalAndLoc,
327  tok::ampamp, LHS.get(), RHS.get());
328  if (!Op.isUsable()) {
329  Actions.CorrectDelayedTyposInExpr(RHS);
330  Actions.CorrectDelayedTyposInExpr(LHS);
331  return ExprError();
332  }
333  LHS = Op;
334  }
335  return LHS;
336 }
337 
338 /// \brief Parse a constraint-logical-or-expression.
339 ///
340 /// \verbatim
341 /// C++2a[temp.constr.decl]p1
342 /// constraint-logical-or-expression:
343 /// constraint-logical-and-expression
344 /// constraint-logical-or-expression '||'
345 /// constraint-logical-and-expression
346 ///
347 /// \endverbatim
349 Parser::ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause) {
350  ExprResult LHS(ParseConstraintLogicalAndExpression(IsTrailingRequiresClause));
351  if (!LHS.isUsable())
352  return ExprError();
353  while (Tok.is(tok::pipepipe)) {
354  SourceLocation LogicalOrLoc = ConsumeToken();
355  ExprResult RHS =
356  ParseConstraintLogicalAndExpression(IsTrailingRequiresClause);
357  if (!RHS.isUsable()) {
358  Actions.CorrectDelayedTyposInExpr(LHS);
359  return ExprError();
360  }
361  ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalOrLoc,
362  tok::pipepipe, LHS.get(), RHS.get());
363  if (!Op.isUsable()) {
364  Actions.CorrectDelayedTyposInExpr(RHS);
365  Actions.CorrectDelayedTyposInExpr(LHS);
366  return ExprError();
367  }
368  LHS = Op;
369  }
370  return LHS;
371 }
372 
373 bool Parser::isNotExpressionStart() {
374  tok::TokenKind K = Tok.getKind();
375  if (K == tok::l_brace || K == tok::r_brace ||
376  K == tok::kw_for || K == tok::kw_while ||
377  K == tok::kw_if || K == tok::kw_else ||
378  K == tok::kw_goto || K == tok::kw_try)
379  return true;
380  // If this is a decl-specifier, we can't be at the start of an expression.
381  return isKnownToBeDeclarationSpecifier();
382 }
383 
384 bool Parser::isFoldOperator(prec::Level Level) const {
385  return Level > prec::Unknown && Level != prec::Conditional &&
387 }
388 
389 bool Parser::isFoldOperator(tok::TokenKind Kind) const {
390  return isFoldOperator(getBinOpPrecedence(Kind, GreaterThanIsOperator, true));
391 }
392 
393 /// Parse a binary expression that starts with \p LHS and has a
394 /// precedence of at least \p MinPrec.
396 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
397  prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
398  GreaterThanIsOperator,
400  SourceLocation ColonLoc;
401 
402  auto SavedType = PreferredType;
403  while (true) {
404  // Every iteration may rely on a preferred type for the whole expression.
405  PreferredType = SavedType;
406  // If this token has a lower precedence than we are allowed to parse (e.g.
407  // because we are called recursively, or because the token is not a binop),
408  // then we are done!
409  if (NextTokPrec < MinPrec)
410  return LHS;
411 
412  // Consume the operator, saving the operator token for error reporting.
413  Token OpToken = Tok;
414  ConsumeToken();
415 
416  if (OpToken.is(tok::caretcaret)) {
417  return ExprError(Diag(Tok, diag::err_opencl_logical_exclusive_or));
418  }
419 
420  // If we're potentially in a template-id, we may now be able to determine
421  // whether we're actually in one or not.
422  if (OpToken.isOneOf(tok::comma, tok::greater, tok::greatergreater,
423  tok::greatergreatergreater) &&
424  checkPotentialAngleBracketDelimiter(OpToken))
425  return ExprError();
426 
427  // Bail out when encountering a comma followed by a token which can't
428  // possibly be the start of an expression. For instance:
429  // int f() { return 1, }
430  // We can't do this before consuming the comma, because
431  // isNotExpressionStart() looks at the token stream.
432  if (OpToken.is(tok::comma) && isNotExpressionStart()) {
433  PP.EnterToken(Tok, /*IsReinject*/true);
434  Tok = OpToken;
435  return LHS;
436  }
437 
438  // If the next token is an ellipsis, then this is a fold-expression. Leave
439  // it alone so we can handle it in the paren expression.
440  if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
441  // FIXME: We can't check this via lookahead before we consume the token
442  // because that tickles a lexer bug.
443  PP.EnterToken(Tok, /*IsReinject*/true);
444  Tok = OpToken;
445  return LHS;
446  }
447 
448  // In Objective-C++, alternative operator tokens can be used as keyword args
449  // in message expressions. Unconsume the token so that it can reinterpreted
450  // as an identifier in ParseObjCMessageExpressionBody. i.e., we support:
451  // [foo meth:0 and:0];
452  // [foo not_eq];
453  if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
454  Tok.isOneOf(tok::colon, tok::r_square) &&
455  OpToken.getIdentifierInfo() != nullptr) {
456  PP.EnterToken(Tok, /*IsReinject*/true);
457  Tok = OpToken;
458  return LHS;
459  }
460 
461  // Special case handling for the ternary operator.
462  ExprResult TernaryMiddle(true);
463  if (NextTokPrec == prec::Conditional) {
464  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
465  // Parse a braced-init-list here for error recovery purposes.
466  SourceLocation BraceLoc = Tok.getLocation();
467  TernaryMiddle = ParseBraceInitializer();
468  if (!TernaryMiddle.isInvalid()) {
469  Diag(BraceLoc, diag::err_init_list_bin_op)
470  << /*RHS*/ 1 << PP.getSpelling(OpToken)
471  << Actions.getExprRange(TernaryMiddle.get());
472  TernaryMiddle = ExprError();
473  }
474  } else if (Tok.isNot(tok::colon)) {
475  // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
477 
478  // Handle this production specially:
479  // logical-OR-expression '?' expression ':' conditional-expression
480  // In particular, the RHS of the '?' is 'expression', not
481  // 'logical-OR-expression' as we might expect.
482  TernaryMiddle = ParseExpression();
483  } else {
484  // Special case handling of "X ? Y : Z" where Y is empty:
485  // logical-OR-expression '?' ':' conditional-expression [GNU]
486  TernaryMiddle = nullptr;
487  Diag(Tok, diag::ext_gnu_conditional_expr);
488  }
489 
490  if (TernaryMiddle.isInvalid()) {
491  Actions.CorrectDelayedTyposInExpr(LHS);
492  LHS = ExprError();
493  TernaryMiddle = nullptr;
494  }
495 
496  if (!TryConsumeToken(tok::colon, ColonLoc)) {
497  // Otherwise, we're missing a ':'. Assume that this was a typo that
498  // the user forgot. If we're not in a macro expansion, we can suggest
499  // a fixit hint. If there were two spaces before the current token,
500  // suggest inserting the colon in between them, otherwise insert ": ".
501  SourceLocation FILoc = Tok.getLocation();
502  const char *FIText = ": ";
503  const SourceManager &SM = PP.getSourceManager();
504  if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
505  assert(FILoc.isFileID());
506  bool IsInvalid = false;
507  const char *SourcePtr =
508  SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
509  if (!IsInvalid && *SourcePtr == ' ') {
510  SourcePtr =
511  SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
512  if (!IsInvalid && *SourcePtr == ' ') {
513  FILoc = FILoc.getLocWithOffset(-1);
514  FIText = ":";
515  }
516  }
517  }
518 
519  Diag(Tok, diag::err_expected)
520  << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
521  Diag(OpToken, diag::note_matching) << tok::question;
522  ColonLoc = Tok.getLocation();
523  }
524  }
525 
526  PreferredType.enterBinary(Actions, Tok.getLocation(), LHS.get(),
527  OpToken.getKind());
528  // Parse another leaf here for the RHS of the operator.
529  // ParseCastExpression works here because all RHS expressions in C have it
530  // as a prefix, at least. However, in C++, an assignment-expression could
531  // be a throw-expression, which is not a valid cast-expression.
532  // Therefore we need some special-casing here.
533  // Also note that the third operand of the conditional operator is
534  // an assignment-expression in C++, and in C++11, we can have a
535  // braced-init-list on the RHS of an assignment. For better diagnostics,
536  // parse as if we were allowed braced-init-lists everywhere, and check that
537  // they only appear on the RHS of assignments later.
538  ExprResult RHS;
539  bool RHSIsInitList = false;
540  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
541  RHS = ParseBraceInitializer();
542  RHSIsInitList = true;
543  } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
545  else
546  RHS = ParseCastExpression(AnyCastExpr);
547 
548  if (RHS.isInvalid()) {
549  // FIXME: Errors generated by the delayed typo correction should be
550  // printed before errors from parsing the RHS, not after.
551  Actions.CorrectDelayedTyposInExpr(LHS);
552  if (TernaryMiddle.isUsable())
553  TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
554  LHS = ExprError();
555  }
556 
557  // Remember the precedence of this operator and get the precedence of the
558  // operator immediately to the right of the RHS.
559  prec::Level ThisPrec = NextTokPrec;
560  NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
562 
563  // Assignment and conditional expressions are right-associative.
564  bool isRightAssoc = ThisPrec == prec::Conditional ||
565  ThisPrec == prec::Assignment;
566 
567  // Get the precedence of the operator to the right of the RHS. If it binds
568  // more tightly with RHS than we do, evaluate it completely first.
569  if (ThisPrec < NextTokPrec ||
570  (ThisPrec == NextTokPrec && isRightAssoc)) {
571  if (!RHS.isInvalid() && RHSIsInitList) {
572  Diag(Tok, diag::err_init_list_bin_op)
573  << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
574  RHS = ExprError();
575  }
576  // If this is left-associative, only parse things on the RHS that bind
577  // more tightly than the current operator. If it is left-associative, it
578  // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
579  // A=(B=(C=D)), where each paren is a level of recursion here.
580  // The function takes ownership of the RHS.
581  RHS = ParseRHSOfBinaryExpression(RHS,
582  static_cast<prec::Level>(ThisPrec + !isRightAssoc));
583  RHSIsInitList = false;
584 
585  if (RHS.isInvalid()) {
586  // FIXME: Errors generated by the delayed typo correction should be
587  // printed before errors from ParseRHSOfBinaryExpression, not after.
588  Actions.CorrectDelayedTyposInExpr(LHS);
589  if (TernaryMiddle.isUsable())
590  TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
591  LHS = ExprError();
592  }
593 
594  NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
596  }
597 
598  if (!RHS.isInvalid() && RHSIsInitList) {
599  if (ThisPrec == prec::Assignment) {
600  Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
601  << Actions.getExprRange(RHS.get());
602  } else if (ColonLoc.isValid()) {
603  Diag(ColonLoc, diag::err_init_list_bin_op)
604  << /*RHS*/1 << ":"
605  << Actions.getExprRange(RHS.get());
606  LHS = ExprError();
607  } else {
608  Diag(OpToken, diag::err_init_list_bin_op)
609  << /*RHS*/1 << PP.getSpelling(OpToken)
610  << Actions.getExprRange(RHS.get());
611  LHS = ExprError();
612  }
613  }
614 
615  ExprResult OrigLHS = LHS;
616  if (!LHS.isInvalid()) {
617  // Combine the LHS and RHS into the LHS (e.g. build AST).
618  if (TernaryMiddle.isInvalid()) {
619  // If we're using '>>' as an operator within a template
620  // argument list (in C++98), suggest the addition of
621  // parentheses so that the code remains well-formed in C++0x.
622  if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
623  SuggestParentheses(OpToken.getLocation(),
624  diag::warn_cxx11_right_shift_in_template_arg,
625  SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
626  Actions.getExprRange(RHS.get()).getEnd()));
627 
628  ExprResult BinOp =
629  Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
630  OpToken.getKind(), LHS.get(), RHS.get());
631  if (BinOp.isInvalid())
632  BinOp = Actions.CreateRecoveryExpr(LHS.get()->getBeginLoc(),
633  RHS.get()->getEndLoc(),
634  {LHS.get(), RHS.get()});
635 
636  LHS = BinOp;
637  } else {
638  ExprResult CondOp = Actions.ActOnConditionalOp(
639  OpToken.getLocation(), ColonLoc, LHS.get(), TernaryMiddle.get(),
640  RHS.get());
641  if (CondOp.isInvalid()) {
642  std::vector<clang::Expr *> Args;
643  // TernaryMiddle can be null for the GNU conditional expr extension.
644  if (TernaryMiddle.get())
645  Args = {LHS.get(), TernaryMiddle.get(), RHS.get()};
646  else
647  Args = {LHS.get(), RHS.get()};
648  CondOp = Actions.CreateRecoveryExpr(LHS.get()->getBeginLoc(),
649  RHS.get()->getEndLoc(), Args);
650  }
651 
652  LHS = CondOp;
653  }
654  // In this case, ActOnBinOp or ActOnConditionalOp performed the
655  // CorrectDelayedTyposInExpr check.
656  if (!getLangOpts().CPlusPlus)
657  continue;
658  }
659 
660  // Ensure potential typos aren't left undiagnosed.
661  if (LHS.isInvalid()) {
662  Actions.CorrectDelayedTyposInExpr(OrigLHS);
663  Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
664  Actions.CorrectDelayedTyposInExpr(RHS);
665  }
666  }
667 }
668 
669 /// Parse a cast-expression, unary-expression or primary-expression, based
670 /// on \p ExprType.
671 ///
672 /// \p isAddressOfOperand exists because an id-expression that is the
673 /// operand of address-of gets special treatment due to member pointers.
674 ///
675 ExprResult Parser::ParseCastExpression(CastParseKind ParseKind,
676  bool isAddressOfOperand,
677  TypeCastState isTypeCast,
678  bool isVectorLiteral,
679  bool *NotPrimaryExpression) {
680  bool NotCastExpr;
681  ExprResult Res = ParseCastExpression(ParseKind,
682  isAddressOfOperand,
683  NotCastExpr,
684  isTypeCast,
685  isVectorLiteral,
686  NotPrimaryExpression);
687  if (NotCastExpr)
688  Diag(Tok, diag::err_expected_expression);
689  return Res;
690 }
691 
692 namespace {
693 class CastExpressionIdValidator final : public CorrectionCandidateCallback {
694  public:
695  CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
696  : NextToken(Next), AllowNonTypes(AllowNonTypes) {
697  WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
698  }
699 
700  bool ValidateCandidate(const TypoCorrection &candidate) override {
701  NamedDecl *ND = candidate.getCorrectionDecl();
702  if (!ND)
703  return candidate.isKeyword();
704 
705  if (isa<TypeDecl>(ND))
706  return WantTypeSpecifiers;
707 
708  if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
709  return false;
710 
711  if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
712  return true;
713 
714  for (auto *C : candidate) {
715  NamedDecl *ND = C->getUnderlyingDecl();
716  if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
717  return true;
718  }
719  return false;
720  }
721 
722  std::unique_ptr<CorrectionCandidateCallback> clone() override {
723  return std::make_unique<CastExpressionIdValidator>(*this);
724  }
725 
726  private:
727  Token NextToken;
728  bool AllowNonTypes;
729 };
730 }
731 
732 /// Parse a cast-expression, or, if \pisUnaryExpression is true, parse
733 /// a unary-expression.
734 ///
735 /// \p isAddressOfOperand exists because an id-expression that is the operand
736 /// of address-of gets special treatment due to member pointers. NotCastExpr
737 /// is set to true if the token is not the start of a cast-expression, and no
738 /// diagnostic is emitted in this case and no tokens are consumed.
739 ///
740 /// \verbatim
741 /// cast-expression: [C99 6.5.4]
742 /// unary-expression
743 /// '(' type-name ')' cast-expression
744 ///
745 /// unary-expression: [C99 6.5.3]
746 /// postfix-expression
747 /// '++' unary-expression
748 /// '--' unary-expression
749 /// [Coro] 'co_await' cast-expression
750 /// unary-operator cast-expression
751 /// 'sizeof' unary-expression
752 /// 'sizeof' '(' type-name ')'
753 /// [C++11] 'sizeof' '...' '(' identifier ')'
754 /// [GNU] '__alignof' unary-expression
755 /// [GNU] '__alignof' '(' type-name ')'
756 /// [C11] '_Alignof' '(' type-name ')'
757 /// [C++11] 'alignof' '(' type-id ')'
758 /// [GNU] '&&' identifier
759 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
760 /// [C++] new-expression
761 /// [C++] delete-expression
762 ///
763 /// unary-operator: one of
764 /// '&' '*' '+' '-' '~' '!'
765 /// [GNU] '__extension__' '__real' '__imag'
766 ///
767 /// primary-expression: [C99 6.5.1]
768 /// [C99] identifier
769 /// [C++] id-expression
770 /// constant
771 /// string-literal
772 /// [C++] boolean-literal [C++ 2.13.5]
773 /// [C++11] 'nullptr' [C++11 2.14.7]
774 /// [C++11] user-defined-literal
775 /// '(' expression ')'
776 /// [C11] generic-selection
777 /// [C++2a] requires-expression
778 /// '__func__' [C99 6.4.2.2]
779 /// [GNU] '__FUNCTION__'
780 /// [MS] '__FUNCDNAME__'
781 /// [MS] 'L__FUNCTION__'
782 /// [MS] '__FUNCSIG__'
783 /// [MS] 'L__FUNCSIG__'
784 /// [GNU] '__PRETTY_FUNCTION__'
785 /// [GNU] '(' compound-statement ')'
786 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
787 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
788 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
789 /// assign-expr ')'
790 /// [GNU] '__builtin_FILE' '(' ')'
791 /// [GNU] '__builtin_FUNCTION' '(' ')'
792 /// [GNU] '__builtin_LINE' '(' ')'
793 /// [CLANG] '__builtin_COLUMN' '(' ')'
794 /// [GNU] '__builtin_source_location' '(' ')'
795 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
796 /// [GNU] '__null'
797 /// [OBJC] '[' objc-message-expr ']'
798 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
799 /// [OBJC] '\@protocol' '(' identifier ')'
800 /// [OBJC] '\@encode' '(' type-name ')'
801 /// [OBJC] objc-string-literal
802 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
803 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
804 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
805 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
806 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
807 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
808 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
809 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
810 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
811 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
812 /// [C++] 'this' [C++ 9.3.2]
813 /// [G++] unary-type-trait '(' type-id ')'
814 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
815 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
816 /// [clang] '^' block-literal
817 ///
818 /// constant: [C99 6.4.4]
819 /// integer-constant
820 /// floating-constant
821 /// enumeration-constant -> identifier
822 /// character-constant
823 ///
824 /// id-expression: [C++ 5.1]
825 /// unqualified-id
826 /// qualified-id
827 ///
828 /// unqualified-id: [C++ 5.1]
829 /// identifier
830 /// operator-function-id
831 /// conversion-function-id
832 /// '~' class-name
833 /// template-id
834 ///
835 /// new-expression: [C++ 5.3.4]
836 /// '::'[opt] 'new' new-placement[opt] new-type-id
837 /// new-initializer[opt]
838 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
839 /// new-initializer[opt]
840 ///
841 /// delete-expression: [C++ 5.3.5]
842 /// '::'[opt] 'delete' cast-expression
843 /// '::'[opt] 'delete' '[' ']' cast-expression
844 ///
845 /// [GNU/Embarcadero] unary-type-trait:
846 /// '__is_arithmetic'
847 /// '__is_floating_point'
848 /// '__is_integral'
849 /// '__is_lvalue_expr'
850 /// '__is_rvalue_expr'
851 /// '__is_complete_type'
852 /// '__is_void'
853 /// '__is_array'
854 /// '__is_function'
855 /// '__is_reference'
856 /// '__is_lvalue_reference'
857 /// '__is_rvalue_reference'
858 /// '__is_fundamental'
859 /// '__is_object'
860 /// '__is_scalar'
861 /// '__is_compound'
862 /// '__is_pointer'
863 /// '__is_member_object_pointer'
864 /// '__is_member_function_pointer'
865 /// '__is_member_pointer'
866 /// '__is_const'
867 /// '__is_volatile'
868 /// '__is_trivial'
869 /// '__is_standard_layout'
870 /// '__is_signed'
871 /// '__is_unsigned'
872 ///
873 /// [GNU] unary-type-trait:
874 /// '__has_nothrow_assign'
875 /// '__has_nothrow_copy'
876 /// '__has_nothrow_constructor'
877 /// '__has_trivial_assign' [TODO]
878 /// '__has_trivial_copy' [TODO]
879 /// '__has_trivial_constructor'
880 /// '__has_trivial_destructor'
881 /// '__has_virtual_destructor'
882 /// '__is_abstract' [TODO]
883 /// '__is_class'
884 /// '__is_empty' [TODO]
885 /// '__is_enum'
886 /// '__is_final'
887 /// '__is_pod'
888 /// '__is_polymorphic'
889 /// '__is_sealed' [MS]
890 /// '__is_trivial'
891 /// '__is_union'
892 /// '__has_unique_object_representations'
893 ///
894 /// [Clang] unary-type-trait:
895 /// '__is_aggregate'
896 /// '__trivially_copyable'
897 ///
898 /// binary-type-trait:
899 /// [GNU] '__is_base_of'
900 /// [MS] '__is_convertible_to'
901 /// '__is_convertible'
902 /// '__is_same'
903 ///
904 /// [Embarcadero] array-type-trait:
905 /// '__array_rank'
906 /// '__array_extent'
907 ///
908 /// [Embarcadero] expression-trait:
909 /// '__is_lvalue_expr'
910 /// '__is_rvalue_expr'
911 /// \endverbatim
912 ///
913 ExprResult Parser::ParseCastExpression(CastParseKind ParseKind,
914  bool isAddressOfOperand,
915  bool &NotCastExpr,
916  TypeCastState isTypeCast,
917  bool isVectorLiteral,
918  bool *NotPrimaryExpression) {
919  ExprResult Res;
920  tok::TokenKind SavedKind = Tok.getKind();
921  auto SavedType = PreferredType;
922  NotCastExpr = false;
923 
924  // Are postfix-expression suffix operators permitted after this
925  // cast-expression? If not, and we find some, we'll parse them anyway and
926  // diagnose them.
927  bool AllowSuffix = true;
928 
929  // This handles all of cast-expression, unary-expression, postfix-expression,
930  // and primary-expression. We handle them together like this for efficiency
931  // and to simplify handling of an expression starting with a '(' token: which
932  // may be one of a parenthesized expression, cast-expression, compound literal
933  // expression, or statement expression.
934  //
935  // If the parsed tokens consist of a primary-expression, the cases below
936  // break out of the switch; at the end we call ParsePostfixExpressionSuffix
937  // to handle the postfix expression suffixes. Cases that cannot be followed
938  // by postfix exprs should set AllowSuffix to false.
939  switch (SavedKind) {
940  case tok::l_paren: {
941  // If this expression is limited to being a unary-expression, the paren can
942  // not start a cast expression.
943  ParenParseOption ParenExprType;
944  switch (ParseKind) {
945  case CastParseKind::UnaryExprOnly:
946  assert(getLangOpts().CPlusPlus && "not possible to get here in C");
947  [[fallthrough]];
948  case CastParseKind::AnyCastExpr:
949  ParenExprType = ParenParseOption::CastExpr;
950  break;
951  case CastParseKind::PrimaryExprOnly:
952  ParenExprType = FoldExpr;
953  break;
954  }
955  ParsedType CastTy;
956  SourceLocation RParenLoc;
957  Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
958  isTypeCast == IsTypeCast, CastTy, RParenLoc);
959 
960  // FIXME: What should we do if a vector literal is followed by a
961  // postfix-expression suffix? Usually postfix operators are permitted on
962  // literals.
963  if (isVectorLiteral)
964  return Res;
965 
966  switch (ParenExprType) {
967  case SimpleExpr: break; // Nothing else to do.
968  case CompoundStmt: break; // Nothing else to do.
969  case CompoundLiteral:
970  // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
971  // postfix-expression exist, parse them now.
972  break;
973  case CastExpr:
974  // We have parsed the cast-expression and no postfix-expr pieces are
975  // following.
976  return Res;
977  case FoldExpr:
978  // We only parsed a fold-expression. There might be postfix-expr pieces
979  // afterwards; parse them now.
980  break;
981  }
982 
983  break;
984  }
985 
986  // primary-expression
987  case tok::numeric_constant:
988  // constant: integer-constant
989  // constant: floating-constant
990 
991  Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
992  ConsumeToken();
993  break;
994 
995  case tok::kw_true:
996  case tok::kw_false:
997  Res = ParseCXXBoolLiteral();
998  break;
999 
1000  case tok::kw___objc_yes:
1001  case tok::kw___objc_no:
1002  Res = ParseObjCBoolLiteral();
1003  break;
1004 
1005  case tok::kw_nullptr:
1006  if (getLangOpts().CPlusPlus)
1007  Diag(Tok, diag::warn_cxx98_compat_nullptr);
1008  else
1009  Diag(Tok, getLangOpts().C2x ? diag::warn_c17_compat_nullptr
1010  : diag::ext_c_nullptr);
1011 
1012  Res = Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
1013  break;
1014 
1015  case tok::annot_primary_expr:
1016  case tok::annot_overload_set:
1017  Res = getExprAnnotation(Tok);
1018  if (!Res.isInvalid() && Tok.getKind() == tok::annot_overload_set)
1019  Res = Actions.ActOnNameClassifiedAsOverloadSet(getCurScope(), Res.get());
1020  ConsumeAnnotationToken();
1021  if (!Res.isInvalid() && Tok.is(tok::less))
1022  checkPotentialAngleBracket(Res);
1023  break;
1024 
1025  case tok::annot_non_type:
1026  case tok::annot_non_type_dependent:
1027  case tok::annot_non_type_undeclared: {
1028  CXXScopeSpec SS;
1029  Token Replacement;
1030  Res = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
1031  assert(!Res.isUnset() &&
1032  "should not perform typo correction on annotation token");
1033  break;
1034  }
1035 
1036  case tok::kw___super:
1037  case tok::kw_decltype:
1038  // Annotate the token and tail recurse.
1040  return ExprError();
1041  assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
1042  return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1043  isVectorLiteral, NotPrimaryExpression);
1044 
1045  case tok::identifier:
1046  ParseIdentifier: { // primary-expression: identifier
1047  // unqualified-id: identifier
1048  // constant: enumeration-constant
1049  // Turn a potentially qualified name into a annot_typename or
1050  // annot_cxxscope if it would be valid. This handles things like x::y, etc.
1051  if (getLangOpts().CPlusPlus) {
1052  // Avoid the unnecessary parse-time lookup in the common case
1053  // where the syntax forbids a type.
1054  const Token &Next = NextToken();
1055 
1056  // If this identifier was reverted from a token ID, and the next token
1057  // is a parenthesis, this is likely to be a use of a type trait. Check
1058  // those tokens.
1059  if (Next.is(tok::l_paren) &&
1060  Tok.is(tok::identifier) &&
1062  IdentifierInfo *II = Tok.getIdentifierInfo();
1063  // Build up the mapping of revertible type traits, for future use.
1064  if (RevertibleTypeTraits.empty()) {
1065 #define RTT_JOIN(X,Y) X##Y
1066 #define REVERTIBLE_TYPE_TRAIT(Name) \
1067  RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
1068  = RTT_JOIN(tok::kw_,Name)
1069 
1070  REVERTIBLE_TYPE_TRAIT(__is_abstract);
1071  REVERTIBLE_TYPE_TRAIT(__is_aggregate);
1072  REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
1073  REVERTIBLE_TYPE_TRAIT(__is_array);
1074  REVERTIBLE_TYPE_TRAIT(__is_assignable);
1075  REVERTIBLE_TYPE_TRAIT(__is_base_of);
1076  REVERTIBLE_TYPE_TRAIT(__is_bounded_array);
1077  REVERTIBLE_TYPE_TRAIT(__is_class);
1078  REVERTIBLE_TYPE_TRAIT(__is_complete_type);
1079  REVERTIBLE_TYPE_TRAIT(__is_compound);
1080  REVERTIBLE_TYPE_TRAIT(__is_const);
1081  REVERTIBLE_TYPE_TRAIT(__is_constructible);
1082  REVERTIBLE_TYPE_TRAIT(__is_convertible);
1083  REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
1084  REVERTIBLE_TYPE_TRAIT(__is_destructible);
1085  REVERTIBLE_TYPE_TRAIT(__is_empty);
1086  REVERTIBLE_TYPE_TRAIT(__is_enum);
1087  REVERTIBLE_TYPE_TRAIT(__is_floating_point);
1088  REVERTIBLE_TYPE_TRAIT(__is_final);
1089  REVERTIBLE_TYPE_TRAIT(__is_function);
1090  REVERTIBLE_TYPE_TRAIT(__is_fundamental);
1091  REVERTIBLE_TYPE_TRAIT(__is_integral);
1092  REVERTIBLE_TYPE_TRAIT(__is_interface_class);
1093  REVERTIBLE_TYPE_TRAIT(__is_literal);
1094  REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
1095  REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
1096  REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
1097  REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
1098  REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
1099  REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
1100  REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
1101  REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
1102  REVERTIBLE_TYPE_TRAIT(__is_nullptr);
1103  REVERTIBLE_TYPE_TRAIT(__is_object);
1104  REVERTIBLE_TYPE_TRAIT(__is_pod);
1105  REVERTIBLE_TYPE_TRAIT(__is_pointer);
1106  REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
1107  REVERTIBLE_TYPE_TRAIT(__is_reference);
1108  REVERTIBLE_TYPE_TRAIT(__is_referenceable);
1109  REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
1110  REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
1111  REVERTIBLE_TYPE_TRAIT(__is_same);
1112  REVERTIBLE_TYPE_TRAIT(__is_scalar);
1113  REVERTIBLE_TYPE_TRAIT(__is_scoped_enum);
1114  REVERTIBLE_TYPE_TRAIT(__is_sealed);
1115  REVERTIBLE_TYPE_TRAIT(__is_signed);
1116  REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
1117  REVERTIBLE_TYPE_TRAIT(__is_trivial);
1118  REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
1119  REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
1120  REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
1121  REVERTIBLE_TYPE_TRAIT(__is_unbounded_array);
1122  REVERTIBLE_TYPE_TRAIT(__is_union);
1123  REVERTIBLE_TYPE_TRAIT(__is_unsigned);
1124  REVERTIBLE_TYPE_TRAIT(__is_void);
1125  REVERTIBLE_TYPE_TRAIT(__is_volatile);
1126 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) \
1127  REVERTIBLE_TYPE_TRAIT(RTT_JOIN(__, Trait));
1128 #include "clang/Basic/TransformTypeTraits.def"
1129 #undef REVERTIBLE_TYPE_TRAIT
1130 #undef RTT_JOIN
1131  }
1132 
1133  // If we find that this is in fact the name of a type trait,
1134  // update the token kind in place and parse again to treat it as
1135  // the appropriate kind of type trait.
1136  llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
1137  = RevertibleTypeTraits.find(II);
1138  if (Known != RevertibleTypeTraits.end()) {
1139  Tok.setKind(Known->second);
1140  return ParseCastExpression(ParseKind, isAddressOfOperand,
1141  NotCastExpr, isTypeCast,
1142  isVectorLiteral, NotPrimaryExpression);
1143  }
1144  }
1145 
1146  if ((!ColonIsSacred && Next.is(tok::colon)) ||
1147  Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
1148  tok::l_brace)) {
1149  // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1151  return ExprError();
1152  if (!Tok.is(tok::identifier))
1153  return ParseCastExpression(ParseKind, isAddressOfOperand,
1154  NotCastExpr, isTypeCast,
1155  isVectorLiteral,
1156  NotPrimaryExpression);
1157  }
1158  }
1159 
1160  // Consume the identifier so that we can see if it is followed by a '(' or
1161  // '.'.
1162  IdentifierInfo &II = *Tok.getIdentifierInfo();
1163  SourceLocation ILoc = ConsumeToken();
1164 
1165  // Support 'Class.property' and 'super.property' notation.
1166  if (getLangOpts().ObjC && Tok.is(tok::period) &&
1167  (Actions.getTypeName(II, ILoc, getCurScope()) ||
1168  // Allow the base to be 'super' if in an objc-method.
1169  (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
1170  ConsumeToken();
1171 
1172  if (Tok.is(tok::code_completion) && &II != Ident_super) {
1173  cutOffParsing();
1175  getCurScope(), II, ILoc, ExprStatementTokLoc == ILoc);
1176  return ExprError();
1177  }
1178  // Allow either an identifier or the keyword 'class' (in C++).
1179  if (Tok.isNot(tok::identifier) &&
1180  !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
1181  Diag(Tok, diag::err_expected_property_name);
1182  return ExprError();
1183  }
1184  IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
1185  SourceLocation PropertyLoc = ConsumeToken();
1186 
1187  Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
1188  ILoc, PropertyLoc);
1189  break;
1190  }
1191 
1192  // In an Objective-C method, if we have "super" followed by an identifier,
1193  // the token sequence is ill-formed. However, if there's a ':' or ']' after
1194  // that identifier, this is probably a message send with a missing open
1195  // bracket. Treat it as such.
1196  if (getLangOpts().ObjC && &II == Ident_super && !InMessageExpression &&
1197  getCurScope()->isInObjcMethodScope() &&
1198  ((Tok.is(tok::identifier) &&
1199  (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
1200  Tok.is(tok::code_completion))) {
1201  Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, nullptr,
1202  nullptr);
1203  break;
1204  }
1205 
1206  // If we have an Objective-C class name followed by an identifier
1207  // and either ':' or ']', this is an Objective-C class message
1208  // send that's missing the opening '['. Recovery
1209  // appropriately. Also take this path if we're performing code
1210  // completion after an Objective-C class name.
1211  if (getLangOpts().ObjC &&
1212  ((Tok.is(tok::identifier) && !InMessageExpression) ||
1213  Tok.is(tok::code_completion))) {
1214  const Token& Next = NextToken();
1215  if (Tok.is(tok::code_completion) ||
1216  Next.is(tok::colon) || Next.is(tok::r_square))
1217  if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
1218  if (Typ.get()->isObjCObjectOrInterfaceType()) {
1219  // Fake up a Declarator to use with ActOnTypeName.
1220  DeclSpec DS(AttrFactory);
1221  DS.SetRangeStart(ILoc);
1222  DS.SetRangeEnd(ILoc);
1223  const char *PrevSpec = nullptr;
1224  unsigned DiagID;
1225  DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
1226  Actions.getASTContext().getPrintingPolicy());
1227 
1228  Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1230  TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
1231  DeclaratorInfo);
1232  if (Ty.isInvalid())
1233  break;
1234 
1235  Res = ParseObjCMessageExpressionBody(SourceLocation(),
1236  SourceLocation(),
1237  Ty.get(), nullptr);
1238  break;
1239  }
1240  }
1241 
1242  // Make sure to pass down the right value for isAddressOfOperand.
1243  if (isAddressOfOperand && isPostfixExpressionSuffixStart())
1244  isAddressOfOperand = false;
1245 
1246  // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
1247  // need to know whether or not this identifier is a function designator or
1248  // not.
1249  UnqualifiedId Name;
1250  CXXScopeSpec ScopeSpec;
1251  SourceLocation TemplateKWLoc;
1252  Token Replacement;
1253  CastExpressionIdValidator Validator(
1254  /*Next=*/Tok,
1255  /*AllowTypes=*/isTypeCast != NotTypeCast,
1256  /*AllowNonTypes=*/isTypeCast != IsTypeCast);
1257  Validator.IsAddressOfOperand = isAddressOfOperand;
1258  if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
1259  Validator.WantExpressionKeywords = false;
1260  Validator.WantRemainingKeywords = false;
1261  } else {
1262  Validator.WantRemainingKeywords = Tok.isNot(tok::r_paren);
1263  }
1264  Name.setIdentifier(&II, ILoc);
1265  Res = Actions.ActOnIdExpression(
1266  getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
1267  isAddressOfOperand, &Validator,
1268  /*IsInlineAsmIdentifier=*/false,
1269  Tok.is(tok::r_paren) ? nullptr : &Replacement);
1270  if (!Res.isInvalid() && Res.isUnset()) {
1271  UnconsumeToken(Replacement);
1272  return ParseCastExpression(ParseKind, isAddressOfOperand,
1273  NotCastExpr, isTypeCast,
1274  /*isVectorLiteral=*/false,
1275  NotPrimaryExpression);
1276  }
1277  if (!Res.isInvalid() && Tok.is(tok::less))
1278  checkPotentialAngleBracket(Res);
1279  break;
1280  }
1281  case tok::char_constant: // constant: character-constant
1282  case tok::wide_char_constant:
1283  case tok::utf8_char_constant:
1284  case tok::utf16_char_constant:
1285  case tok::utf32_char_constant:
1286  Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
1287  ConsumeToken();
1288  break;
1289  case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
1290  case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
1291  case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
1292  case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
1293  case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
1294  case tok::kw_L__FUNCSIG__: // primary-expression: L__FUNCSIG__ [MS]
1295  case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
1296  Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
1297  ConsumeToken();
1298  break;
1299  case tok::string_literal: // primary-expression: string-literal
1300  case tok::wide_string_literal:
1301  case tok::utf8_string_literal:
1302  case tok::utf16_string_literal:
1303  case tok::utf32_string_literal:
1304  Res = ParseStringLiteralExpression(true);
1305  break;
1306  case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
1307  Res = ParseGenericSelectionExpression();
1308  break;
1309  case tok::kw___builtin_available:
1310  Res = ParseAvailabilityCheckExpr(Tok.getLocation());
1311  break;
1312  case tok::kw___builtin_va_arg:
1313  case tok::kw___builtin_offsetof:
1314  case tok::kw___builtin_choose_expr:
1315  case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1316  case tok::kw___builtin_convertvector:
1317  case tok::kw___builtin_COLUMN:
1318  case tok::kw___builtin_FILE:
1319  case tok::kw___builtin_FUNCTION:
1320  case tok::kw___builtin_LINE:
1321  case tok::kw___builtin_source_location:
1322  if (NotPrimaryExpression)
1323  *NotPrimaryExpression = true;
1324  // This parses the complete suffix; we can return early.
1325  return ParseBuiltinPrimaryExpression();
1326  case tok::kw___null:
1327  Res = Actions.ActOnGNUNullExpr(ConsumeToken());
1328  break;
1329 
1330  case tok::plusplus: // unary-expression: '++' unary-expression [C99]
1331  case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
1332  if (NotPrimaryExpression)
1333  *NotPrimaryExpression = true;
1334  // C++ [expr.unary] has:
1335  // unary-expression:
1336  // ++ cast-expression
1337  // -- cast-expression
1338  Token SavedTok = Tok;
1339  ConsumeToken();
1340 
1341  PreferredType.enterUnary(Actions, Tok.getLocation(), SavedTok.getKind(),
1342  SavedTok.getLocation());
1343  // One special case is implicitly handled here: if the preceding tokens are
1344  // an ambiguous cast expression, such as "(T())++", then we recurse to
1345  // determine whether the '++' is prefix or postfix.
1346  Res = ParseCastExpression(getLangOpts().CPlusPlus ?
1347  UnaryExprOnly : AnyCastExpr,
1348  /*isAddressOfOperand*/false, NotCastExpr,
1349  NotTypeCast);
1350  if (NotCastExpr) {
1351  // If we return with NotCastExpr = true, we must not consume any tokens,
1352  // so put the token back where we found it.
1353  assert(Res.isInvalid());
1354  UnconsumeToken(SavedTok);
1355  return ExprError();
1356  }
1357  if (!Res.isInvalid()) {
1358  Expr *Arg = Res.get();
1359  Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
1360  SavedKind, Arg);
1361  if (Res.isInvalid())
1362  Res = Actions.CreateRecoveryExpr(SavedTok.getLocation(),
1363  Arg->getEndLoc(), Arg);
1364  }
1365  return Res;
1366  }
1367  case tok::amp: { // unary-expression: '&' cast-expression
1368  if (NotPrimaryExpression)
1369  *NotPrimaryExpression = true;
1370  // Special treatment because of member pointers
1371  SourceLocation SavedLoc = ConsumeToken();
1372  PreferredType.enterUnary(Actions, Tok.getLocation(), tok::amp, SavedLoc);
1373 
1374  Res = ParseCastExpression(AnyCastExpr, /*isAddressOfOperand=*/true);
1375  if (!Res.isInvalid()) {
1376  Expr *Arg = Res.get();
1377  Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg);
1378  if (Res.isInvalid())
1379  Res = Actions.CreateRecoveryExpr(Tok.getLocation(), Arg->getEndLoc(),
1380  Arg);
1381  }
1382  return Res;
1383  }
1384 
1385  case tok::star: // unary-expression: '*' cast-expression
1386  case tok::plus: // unary-expression: '+' cast-expression
1387  case tok::minus: // unary-expression: '-' cast-expression
1388  case tok::tilde: // unary-expression: '~' cast-expression
1389  case tok::exclaim: // unary-expression: '!' cast-expression
1390  case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
1391  case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
1392  if (NotPrimaryExpression)
1393  *NotPrimaryExpression = true;
1394  SourceLocation SavedLoc = ConsumeToken();
1395  PreferredType.enterUnary(Actions, Tok.getLocation(), SavedKind, SavedLoc);
1396  Res = ParseCastExpression(AnyCastExpr);
1397  if (!Res.isInvalid()) {
1398  Expr *Arg = Res.get();
1399  Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg,
1400  isAddressOfOperand);
1401  if (Res.isInvalid())
1402  Res = Actions.CreateRecoveryExpr(SavedLoc, Arg->getEndLoc(), Arg);
1403  }
1404  return Res;
1405  }
1406 
1407  case tok::kw_co_await: { // unary-expression: 'co_await' cast-expression
1408  if (NotPrimaryExpression)
1409  *NotPrimaryExpression = true;
1410  SourceLocation CoawaitLoc = ConsumeToken();
1411  Res = ParseCastExpression(AnyCastExpr);
1412  if (!Res.isInvalid())
1413  Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1414  return Res;
1415  }
1416 
1417  case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1418  // __extension__ silences extension warnings in the subexpression.
1419  if (NotPrimaryExpression)
1420  *NotPrimaryExpression = true;
1421  ExtensionRAIIObject O(Diags); // Use RAII to do this.
1422  SourceLocation SavedLoc = ConsumeToken();
1423  Res = ParseCastExpression(AnyCastExpr);
1424  if (!Res.isInvalid())
1425  Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1426  return Res;
1427  }
1428  case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
1429  if (!getLangOpts().C11)
1430  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
1431  [[fallthrough]];
1432  case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
1433  case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
1434  // unary-expression: '__alignof' '(' type-name ')'
1435  case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
1436  // unary-expression: 'sizeof' '(' type-name ')'
1437  case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
1438  // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1439  case tok::kw___builtin_omp_required_simd_align:
1440  if (NotPrimaryExpression)
1441  *NotPrimaryExpression = true;
1442  AllowSuffix = false;
1443  Res = ParseUnaryExprOrTypeTraitExpression();
1444  break;
1445  case tok::ampamp: { // unary-expression: '&&' identifier
1446  if (NotPrimaryExpression)
1447  *NotPrimaryExpression = true;
1448  SourceLocation AmpAmpLoc = ConsumeToken();
1449  if (Tok.isNot(tok::identifier))
1450  return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1451 
1452  if (getCurScope()->getFnParent() == nullptr)
1453  return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1454 
1455  Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1456  LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1457  Tok.getLocation());
1458  Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1459  ConsumeToken();
1460  AllowSuffix = false;
1461  break;
1462  }
1463  case tok::kw_const_cast:
1464  case tok::kw_dynamic_cast:
1465  case tok::kw_reinterpret_cast:
1466  case tok::kw_static_cast:
1467  case tok::kw_addrspace_cast:
1468  if (NotPrimaryExpression)
1469  *NotPrimaryExpression = true;
1470  Res = ParseCXXCasts();
1471  break;
1472  case tok::kw___builtin_bit_cast:
1473  if (NotPrimaryExpression)
1474  *NotPrimaryExpression = true;
1475  Res = ParseBuiltinBitCast();
1476  break;
1477  case tok::kw_typeid:
1478  if (NotPrimaryExpression)
1479  *NotPrimaryExpression = true;
1480  Res = ParseCXXTypeid();
1481  break;
1482  case tok::kw___uuidof:
1483  if (NotPrimaryExpression)
1484  *NotPrimaryExpression = true;
1485  Res = ParseCXXUuidof();
1486  break;
1487  case tok::kw_this:
1488  Res = ParseCXXThis();
1489  break;
1490  case tok::kw___builtin_sycl_unique_stable_name:
1491  Res = ParseSYCLUniqueStableNameExpression();
1492  break;
1493 
1494  case tok::annot_typename:
1495  if (isStartOfObjCClassMessageMissingOpenBracket()) {
1497 
1498  // Fake up a Declarator to use with ActOnTypeName.
1499  DeclSpec DS(AttrFactory);
1500  DS.SetRangeStart(Tok.getLocation());
1501  DS.SetRangeEnd(Tok.getLastLoc());
1502 
1503  const char *PrevSpec = nullptr;
1504  unsigned DiagID;
1505  DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1506  PrevSpec, DiagID, Type,
1507  Actions.getASTContext().getPrintingPolicy());
1508 
1509  Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1511  TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1512  if (Ty.isInvalid())
1513  break;
1514 
1515  ConsumeAnnotationToken();
1516  Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1517  Ty.get(), nullptr);
1518  break;
1519  }
1520  [[fallthrough]];
1521 
1522  case tok::annot_decltype:
1523  case tok::kw_char:
1524  case tok::kw_wchar_t:
1525  case tok::kw_char8_t:
1526  case tok::kw_char16_t:
1527  case tok::kw_char32_t:
1528  case tok::kw_bool:
1529  case tok::kw_short:
1530  case tok::kw_int:
1531  case tok::kw_long:
1532  case tok::kw___int64:
1533  case tok::kw___int128:
1534  case tok::kw__ExtInt:
1535  case tok::kw__BitInt:
1536  case tok::kw_signed:
1537  case tok::kw_unsigned:
1538  case tok::kw_half:
1539  case tok::kw_float:
1540  case tok::kw_double:
1541  case tok::kw___bf16:
1542  case tok::kw__Float16:
1543  case tok::kw___float128:
1544  case tok::kw___ibm128:
1545  case tok::kw_void:
1546  case tok::kw_auto:
1547  case tok::kw_typename:
1548  case tok::kw_typeof:
1549  case tok::kw___vector:
1550 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1551 #include "clang/Basic/OpenCLImageTypes.def"
1552  {
1553  if (!getLangOpts().CPlusPlus) {
1554  Diag(Tok, diag::err_expected_expression);
1555  return ExprError();
1556  }
1557 
1558  // Everything henceforth is a postfix-expression.
1559  if (NotPrimaryExpression)
1560  *NotPrimaryExpression = true;
1561 
1562  if (SavedKind == tok::kw_typename) {
1563  // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1564  // typename-specifier braced-init-list
1566  return ExprError();
1567 
1568  if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1569  // We are trying to parse a simple-type-specifier but might not get such
1570  // a token after error recovery.
1571  return ExprError();
1572  }
1573 
1574  // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1575  // simple-type-specifier braced-init-list
1576  //
1577  DeclSpec DS(AttrFactory);
1578 
1579  ParseCXXSimpleTypeSpecifier(DS);
1580  if (Tok.isNot(tok::l_paren) &&
1581  (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1582  return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1583  << DS.getSourceRange());
1584 
1585  if (Tok.is(tok::l_brace))
1586  Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1587 
1588  Res = ParseCXXTypeConstructExpression(DS);
1589  break;
1590  }
1591 
1592  case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1593  // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1594  // (We can end up in this situation after tentative parsing.)
1596  return ExprError();
1597  if (!Tok.is(tok::annot_cxxscope))
1598  return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
1599  isTypeCast, isVectorLiteral,
1600  NotPrimaryExpression);
1601 
1602  Token Next = NextToken();
1603  if (Next.is(tok::annot_template_id)) {
1604  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1605  if (TemplateId->Kind == TNK_Type_template) {
1606  // We have a qualified template-id that we know refers to a
1607  // type, translate it into a type and continue parsing as a
1608  // cast expression.
1609  CXXScopeSpec SS;
1610  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1611  /*ObjectHasErrors=*/false,
1612  /*EnteringContext=*/false);
1613  AnnotateTemplateIdTokenAsType(SS, ImplicitTypenameContext::Yes);
1614  return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
1615  isTypeCast, isVectorLiteral,
1616  NotPrimaryExpression);
1617  }
1618  }
1619 
1620  // Parse as an id-expression.
1621  Res = ParseCXXIdExpression(isAddressOfOperand);
1622  break;
1623  }
1624 
1625  case tok::annot_template_id: { // [C++] template-id
1626  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1627  if (TemplateId->Kind == TNK_Type_template) {
1628  // We have a template-id that we know refers to a type,
1629  // translate it into a type and continue parsing as a cast
1630  // expression.
1631  CXXScopeSpec SS;
1632  AnnotateTemplateIdTokenAsType(SS, ImplicitTypenameContext::Yes);
1633  return ParseCastExpression(ParseKind, isAddressOfOperand,
1634  NotCastExpr, isTypeCast, isVectorLiteral,
1635  NotPrimaryExpression);
1636  }
1637 
1638  // Fall through to treat the template-id as an id-expression.
1639  [[fallthrough]];
1640  }
1641 
1642  case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1643  Res = ParseCXXIdExpression(isAddressOfOperand);
1644  break;
1645 
1646  case tok::coloncolon: {
1647  // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1648  // annotates the token, tail recurse.
1650  return ExprError();
1651  if (!Tok.is(tok::coloncolon))
1652  return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1653  isVectorLiteral, NotPrimaryExpression);
1654 
1655  // ::new -> [C++] new-expression
1656  // ::delete -> [C++] delete-expression
1657  SourceLocation CCLoc = ConsumeToken();
1658  if (Tok.is(tok::kw_new)) {
1659  if (NotPrimaryExpression)
1660  *NotPrimaryExpression = true;
1661  Res = ParseCXXNewExpression(true, CCLoc);
1662  AllowSuffix = false;
1663  break;
1664  }
1665  if (Tok.is(tok::kw_delete)) {
1666  if (NotPrimaryExpression)
1667  *NotPrimaryExpression = true;
1668  Res = ParseCXXDeleteExpression(true, CCLoc);
1669  AllowSuffix = false;
1670  break;
1671  }
1672 
1673  // This is not a type name or scope specifier, it is an invalid expression.
1674  Diag(CCLoc, diag::err_expected_expression);
1675  return ExprError();
1676  }
1677 
1678  case tok::kw_new: // [C++] new-expression
1679  if (NotPrimaryExpression)
1680  *NotPrimaryExpression = true;
1681  Res = ParseCXXNewExpression(false, Tok.getLocation());
1682  AllowSuffix = false;
1683  break;
1684 
1685  case tok::kw_delete: // [C++] delete-expression
1686  if (NotPrimaryExpression)
1687  *NotPrimaryExpression = true;
1688  Res = ParseCXXDeleteExpression(false, Tok.getLocation());
1689  AllowSuffix = false;
1690  break;
1691 
1692  case tok::kw_requires: // [C++2a] requires-expression
1693  Res = ParseRequiresExpression();
1694  AllowSuffix = false;
1695  break;
1696 
1697  case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1698  if (NotPrimaryExpression)
1699  *NotPrimaryExpression = true;
1700  Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1701  SourceLocation KeyLoc = ConsumeToken();
1702  BalancedDelimiterTracker T(*this, tok::l_paren);
1703 
1704  if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1705  return ExprError();
1706  // C++11 [expr.unary.noexcept]p1:
1707  // The noexcept operator determines whether the evaluation of its operand,
1708  // which is an unevaluated operand, can throw an exception.
1711  Res = ParseExpression();
1712 
1713  T.consumeClose();
1714 
1715  if (!Res.isInvalid())
1716  Res = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(), Res.get(),
1717  T.getCloseLocation());
1718  AllowSuffix = false;
1719  break;
1720  }
1721 
1722 #define TYPE_TRAIT(N,Spelling,K) \
1723  case tok::kw_##Spelling:
1724 #include "clang/Basic/TokenKinds.def"
1725  Res = ParseTypeTrait();
1726  break;
1727 
1728  case tok::kw___array_rank:
1729  case tok::kw___array_extent:
1730  if (NotPrimaryExpression)
1731  *NotPrimaryExpression = true;
1732  Res = ParseArrayTypeTrait();
1733  break;
1734 
1735  case tok::kw___is_lvalue_expr:
1736  case tok::kw___is_rvalue_expr:
1737  if (NotPrimaryExpression)
1738  *NotPrimaryExpression = true;
1739  Res = ParseExpressionTrait();
1740  break;
1741 
1742  case tok::at: {
1743  if (NotPrimaryExpression)
1744  *NotPrimaryExpression = true;
1745  SourceLocation AtLoc = ConsumeToken();
1746  return ParseObjCAtExpression(AtLoc);
1747  }
1748  case tok::caret:
1749  Res = ParseBlockLiteralExpression();
1750  break;
1751  case tok::code_completion: {
1752  cutOffParsing();
1754  PreferredType.get(Tok.getLocation()));
1755  return ExprError();
1756  }
1757 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
1758 #include "clang/Basic/TransformTypeTraits.def"
1759  // HACK: libstdc++ uses some of the transform-type-traits as alias
1760  // templates, so we need to work around this.
1761  if (!NextToken().is(tok::l_paren)) {
1762  Tok.setKind(tok::identifier);
1763  Diag(Tok, diag::ext_keyword_as_ident)
1764  << Tok.getIdentifierInfo()->getName() << 0;
1765  goto ParseIdentifier;
1766  }
1767  goto ExpectedExpression;
1768  case tok::l_square:
1769  if (getLangOpts().CPlusPlus11) {
1770  if (getLangOpts().ObjC) {
1771  // C++11 lambda expressions and Objective-C message sends both start with a
1772  // square bracket. There are three possibilities here:
1773  // we have a valid lambda expression, we have an invalid lambda
1774  // expression, or we have something that doesn't appear to be a lambda.
1775  // If we're in the last case, we fall back to ParseObjCMessageExpression.
1776  Res = TryParseLambdaExpression();
1777  if (!Res.isInvalid() && !Res.get()) {
1778  // We assume Objective-C++ message expressions are not
1779  // primary-expressions.
1780  if (NotPrimaryExpression)
1781  *NotPrimaryExpression = true;
1782  Res = ParseObjCMessageExpression();
1783  }
1784  break;
1785  }
1786  Res = ParseLambdaExpression();
1787  break;
1788  }
1789  if (getLangOpts().ObjC) {
1790  Res = ParseObjCMessageExpression();
1791  break;
1792  }
1793  [[fallthrough]];
1794  default:
1795  ExpectedExpression:
1796  NotCastExpr = true;
1797  return ExprError();
1798  }
1799 
1800  // Check to see whether Res is a function designator only. If it is and we
1801  // are compiling for OpenCL, we need to return an error as this implies
1802  // that the address of the function is being taken, which is illegal in CL.
1803 
1804  if (ParseKind == PrimaryExprOnly)
1805  // This is strictly a primary-expression - no postfix-expr pieces should be
1806  // parsed.
1807  return Res;
1808 
1809  if (!AllowSuffix) {
1810  // FIXME: Don't parse a primary-expression suffix if we encountered a parse
1811  // error already.
1812  if (Res.isInvalid())
1813  return Res;
1814 
1815  switch (Tok.getKind()) {
1816  case tok::l_square:
1817  case tok::l_paren:
1818  case tok::plusplus:
1819  case tok::minusminus:
1820  // "expected ';'" or similar is probably the right diagnostic here. Let
1821  // the caller decide what to do.
1822  if (Tok.isAtStartOfLine())
1823  return Res;
1824 
1825  [[fallthrough]];
1826  case tok::period:
1827  case tok::arrow:
1828  break;
1829 
1830  default:
1831  return Res;
1832  }
1833 
1834  // This was a unary-expression for which a postfix-expression suffix is
1835  // not permitted by the grammar (eg, a sizeof expression or
1836  // new-expression or similar). Diagnose but parse the suffix anyway.
1837  Diag(Tok.getLocation(), diag::err_postfix_after_unary_requires_parens)
1838  << Tok.getKind() << Res.get()->getSourceRange()
1839  << FixItHint::CreateInsertion(Res.get()->getBeginLoc(), "(")
1840  << FixItHint::CreateInsertion(PP.getLocForEndOfToken(PrevTokLocation),
1841  ")");
1842  }
1843 
1844  // These can be followed by postfix-expr pieces.
1845  PreferredType = SavedType;
1846  Res = ParsePostfixExpressionSuffix(Res);
1847  if (getLangOpts().OpenCL &&
1848  !getActions().getOpenCLOptions().isAvailableOption(
1849  "__cl_clang_function_pointers", getLangOpts()))
1850  if (Expr *PostfixExpr = Res.get()) {
1851  QualType Ty = PostfixExpr->getType();
1852  if (!Ty.isNull() && Ty->isFunctionType()) {
1853  Diag(PostfixExpr->getExprLoc(),
1854  diag::err_opencl_taking_function_address_parser);
1855  return ExprError();
1856  }
1857  }
1858 
1859  return Res;
1860 }
1861 
1862 /// Once the leading part of a postfix-expression is parsed, this
1863 /// method parses any suffixes that apply.
1864 ///
1865 /// \verbatim
1866 /// postfix-expression: [C99 6.5.2]
1867 /// primary-expression
1868 /// postfix-expression '[' expression ']'
1869 /// postfix-expression '[' braced-init-list ']'
1870 /// postfix-expression '[' expression-list [opt] ']' [C++2b 12.4.5]
1871 /// postfix-expression '(' argument-expression-list[opt] ')'
1872 /// postfix-expression '.' identifier
1873 /// postfix-expression '->' identifier
1874 /// postfix-expression '++'
1875 /// postfix-expression '--'
1876 /// '(' type-name ')' '{' initializer-list '}'
1877 /// '(' type-name ')' '{' initializer-list ',' '}'
1878 ///
1879 /// argument-expression-list: [C99 6.5.2]
1880 /// argument-expression ...[opt]
1881 /// argument-expression-list ',' assignment-expression ...[opt]
1882 /// \endverbatim
1883 ExprResult
1884 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1885  // Now that the primary-expression piece of the postfix-expression has been
1886  // parsed, see if there are any postfix-expression pieces here.
1887  SourceLocation Loc;
1888  auto SavedType = PreferredType;
1889  while (true) {
1890  // Each iteration relies on preferred type for the whole expression.
1891  PreferredType = SavedType;
1892  switch (Tok.getKind()) {
1893  case tok::code_completion:
1894  if (InMessageExpression)
1895  return LHS;
1896 
1897  cutOffParsing();
1899  getCurScope(), LHS, PreferredType.get(Tok.getLocation()));
1900  return ExprError();
1901 
1902  case tok::identifier:
1903  // If we see identifier: after an expression, and we're not already in a
1904  // message send, then this is probably a message send with a missing
1905  // opening bracket '['.
1906  if (getLangOpts().ObjC && !InMessageExpression &&
1907  (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1908  LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1909  nullptr, LHS.get());
1910  break;
1911  }
1912  // Fall through; this isn't a message send.
1913  [[fallthrough]];
1914 
1915  default: // Not a postfix-expression suffix.
1916  return LHS;
1917  case tok::l_square: { // postfix-expression: p-e '[' expression ']'
1918  // If we have a array postfix expression that starts on a new line and
1919  // Objective-C is enabled, it is highly likely that the user forgot a
1920  // semicolon after the base expression and that the array postfix-expr is
1921  // actually another message send. In this case, do some look-ahead to see
1922  // if the contents of the square brackets are obviously not a valid
1923  // expression and recover by pretending there is no suffix.
1924  if (getLangOpts().ObjC && Tok.isAtStartOfLine() &&
1925  isSimpleObjCMessageExpression())
1926  return LHS;
1927 
1928  // Reject array indices starting with a lambda-expression. '[[' is
1929  // reserved for attributes.
1930  if (CheckProhibitedCXX11Attribute()) {
1931  (void)Actions.CorrectDelayedTyposInExpr(LHS);
1932  return ExprError();
1933  }
1934  BalancedDelimiterTracker T(*this, tok::l_square);
1935  T.consumeOpen();
1936  Loc = T.getOpenLocation();
1937  ExprResult Length, Stride;
1938  SourceLocation ColonLocFirst, ColonLocSecond;
1939  ExprVector ArgExprs;
1940  bool HasError = false;
1941  PreferredType.enterSubscript(Actions, Tok.getLocation(), LHS.get());
1942 
1943  // We try to parse a list of indexes in all language mode first
1944  // and, in we find 0 or one index, we try to parse an OpenMP array
1945  // section. This allow us to support C++2b multi dimensional subscript and
1946  // OpenMp sections in the same language mode.
1947  if (!getLangOpts().OpenMP || Tok.isNot(tok::colon)) {
1948  if (!getLangOpts().CPlusPlus2b) {
1949  ExprResult Idx;
1950  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1951  Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1952  Idx = ParseBraceInitializer();
1953  } else {
1954  Idx = ParseExpression(); // May be a comma expression
1955  }
1956  LHS = Actions.CorrectDelayedTyposInExpr(LHS);
1957  Idx = Actions.CorrectDelayedTyposInExpr(Idx);
1958  if (Idx.isInvalid()) {
1959  HasError = true;
1960  } else {
1961  ArgExprs.push_back(Idx.get());
1962  }
1963  } else if (Tok.isNot(tok::r_square)) {
1964  if (ParseExpressionList(ArgExprs)) {
1965  LHS = Actions.CorrectDelayedTyposInExpr(LHS);
1966  HasError = true;
1967  }
1968  }
1969  }
1970 
1971  if (ArgExprs.size() <= 1 && getLangOpts().OpenMP) {
1972  ColonProtectionRAIIObject RAII(*this);
1973  if (Tok.is(tok::colon)) {
1974  // Consume ':'
1975  ColonLocFirst = ConsumeToken();
1976  if (Tok.isNot(tok::r_square) &&
1977  (getLangOpts().OpenMP < 50 ||
1978  ((Tok.isNot(tok::colon) && getLangOpts().OpenMP >= 50)))) {
1979  Length = ParseExpression();
1980  Length = Actions.CorrectDelayedTyposInExpr(Length);
1981  }
1982  }
1983  if (getLangOpts().OpenMP >= 50 &&
1984  (OMPClauseKind == llvm::omp::Clause::OMPC_to ||
1985  OMPClauseKind == llvm::omp::Clause::OMPC_from) &&
1986  Tok.is(tok::colon)) {
1987  // Consume ':'
1988  ColonLocSecond = ConsumeToken();
1989  if (Tok.isNot(tok::r_square)) {
1990  Stride = ParseExpression();
1991  }
1992  }
1993  }
1994 
1995  SourceLocation RLoc = Tok.getLocation();
1996  LHS = Actions.CorrectDelayedTyposInExpr(LHS);
1997 
1998  if (!LHS.isInvalid() && !HasError && !Length.isInvalid() &&
1999  !Stride.isInvalid() && Tok.is(tok::r_square)) {
2000  if (ColonLocFirst.isValid() || ColonLocSecond.isValid()) {
2001  LHS = Actions.ActOnOMPArraySectionExpr(
2002  LHS.get(), Loc, ArgExprs.empty() ? nullptr : ArgExprs[0],
2003  ColonLocFirst, ColonLocSecond, Length.get(), Stride.get(), RLoc);
2004  } else {
2005  LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
2006  ArgExprs, RLoc);
2007  }
2008  } else {
2009  LHS = ExprError();
2010  }
2011 
2012  // Match the ']'.
2013  T.consumeClose();
2014  break;
2015  }
2016 
2017  case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
2018  case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
2019  // '(' argument-expression-list[opt] ')'
2020  tok::TokenKind OpKind = Tok.getKind();
2021  InMessageExpressionRAIIObject InMessage(*this, false);
2022 
2023  Expr *ExecConfig = nullptr;
2024 
2025  BalancedDelimiterTracker PT(*this, tok::l_paren);
2026 
2027  if (OpKind == tok::lesslessless) {
2028  ExprVector ExecConfigExprs;
2029  SourceLocation OpenLoc = ConsumeToken();
2030 
2031  if (ParseSimpleExpressionList(ExecConfigExprs)) {
2032  (void)Actions.CorrectDelayedTyposInExpr(LHS);
2033  LHS = ExprError();
2034  }
2035 
2036  SourceLocation CloseLoc;
2037  if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
2038  } else if (LHS.isInvalid()) {
2039  SkipUntil(tok::greatergreatergreater, StopAtSemi);
2040  } else {
2041  // There was an error closing the brackets
2042  Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
2043  Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
2044  SkipUntil(tok::greatergreatergreater, StopAtSemi);
2045  LHS = ExprError();
2046  }
2047 
2048  if (!LHS.isInvalid()) {
2049  if (ExpectAndConsume(tok::l_paren))
2050  LHS = ExprError();
2051  else
2052  Loc = PrevTokLocation;
2053  }
2054 
2055  if (!LHS.isInvalid()) {
2056  ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
2057  OpenLoc,
2058  ExecConfigExprs,
2059  CloseLoc);
2060  if (ECResult.isInvalid())
2061  LHS = ExprError();
2062  else
2063  ExecConfig = ECResult.get();
2064  }
2065  } else {
2066  PT.consumeOpen();
2067  Loc = PT.getOpenLocation();
2068  }
2069 
2070  ExprVector ArgExprs;
2071  auto RunSignatureHelp = [&]() -> QualType {
2072  QualType PreferredType = Actions.ProduceCallSignatureHelp(
2073  LHS.get(), ArgExprs, PT.getOpenLocation());
2074  CalledSignatureHelp = true;
2075  return PreferredType;
2076  };
2077  if (OpKind == tok::l_paren || !LHS.isInvalid()) {
2078  if (Tok.isNot(tok::r_paren)) {
2079  if (ParseExpressionList(ArgExprs, [&] {
2080  PreferredType.enterFunctionArgument(Tok.getLocation(),
2081  RunSignatureHelp);
2082  })) {
2083  (void)Actions.CorrectDelayedTyposInExpr(LHS);
2084  // If we got an error when parsing expression list, we don't call
2085  // the CodeCompleteCall handler inside the parser. So call it here
2086  // to make sure we get overload suggestions even when we are in the
2087  // middle of a parameter.
2088  if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
2089  RunSignatureHelp();
2090  LHS = ExprError();
2091  } else if (LHS.isInvalid()) {
2092  for (auto &E : ArgExprs)
2093  Actions.CorrectDelayedTyposInExpr(E);
2094  }
2095  }
2096  }
2097 
2098  // Match the ')'.
2099  if (LHS.isInvalid()) {
2100  SkipUntil(tok::r_paren, StopAtSemi);
2101  } else if (Tok.isNot(tok::r_paren)) {
2102  bool HadDelayedTypo = false;
2103  if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
2104  HadDelayedTypo = true;
2105  for (auto &E : ArgExprs)
2106  if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
2107  HadDelayedTypo = true;
2108  // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
2109  // instead of PT.consumeClose() to avoid emitting extra diagnostics for
2110  // the unmatched l_paren.
2111  if (HadDelayedTypo)
2112  SkipUntil(tok::r_paren, StopAtSemi);
2113  else
2114  PT.consumeClose();
2115  LHS = ExprError();
2116  } else {
2117  Expr *Fn = LHS.get();
2118  SourceLocation RParLoc = Tok.getLocation();
2119  LHS = Actions.ActOnCallExpr(getCurScope(), Fn, Loc, ArgExprs, RParLoc,
2120  ExecConfig);
2121  if (LHS.isInvalid()) {
2122  ArgExprs.insert(ArgExprs.begin(), Fn);
2123  LHS =
2124  Actions.CreateRecoveryExpr(Fn->getBeginLoc(), RParLoc, ArgExprs);
2125  }
2126  PT.consumeClose();
2127  }
2128 
2129  break;
2130  }
2131  case tok::arrow:
2132  case tok::period: {
2133  // postfix-expression: p-e '->' template[opt] id-expression
2134  // postfix-expression: p-e '.' template[opt] id-expression
2135  tok::TokenKind OpKind = Tok.getKind();
2136  SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
2137 
2138  CXXScopeSpec SS;
2139  ParsedType ObjectType;
2140  bool MayBePseudoDestructor = false;
2141  Expr* OrigLHS = !LHS.isInvalid() ? LHS.get() : nullptr;
2142 
2143  PreferredType.enterMemAccess(Actions, Tok.getLocation(), OrigLHS);
2144 
2145  if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
2146  Expr *Base = OrigLHS;
2147  const Type* BaseType = Base->getType().getTypePtrOrNull();
2148  if (BaseType && Tok.is(tok::l_paren) &&
2149  (BaseType->isFunctionType() ||
2150  BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
2151  Diag(OpLoc, diag::err_function_is_not_record)
2152  << OpKind << Base->getSourceRange()
2153  << FixItHint::CreateRemoval(OpLoc);
2154  return ParsePostfixExpressionSuffix(Base);
2155  }
2156 
2157  LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base, OpLoc,
2158  OpKind, ObjectType,
2159  MayBePseudoDestructor);
2160  if (LHS.isInvalid()) {
2161  // Clang will try to perform expression based completion as a
2162  // fallback, which is confusing in case of member references. So we
2163  // stop here without any completions.
2164  if (Tok.is(tok::code_completion)) {
2165  cutOffParsing();
2166  return ExprError();
2167  }
2168  break;
2169  }
2170  ParseOptionalCXXScopeSpecifier(
2171  SS, ObjectType, LHS.get() && LHS.get()->containsErrors(),
2172  /*EnteringContext=*/false, &MayBePseudoDestructor);
2173  if (SS.isNotEmpty())
2174  ObjectType = nullptr;
2175  }
2176 
2177  if (Tok.is(tok::code_completion)) {
2178  tok::TokenKind CorrectedOpKind =
2179  OpKind == tok::arrow ? tok::period : tok::arrow;
2180  ExprResult CorrectedLHS(/*Invalid=*/true);
2181  if (getLangOpts().CPlusPlus && OrigLHS) {
2182  // FIXME: Creating a TentativeAnalysisScope from outside Sema is a
2183  // hack.
2184  Sema::TentativeAnalysisScope Trap(Actions);
2185  CorrectedLHS = Actions.ActOnStartCXXMemberReference(
2186  getCurScope(), OrigLHS, OpLoc, CorrectedOpKind, ObjectType,
2187  MayBePseudoDestructor);
2188  }
2189 
2190  Expr *Base = LHS.get();
2191  Expr *CorrectedBase = CorrectedLHS.get();
2192  if (!CorrectedBase && !getLangOpts().CPlusPlus)
2193  CorrectedBase = Base;
2194 
2195  // Code completion for a member access expression.
2196  cutOffParsing();
2198  getCurScope(), Base, CorrectedBase, OpLoc, OpKind == tok::arrow,
2199  Base && ExprStatementTokLoc == Base->getBeginLoc(),
2200  PreferredType.get(Tok.getLocation()));
2201 
2202  return ExprError();
2203  }
2204 
2205  if (MayBePseudoDestructor && !LHS.isInvalid()) {
2206  LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
2207  ObjectType);
2208  break;
2209  }
2210 
2211  // Either the action has told us that this cannot be a
2212  // pseudo-destructor expression (based on the type of base
2213  // expression), or we didn't see a '~' in the right place. We
2214  // can still parse a destructor name here, but in that case it
2215  // names a real destructor.
2216  // Allow explicit constructor calls in Microsoft mode.
2217  // FIXME: Add support for explicit call of template constructor.
2218  SourceLocation TemplateKWLoc;
2219  UnqualifiedId Name;
2220  if (getLangOpts().ObjC && OpKind == tok::period &&
2221  Tok.is(tok::kw_class)) {
2222  // Objective-C++:
2223  // After a '.' in a member access expression, treat the keyword
2224  // 'class' as if it were an identifier.
2225  //
2226  // This hack allows property access to the 'class' method because it is
2227  // such a common method name. For other C++ keywords that are
2228  // Objective-C method names, one must use the message send syntax.
2230  SourceLocation Loc = ConsumeToken();
2231  Name.setIdentifier(Id, Loc);
2232  } else if (ParseUnqualifiedId(
2233  SS, ObjectType, LHS.get() && LHS.get()->containsErrors(),
2234  /*EnteringContext=*/false,
2235  /*AllowDestructorName=*/true,
2236  /*AllowConstructorName=*/
2237  getLangOpts().MicrosoftExt && SS.isNotEmpty(),
2238  /*AllowDeductionGuide=*/false, &TemplateKWLoc, Name)) {
2239  (void)Actions.CorrectDelayedTyposInExpr(LHS);
2240  LHS = ExprError();
2241  }
2242 
2243  if (!LHS.isInvalid())
2244  LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
2245  OpKind, SS, TemplateKWLoc, Name,
2246  CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
2247  : nullptr);
2248  if (!LHS.isInvalid()) {
2249  if (Tok.is(tok::less))
2250  checkPotentialAngleBracket(LHS);
2251  } else if (OrigLHS && Name.isValid()) {
2252  // Preserve the LHS if the RHS is an invalid member.
2253  LHS = Actions.CreateRecoveryExpr(OrigLHS->getBeginLoc(),
2254  Name.getEndLoc(), {OrigLHS});
2255  }
2256  break;
2257  }
2258  case tok::plusplus: // postfix-expression: postfix-expression '++'
2259  case tok::minusminus: // postfix-expression: postfix-expression '--'
2260  if (!LHS.isInvalid()) {
2261  Expr *Arg = LHS.get();
2262  LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
2263  Tok.getKind(), Arg);
2264  if (LHS.isInvalid())
2265  LHS = Actions.CreateRecoveryExpr(Arg->getBeginLoc(),
2266  Tok.getLocation(), Arg);
2267  }
2268  ConsumeToken();
2269  break;
2270  }
2271  }
2272 }
2273 
2274 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
2275 /// vec_step and we are at the start of an expression or a parenthesized
2276 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
2277 /// expression (isCastExpr == false) or the type (isCastExpr == true).
2278 ///
2279 /// \verbatim
2280 /// unary-expression: [C99 6.5.3]
2281 /// 'sizeof' unary-expression
2282 /// 'sizeof' '(' type-name ')'
2283 /// [GNU] '__alignof' unary-expression
2284 /// [GNU] '__alignof' '(' type-name ')'
2285 /// [C11] '_Alignof' '(' type-name ')'
2286 /// [C++0x] 'alignof' '(' type-id ')'
2287 ///
2288 /// [GNU] typeof-specifier:
2289 /// typeof ( expressions )
2290 /// typeof ( type-name )
2291 /// [GNU/C++] typeof unary-expression
2292 /// [C2x] typeof-specifier:
2293 /// typeof '(' typeof-specifier-argument ')'
2294 /// typeof_unqual '(' typeof-specifier-argument ')'
2295 ///
2296 /// typeof-specifier-argument:
2297 /// expression
2298 /// type-name
2299 ///
2300 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
2301 /// vec_step ( expressions )
2302 /// vec_step ( type-name )
2303 /// \endverbatim
2304 ExprResult
2305 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
2306  bool &isCastExpr,
2307  ParsedType &CastTy,
2308  SourceRange &CastRange) {
2309 
2310  assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual, tok::kw_sizeof,
2311  tok::kw___alignof, tok::kw_alignof, tok::kw__Alignof,
2312  tok::kw_vec_step,
2313  tok::kw___builtin_omp_required_simd_align) &&
2314  "Not a typeof/sizeof/alignof/vec_step expression!");
2315 
2317 
2318  // If the operand doesn't start with an '(', it must be an expression.
2319  if (Tok.isNot(tok::l_paren)) {
2320  // If construct allows a form without parenthesis, user may forget to put
2321  // pathenthesis around type name.
2322  if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
2323  tok::kw__Alignof)) {
2324  if (isTypeIdUnambiguously()) {
2325  DeclSpec DS(AttrFactory);
2326  ParseSpecifierQualifierList(DS);
2327  Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
2329  ParseDeclarator(DeclaratorInfo);
2330 
2331  SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
2332  SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
2333  if (LParenLoc.isInvalid() || RParenLoc.isInvalid()) {
2334  Diag(OpTok.getLocation(),
2335  diag::err_expected_parentheses_around_typename)
2336  << OpTok.getName();
2337  } else {
2338  Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
2339  << OpTok.getName() << FixItHint::CreateInsertion(LParenLoc, "(")
2340  << FixItHint::CreateInsertion(RParenLoc, ")");
2341  }
2342  isCastExpr = true;
2343  return ExprEmpty();
2344  }
2345  }
2346 
2347  isCastExpr = false;
2348  if (OpTok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual) &&
2349  !getLangOpts().CPlusPlus) {
2350  Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
2351  << tok::l_paren;
2352  return ExprError();
2353  }
2354 
2355  Operand = ParseCastExpression(UnaryExprOnly);
2356  } else {
2357  // If it starts with a '(', we know that it is either a parenthesized
2358  // type-name, or it is a unary-expression that starts with a compound
2359  // literal, or starts with a primary-expression that is a parenthesized
2360  // expression.
2361  ParenParseOption ExprType = CastExpr;
2362  SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
2363 
2364  Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
2365  false, CastTy, RParenLoc);
2366  CastRange = SourceRange(LParenLoc, RParenLoc);
2367 
2368  // If ParseParenExpression parsed a '(typename)' sequence only, then this is
2369  // a type.
2370  if (ExprType == CastExpr) {
2371  isCastExpr = true;
2372  return ExprEmpty();
2373  }
2374 
2375  if (getLangOpts().CPlusPlus ||
2376  !OpTok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual)) {
2377  // GNU typeof in C requires the expression to be parenthesized. Not so for
2378  // sizeof/alignof or in C++. Therefore, the parenthesized expression is
2379  // the start of a unary-expression, but doesn't include any postfix
2380  // pieces. Parse these now if present.
2381  if (!Operand.isInvalid())
2382  Operand = ParsePostfixExpressionSuffix(Operand.get());
2383  }
2384  }
2385 
2386  // If we get here, the operand to the typeof/sizeof/alignof was an expression.
2387  isCastExpr = false;
2388  return Operand;
2389 }
2390 
2391 /// Parse a __builtin_sycl_unique_stable_name expression. Accepts a type-id as
2392 /// a parameter.
2393 ExprResult Parser::ParseSYCLUniqueStableNameExpression() {
2394  assert(Tok.is(tok::kw___builtin_sycl_unique_stable_name) &&
2395  "Not __builtin_sycl_unique_stable_name");
2396 
2397  SourceLocation OpLoc = ConsumeToken();
2398  BalancedDelimiterTracker T(*this, tok::l_paren);
2399 
2400  // __builtin_sycl_unique_stable_name expressions are always parenthesized.
2401  if (T.expectAndConsume(diag::err_expected_lparen_after,
2402  "__builtin_sycl_unique_stable_name"))
2403  return ExprError();
2404 
2405  TypeResult Ty = ParseTypeName();
2406 
2407  if (Ty.isInvalid()) {
2408  T.skipToEnd();
2409  return ExprError();
2410  }
2411 
2412  if (T.consumeClose())
2413  return ExprError();
2414 
2415  return Actions.ActOnSYCLUniqueStableNameExpr(OpLoc, T.getOpenLocation(),
2416  T.getCloseLocation(), Ty.get());
2417 }
2418 
2419 /// Parse a sizeof or alignof expression.
2420 ///
2421 /// \verbatim
2422 /// unary-expression: [C99 6.5.3]
2423 /// 'sizeof' unary-expression
2424 /// 'sizeof' '(' type-name ')'
2425 /// [C++11] 'sizeof' '...' '(' identifier ')'
2426 /// [GNU] '__alignof' unary-expression
2427 /// [GNU] '__alignof' '(' type-name ')'
2428 /// [C11] '_Alignof' '(' type-name ')'
2429 /// [C++11] 'alignof' '(' type-id ')'
2430 /// \endverbatim
2431 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
2432  assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
2433  tok::kw__Alignof, tok::kw_vec_step,
2434  tok::kw___builtin_omp_required_simd_align) &&
2435  "Not a sizeof/alignof/vec_step expression!");
2436  Token OpTok = Tok;
2437  ConsumeToken();
2438 
2439  // [C++11] 'sizeof' '...' '(' identifier ')'
2440  if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
2441  SourceLocation EllipsisLoc = ConsumeToken();
2442  SourceLocation LParenLoc, RParenLoc;
2443  IdentifierInfo *Name = nullptr;
2444  SourceLocation NameLoc;
2445  if (Tok.is(tok::l_paren)) {
2446  BalancedDelimiterTracker T(*this, tok::l_paren);
2447  T.consumeOpen();
2448  LParenLoc = T.getOpenLocation();
2449  if (Tok.is(tok::identifier)) {
2450  Name = Tok.getIdentifierInfo();
2451  NameLoc = ConsumeToken();
2452  T.consumeClose();
2453  RParenLoc = T.getCloseLocation();
2454  if (RParenLoc.isInvalid())
2455  RParenLoc = PP.getLocForEndOfToken(NameLoc);
2456  } else {
2457  Diag(Tok, diag::err_expected_parameter_pack);
2458  SkipUntil(tok::r_paren, StopAtSemi);
2459  }
2460  } else if (Tok.is(tok::identifier)) {
2461  Name = Tok.getIdentifierInfo();
2462  NameLoc = ConsumeToken();
2463  LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
2464  RParenLoc = PP.getLocForEndOfToken(NameLoc);
2465  Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
2466  << Name
2467  << FixItHint::CreateInsertion(LParenLoc, "(")
2468  << FixItHint::CreateInsertion(RParenLoc, ")");
2469  } else {
2470  Diag(Tok, diag::err_sizeof_parameter_pack);
2471  }
2472 
2473  if (!Name)
2474  return ExprError();
2475 
2479 
2480  return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
2481  OpTok.getLocation(),
2482  *Name, NameLoc,
2483  RParenLoc);
2484  }
2485 
2486  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2487  Diag(OpTok, diag::warn_cxx98_compat_alignof);
2488 
2492 
2493  bool isCastExpr;
2494  ParsedType CastTy;
2495  SourceRange CastRange;
2496  ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
2497  isCastExpr,
2498  CastTy,
2499  CastRange);
2500 
2501  UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
2502  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2503  ExprKind = UETT_AlignOf;
2504  else if (OpTok.is(tok::kw___alignof))
2505  ExprKind = UETT_PreferredAlignOf;
2506  else if (OpTok.is(tok::kw_vec_step))
2507  ExprKind = UETT_VecStep;
2508  else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
2509  ExprKind = UETT_OpenMPRequiredSimdAlign;
2510 
2511  if (isCastExpr)
2512  return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2513  ExprKind,
2514  /*IsType=*/true,
2515  CastTy.getAsOpaquePtr(),
2516  CastRange);
2517 
2518  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2519  Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
2520 
2521  // If we get here, the operand to the sizeof/alignof was an expression.
2522  if (!Operand.isInvalid())
2524  ExprKind,
2525  /*IsType=*/false,
2526  Operand.get(),
2527  CastRange);
2528  return Operand;
2529 }
2530 
2531 /// ParseBuiltinPrimaryExpression
2532 ///
2533 /// \verbatim
2534 /// primary-expression: [C99 6.5.1]
2535 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
2536 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
2537 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
2538 /// assign-expr ')'
2539 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
2540 /// [GNU] '__builtin_FILE' '(' ')'
2541 /// [GNU] '__builtin_FUNCTION' '(' ')'
2542 /// [GNU] '__builtin_LINE' '(' ')'
2543 /// [CLANG] '__builtin_COLUMN' '(' ')'
2544 /// [GNU] '__builtin_source_location' '(' ')'
2545 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
2546 ///
2547 /// [GNU] offsetof-member-designator:
2548 /// [GNU] identifier
2549 /// [GNU] offsetof-member-designator '.' identifier
2550 /// [GNU] offsetof-member-designator '[' expression ']'
2551 /// \endverbatim
2552 ExprResult Parser::ParseBuiltinPrimaryExpression() {
2553  ExprResult Res;
2554  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
2555 
2556  tok::TokenKind T = Tok.getKind();
2557  SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
2558 
2559  // All of these start with an open paren.
2560  if (Tok.isNot(tok::l_paren))
2561  return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
2562  << tok::l_paren);
2563 
2564  BalancedDelimiterTracker PT(*this, tok::l_paren);
2565  PT.consumeOpen();
2566 
2567  // TODO: Build AST.
2568 
2569  switch (T) {
2570  default: llvm_unreachable("Not a builtin primary expression!");
2571  case tok::kw___builtin_va_arg: {
2573 
2574  if (ExpectAndConsume(tok::comma)) {
2575  SkipUntil(tok::r_paren, StopAtSemi);
2576  Expr = ExprError();
2577  }
2578 
2579  TypeResult Ty = ParseTypeName();
2580 
2581  if (Tok.isNot(tok::r_paren)) {
2582  Diag(Tok, diag::err_expected) << tok::r_paren;
2583  Expr = ExprError();
2584  }
2585 
2586  if (Expr.isInvalid() || Ty.isInvalid())
2587  Res = ExprError();
2588  else
2589  Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
2590  break;
2591  }
2592  case tok::kw___builtin_offsetof: {
2594  TypeResult Ty = ParseTypeName();
2595  if (Ty.isInvalid()) {
2596  SkipUntil(tok::r_paren, StopAtSemi);
2597  return ExprError();
2598  }
2599 
2600  if (ExpectAndConsume(tok::comma)) {
2601  SkipUntil(tok::r_paren, StopAtSemi);
2602  return ExprError();
2603  }
2604 
2605  // We must have at least one identifier here.
2606  if (Tok.isNot(tok::identifier)) {
2607  Diag(Tok, diag::err_expected) << tok::identifier;
2608  SkipUntil(tok::r_paren, StopAtSemi);
2609  return ExprError();
2610  }
2611 
2612  // Keep track of the various subcomponents we see.
2614 
2615  Comps.push_back(Sema::OffsetOfComponent());
2616  Comps.back().isBrackets = false;
2617  Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2618  Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2619 
2620  // FIXME: This loop leaks the index expressions on error.
2621  while (true) {
2622  if (Tok.is(tok::period)) {
2623  // offsetof-member-designator: offsetof-member-designator '.' identifier
2624  Comps.push_back(Sema::OffsetOfComponent());
2625  Comps.back().isBrackets = false;
2626  Comps.back().LocStart = ConsumeToken();
2627 
2628  if (Tok.isNot(tok::identifier)) {
2629  Diag(Tok, diag::err_expected) << tok::identifier;
2630  SkipUntil(tok::r_paren, StopAtSemi);
2631  return ExprError();
2632  }
2633  Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2634  Comps.back().LocEnd = ConsumeToken();
2635 
2636  } else if (Tok.is(tok::l_square)) {
2637  if (CheckProhibitedCXX11Attribute())
2638  return ExprError();
2639 
2640  // offsetof-member-designator: offsetof-member-design '[' expression ']'
2641  Comps.push_back(Sema::OffsetOfComponent());
2642  Comps.back().isBrackets = true;
2643  BalancedDelimiterTracker ST(*this, tok::l_square);
2644  ST.consumeOpen();
2645  Comps.back().LocStart = ST.getOpenLocation();
2646  Res = ParseExpression();
2647  if (Res.isInvalid()) {
2648  SkipUntil(tok::r_paren, StopAtSemi);
2649  return Res;
2650  }
2651  Comps.back().U.E = Res.get();
2652 
2653  ST.consumeClose();
2654  Comps.back().LocEnd = ST.getCloseLocation();
2655  } else {
2656  if (Tok.isNot(tok::r_paren)) {
2657  PT.consumeClose();
2658  Res = ExprError();
2659  } else if (Ty.isInvalid()) {
2660  Res = ExprError();
2661  } else {
2662  PT.consumeClose();
2663  Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2664  Ty.get(), Comps,
2665  PT.getCloseLocation());
2666  }
2667  break;
2668  }
2669  }
2670  break;
2671  }
2672  case tok::kw___builtin_choose_expr: {
2674  if (Cond.isInvalid()) {
2675  SkipUntil(tok::r_paren, StopAtSemi);
2676  return Cond;
2677  }
2678  if (ExpectAndConsume(tok::comma)) {
2679  SkipUntil(tok::r_paren, StopAtSemi);
2680  return ExprError();
2681  }
2682 
2684  if (Expr1.isInvalid()) {
2685  SkipUntil(tok::r_paren, StopAtSemi);
2686  return Expr1;
2687  }
2688  if (ExpectAndConsume(tok::comma)) {
2689  SkipUntil(tok::r_paren, StopAtSemi);
2690  return ExprError();
2691  }
2692 
2694  if (Expr2.isInvalid()) {
2695  SkipUntil(tok::r_paren, StopAtSemi);
2696  return Expr2;
2697  }
2698  if (Tok.isNot(tok::r_paren)) {
2699  Diag(Tok, diag::err_expected) << tok::r_paren;
2700  return ExprError();
2701  }
2702  Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2703  Expr2.get(), ConsumeParen());
2704  break;
2705  }
2706  case tok::kw___builtin_astype: {
2707  // The first argument is an expression to be converted, followed by a comma.
2709  if (Expr.isInvalid()) {
2710  SkipUntil(tok::r_paren, StopAtSemi);
2711  return ExprError();
2712  }
2713 
2714  if (ExpectAndConsume(tok::comma)) {
2715  SkipUntil(tok::r_paren, StopAtSemi);
2716  return ExprError();
2717  }
2718 
2719  // Second argument is the type to bitcast to.
2720  TypeResult DestTy = ParseTypeName();
2721  if (DestTy.isInvalid())
2722  return ExprError();
2723 
2724  // Attempt to consume the r-paren.
2725  if (Tok.isNot(tok::r_paren)) {
2726  Diag(Tok, diag::err_expected) << tok::r_paren;
2727  SkipUntil(tok::r_paren, StopAtSemi);
2728  return ExprError();
2729  }
2730 
2731  Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2732  ConsumeParen());
2733  break;
2734  }
2735  case tok::kw___builtin_convertvector: {
2736  // The first argument is an expression to be converted, followed by a comma.
2738  if (Expr.isInvalid()) {
2739  SkipUntil(tok::r_paren, StopAtSemi);
2740  return ExprError();
2741  }
2742 
2743  if (ExpectAndConsume(tok::comma)) {
2744  SkipUntil(tok::r_paren, StopAtSemi);
2745  return ExprError();
2746  }
2747 
2748  // Second argument is the type to bitcast to.
2749  TypeResult DestTy = ParseTypeName();
2750  if (DestTy.isInvalid())
2751  return ExprError();
2752 
2753  // Attempt to consume the r-paren.
2754  if (Tok.isNot(tok::r_paren)) {
2755  Diag(Tok, diag::err_expected) << tok::r_paren;
2756  SkipUntil(tok::r_paren, StopAtSemi);
2757  return ExprError();
2758  }
2759 
2760  Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2761  ConsumeParen());
2762  break;
2763  }
2764  case tok::kw___builtin_COLUMN:
2765  case tok::kw___builtin_FILE:
2766  case tok::kw___builtin_FUNCTION:
2767  case tok::kw___builtin_LINE:
2768  case tok::kw___builtin_source_location: {
2769  // Attempt to consume the r-paren.
2770  if (Tok.isNot(tok::r_paren)) {
2771  Diag(Tok, diag::err_expected) << tok::r_paren;
2772  SkipUntil(tok::r_paren, StopAtSemi);
2773  return ExprError();
2774  }
2776  switch (T) {
2777  case tok::kw___builtin_FILE:
2778  return SourceLocExpr::File;
2779  case tok::kw___builtin_FUNCTION:
2780  return SourceLocExpr::Function;
2781  case tok::kw___builtin_LINE:
2782  return SourceLocExpr::Line;
2783  case tok::kw___builtin_COLUMN:
2784  return SourceLocExpr::Column;
2785  case tok::kw___builtin_source_location:
2787  default:
2788  llvm_unreachable("invalid keyword");
2789  }
2790  }();
2791  Res = Actions.ActOnSourceLocExpr(Kind, StartLoc, ConsumeParen());
2792  break;
2793  }
2794  }
2795 
2796  if (Res.isInvalid())
2797  return ExprError();
2798 
2799  // These can be followed by postfix-expr pieces because they are
2800  // primary-expressions.
2801  return ParsePostfixExpressionSuffix(Res.get());
2802 }
2803 
2804 bool Parser::tryParseOpenMPArrayShapingCastPart() {
2805  assert(Tok.is(tok::l_square) && "Expected open bracket");
2806  bool ErrorFound = true;
2807  TentativeParsingAction TPA(*this);
2808  do {
2809  if (Tok.isNot(tok::l_square))
2810  break;
2811  // Consume '['
2812  ConsumeBracket();
2813  // Skip inner expression.
2814  while (!SkipUntil(tok::r_square, tok::annot_pragma_openmp_end,
2816  ;
2817  if (Tok.isNot(tok::r_square))
2818  break;
2819  // Consume ']'
2820  ConsumeBracket();
2821  // Found ')' - done.
2822  if (Tok.is(tok::r_paren)) {
2823  ErrorFound = false;
2824  break;
2825  }
2826  } while (Tok.isNot(tok::annot_pragma_openmp_end));
2827  TPA.Revert();
2828  return !ErrorFound;
2829 }
2830 
2831 /// ParseParenExpression - This parses the unit that starts with a '(' token,
2832 /// based on what is allowed by ExprType. The actual thing parsed is returned
2833 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2834 /// not the parsed cast-expression.
2835 ///
2836 /// \verbatim
2837 /// primary-expression: [C99 6.5.1]
2838 /// '(' expression ')'
2839 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
2840 /// postfix-expression: [C99 6.5.2]
2841 /// '(' type-name ')' '{' initializer-list '}'
2842 /// '(' type-name ')' '{' initializer-list ',' '}'
2843 /// cast-expression: [C99 6.5.4]
2844 /// '(' type-name ')' cast-expression
2845 /// [ARC] bridged-cast-expression
2846 /// [ARC] bridged-cast-expression:
2847 /// (__bridge type-name) cast-expression
2848 /// (__bridge_transfer type-name) cast-expression
2849 /// (__bridge_retained type-name) cast-expression
2850 /// fold-expression: [C++1z]
2851 /// '(' cast-expression fold-operator '...' ')'
2852 /// '(' '...' fold-operator cast-expression ')'
2853 /// '(' cast-expression fold-operator '...'
2854 /// fold-operator cast-expression ')'
2855 /// [OPENMP] Array shaping operation
2856 /// '(' '[' expression ']' { '[' expression ']' } cast-expression
2857 /// \endverbatim
2858 ExprResult
2859 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2860  bool isTypeCast, ParsedType &CastTy,
2861  SourceLocation &RParenLoc) {
2862  assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2863  ColonProtectionRAIIObject ColonProtection(*this, false);
2864  BalancedDelimiterTracker T(*this, tok::l_paren);
2865  if (T.consumeOpen())
2866  return ExprError();
2867  SourceLocation OpenLoc = T.getOpenLocation();
2868 
2869  PreferredType.enterParenExpr(Tok.getLocation(), OpenLoc);
2870 
2871  ExprResult Result(true);
2872  bool isAmbiguousTypeId;
2873  CastTy = nullptr;
2874 
2875  if (Tok.is(tok::code_completion)) {
2876  cutOffParsing();
2877  Actions.CodeCompleteExpression(
2878  getCurScope(), PreferredType.get(Tok.getLocation()),
2879  /*IsParenthesized=*/ExprType >= CompoundLiteral);
2880  return ExprError();
2881  }
2882 
2883  // Diagnose use of bridge casts in non-arc mode.
2884  bool BridgeCast = (getLangOpts().ObjC &&
2885  Tok.isOneOf(tok::kw___bridge,
2886  tok::kw___bridge_transfer,
2887  tok::kw___bridge_retained,
2888  tok::kw___bridge_retain));
2889  if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2890  if (!TryConsumeToken(tok::kw___bridge)) {
2891  StringRef BridgeCastName = Tok.getName();
2892  SourceLocation BridgeKeywordLoc = ConsumeToken();
2893  if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2894  Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2895  << BridgeCastName
2896  << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2897  }
2898  BridgeCast = false;
2899  }
2900 
2901  // None of these cases should fall through with an invalid Result
2902  // unless they've already reported an error.
2903  if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2904  Diag(Tok, OpenLoc.isMacroID() ? diag::ext_gnu_statement_expr_macro
2905  : diag::ext_gnu_statement_expr);
2906 
2907  checkCompoundToken(OpenLoc, tok::l_paren, CompoundToken::StmtExprBegin);
2908 
2909  if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2910  Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2911  } else {
2912  // Find the nearest non-record decl context. Variables declared in a
2913  // statement expression behave as if they were declared in the enclosing
2914  // function, block, or other code construct.
2915  DeclContext *CodeDC = Actions.CurContext;
2916  while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
2917  CodeDC = CodeDC->getParent();
2918  assert(CodeDC && !CodeDC->isFileContext() &&
2919  "statement expr not in code context");
2920  }
2921  Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2922 
2923  Actions.ActOnStartStmtExpr();
2924 
2925  StmtResult Stmt(ParseCompoundStatement(true));
2926  ExprType = CompoundStmt;
2927 
2928  // If the substmt parsed correctly, build the AST node.
2929  if (!Stmt.isInvalid()) {
2930  Result = Actions.ActOnStmtExpr(getCurScope(), OpenLoc, Stmt.get(),
2931  Tok.getLocation());
2932  } else {
2933  Actions.ActOnStmtExprError();
2934  }
2935  }
2936  } else if (ExprType >= CompoundLiteral && BridgeCast) {
2937  tok::TokenKind tokenKind = Tok.getKind();
2938  SourceLocation BridgeKeywordLoc = ConsumeToken();
2939 
2940  // Parse an Objective-C ARC ownership cast expression.
2942  if (tokenKind == tok::kw___bridge)
2943  Kind = OBC_Bridge;
2944  else if (tokenKind == tok::kw___bridge_transfer)
2946  else if (tokenKind == tok::kw___bridge_retained)
2948  else {
2949  // As a hopefully temporary workaround, allow __bridge_retain as
2950  // a synonym for __bridge_retained, but only in system headers.
2951  assert(tokenKind == tok::kw___bridge_retain);
2953  if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2954  Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2955  << FixItHint::CreateReplacement(BridgeKeywordLoc,
2956  "__bridge_retained");
2957  }
2958 
2959  TypeResult Ty = ParseTypeName();
2960  T.consumeClose();
2961  ColonProtection.restore();
2962  RParenLoc = T.getCloseLocation();
2963 
2964  PreferredType.enterTypeCast(Tok.getLocation(), Ty.get().get());
2965  ExprResult SubExpr = ParseCastExpression(AnyCastExpr);
2966 
2967  if (Ty.isInvalid() || SubExpr.isInvalid())
2968  return ExprError();
2969 
2970  return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2971  BridgeKeywordLoc, Ty.get(),
2972  RParenLoc, SubExpr.get());
2973  } else if (ExprType >= CompoundLiteral &&
2974  isTypeIdInParens(isAmbiguousTypeId)) {
2975 
2976  // Otherwise, this is a compound literal expression or cast expression.
2977 
2978  // In C++, if the type-id is ambiguous we disambiguate based on context.
2979  // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2980  // in which case we should treat it as type-id.
2981  // if stopIfCastExpr is false, we need to determine the context past the
2982  // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2983  if (isAmbiguousTypeId && !stopIfCastExpr) {
2984  ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2985  ColonProtection);
2986  RParenLoc = T.getCloseLocation();
2987  return res;
2988  }
2989 
2990  // Parse the type declarator.
2991  DeclSpec DS(AttrFactory);
2992  ParseSpecifierQualifierList(DS);
2993  Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
2995  ParseDeclarator(DeclaratorInfo);
2996 
2997  // If our type is followed by an identifier and either ':' or ']', then
2998  // this is probably an Objective-C message send where the leading '[' is
2999  // missing. Recover as if that were the case.
3000  if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
3001  !InMessageExpression && getLangOpts().ObjC &&
3002  (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
3003  TypeResult Ty;
3004  {
3005  InMessageExpressionRAIIObject InMessage(*this, false);
3006  Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3007  }
3008  Result = ParseObjCMessageExpressionBody(SourceLocation(),
3009  SourceLocation(),
3010  Ty.get(), nullptr);
3011  } else {
3012  // Match the ')'.
3013  T.consumeClose();
3014  ColonProtection.restore();
3015  RParenLoc = T.getCloseLocation();
3016  if (Tok.is(tok::l_brace)) {
3017  ExprType = CompoundLiteral;
3018  TypeResult Ty;
3019  {
3020  InMessageExpressionRAIIObject InMessage(*this, false);
3021  Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3022  }
3023  return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
3024  }
3025 
3026  if (Tok.is(tok::l_paren)) {
3027  // This could be OpenCL vector Literals
3028  if (getLangOpts().OpenCL)
3029  {
3030  TypeResult Ty;
3031  {
3032  InMessageExpressionRAIIObject InMessage(*this, false);
3033  Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3034  }
3035  if(Ty.isInvalid())
3036  {
3037  return ExprError();
3038  }
3039  QualType QT = Ty.get().get().getCanonicalType();
3040  if (QT->isVectorType())
3041  {
3042  // We parsed '(' vector-type-name ')' followed by '('
3043 
3044  // Parse the cast-expression that follows it next.
3045  // isVectorLiteral = true will make sure we don't parse any
3046  // Postfix expression yet
3047  Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
3048  /*isAddressOfOperand=*/false,
3049  /*isTypeCast=*/IsTypeCast,
3050  /*isVectorLiteral=*/true);
3051 
3052  if (!Result.isInvalid()) {
3053  Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
3054  DeclaratorInfo, CastTy,
3055  RParenLoc, Result.get());
3056  }
3057 
3058  // After we performed the cast we can check for postfix-expr pieces.
3059  if (!Result.isInvalid()) {
3060  Result = ParsePostfixExpressionSuffix(Result);
3061  }
3062 
3063  return Result;
3064  }
3065  }
3066  }
3067 
3068  if (ExprType == CastExpr) {
3069  // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
3070 
3071  if (DeclaratorInfo.isInvalidType())
3072  return ExprError();
3073 
3074  // Note that this doesn't parse the subsequent cast-expression, it just
3075  // returns the parsed type to the callee.
3076  if (stopIfCastExpr) {
3077  TypeResult Ty;
3078  {
3079  InMessageExpressionRAIIObject InMessage(*this, false);
3080  Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3081  }
3082  CastTy = Ty.get();
3083  return ExprResult();
3084  }
3085 
3086  // Reject the cast of super idiom in ObjC.
3087  if (Tok.is(tok::identifier) && getLangOpts().ObjC &&
3088  Tok.getIdentifierInfo() == Ident_super &&
3089  getCurScope()->isInObjcMethodScope() &&
3090  GetLookAheadToken(1).isNot(tok::period)) {
3091  Diag(Tok.getLocation(), diag::err_illegal_super_cast)
3092  << SourceRange(OpenLoc, RParenLoc);
3093  return ExprError();
3094  }
3095 
3096  PreferredType.enterTypeCast(Tok.getLocation(), CastTy.get());
3097  // Parse the cast-expression that follows it next.
3098  // TODO: For cast expression with CastTy.
3099  Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
3100  /*isAddressOfOperand=*/false,
3101  /*isTypeCast=*/IsTypeCast);
3102  if (!Result.isInvalid()) {
3103  Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
3104  DeclaratorInfo, CastTy,
3105  RParenLoc, Result.get());
3106  }
3107  return Result;
3108  }
3109 
3110  Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
3111  return ExprError();
3112  }
3113  } else if (ExprType >= FoldExpr && Tok.is(tok::ellipsis) &&
3114  isFoldOperator(NextToken().getKind())) {
3115  ExprType = FoldExpr;
3116  return ParseFoldExpression(ExprResult(), T);
3117  } else if (isTypeCast) {
3118  // Parse the expression-list.
3119  InMessageExpressionRAIIObject InMessage(*this, false);
3120  ExprVector ArgExprs;
3121 
3122  if (!ParseSimpleExpressionList(ArgExprs)) {
3123  // FIXME: If we ever support comma expressions as operands to
3124  // fold-expressions, we'll need to allow multiple ArgExprs here.
3125  if (ExprType >= FoldExpr && ArgExprs.size() == 1 &&
3126  isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) {
3127  ExprType = FoldExpr;
3128  return ParseFoldExpression(ArgExprs[0], T);
3129  }
3130 
3131  ExprType = SimpleExpr;
3132  Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
3133  ArgExprs);
3134  }
3135  } else if (getLangOpts().OpenMP >= 50 && OpenMPDirectiveParsing &&
3136  ExprType == CastExpr && Tok.is(tok::l_square) &&
3137  tryParseOpenMPArrayShapingCastPart()) {
3138  bool ErrorFound = false;
3139  SmallVector<Expr *, 4> OMPDimensions;
3140  SmallVector<SourceRange, 4> OMPBracketsRanges;
3141  do {
3142  BalancedDelimiterTracker TS(*this, tok::l_square);
3143  TS.consumeOpen();
3144  ExprResult NumElements =
3146  if (!NumElements.isUsable()) {
3147  ErrorFound = true;
3148  while (!SkipUntil(tok::r_square, tok::r_paren,
3150  ;
3151  }
3152  TS.consumeClose();
3153  OMPDimensions.push_back(NumElements.get());
3154  OMPBracketsRanges.push_back(TS.getRange());
3155  } while (Tok.isNot(tok::r_paren));
3156  // Match the ')'.
3157  T.consumeClose();
3158  RParenLoc = T.getCloseLocation();
3160  if (ErrorFound) {
3161  Result = ExprError();
3162  } else if (!Result.isInvalid()) {
3163  Result = Actions.ActOnOMPArrayShapingExpr(
3164  Result.get(), OpenLoc, RParenLoc, OMPDimensions, OMPBracketsRanges);
3165  }
3166  return Result;
3167  } else {
3168  InMessageExpressionRAIIObject InMessage(*this, false);
3169 
3170  Result = ParseExpression(MaybeTypeCast);
3171  if (!getLangOpts().CPlusPlus && Result.isUsable()) {
3172  // Correct typos in non-C++ code earlier so that implicit-cast-like
3173  // expressions are parsed correctly.
3174  Result = Actions.CorrectDelayedTyposInExpr(Result);
3175  }
3176 
3177  if (ExprType >= FoldExpr && isFoldOperator(Tok.getKind()) &&
3178  NextToken().is(tok::ellipsis)) {
3179  ExprType = FoldExpr;
3180  return ParseFoldExpression(Result, T);
3181  }
3182  ExprType = SimpleExpr;
3183 
3184  // Don't build a paren expression unless we actually match a ')'.
3185  if (!Result.isInvalid() && Tok.is(tok::r_paren))
3186  Result =
3187  Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
3188  }
3189 
3190  // Match the ')'.
3191  if (Result.isInvalid()) {
3192  SkipUntil(tok::r_paren, StopAtSemi);
3193  return ExprError();
3194  }
3195 
3196  T.consumeClose();
3197  RParenLoc = T.getCloseLocation();
3198  return Result;
3199 }
3200 
3201 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
3202 /// and we are at the left brace.
3203 ///
3204 /// \verbatim
3205 /// postfix-expression: [C99 6.5.2]
3206 /// '(' type-name ')' '{' initializer-list '}'
3207 /// '(' type-name ')' '{' initializer-list ',' '}'
3208 /// \endverbatim
3209 ExprResult
3210 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
3211  SourceLocation LParenLoc,
3212  SourceLocation RParenLoc) {
3213  assert(Tok.is(tok::l_brace) && "Not a compound literal!");
3214  if (!getLangOpts().C99) // Compound literals don't exist in C90.
3215  Diag(LParenLoc, diag::ext_c99_compound_literal);
3216  PreferredType.enterTypeCast(Tok.getLocation(), Ty.get());
3217  ExprResult Result = ParseInitializer();
3218  if (!Result.isInvalid() && Ty)
3219  return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
3220  return Result;
3221 }
3222 
3223 /// ParseStringLiteralExpression - This handles the various token types that
3224 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
3225 /// translation phase #6].
3226 ///
3227 /// \verbatim
3228 /// primary-expression: [C99 6.5.1]
3229 /// string-literal
3230 /// \verbatim
3231 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
3232  assert(isTokenStringLiteral() && "Not a string literal!");
3233 
3234  // String concat. Note that keywords like __func__ and __FUNCTION__ are not
3235  // considered to be strings for concatenation purposes.
3236  SmallVector<Token, 4> StringToks;
3237 
3238  do {
3239  StringToks.push_back(Tok);
3240  ConsumeStringToken();
3241  } while (isTokenStringLiteral());
3242 
3243  // Pass the set of string tokens, ready for concatenation, to the actions.
3244  return Actions.ActOnStringLiteral(StringToks,
3245  AllowUserDefinedLiteral ? getCurScope()
3246  : nullptr);
3247 }
3248 
3249 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
3250 /// [C11 6.5.1.1].
3251 ///
3252 /// \verbatim
3253 /// generic-selection:
3254 /// _Generic ( assignment-expression , generic-assoc-list )
3255 /// generic-assoc-list:
3256 /// generic-association
3257 /// generic-assoc-list , generic-association
3258 /// generic-association:
3259 /// type-name : assignment-expression
3260 /// default : assignment-expression
3261 /// \endverbatim
3262 ExprResult Parser::ParseGenericSelectionExpression() {
3263  assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
3264  if (!getLangOpts().C11)
3265  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3266 
3267  SourceLocation KeyLoc = ConsumeToken();
3268  BalancedDelimiterTracker T(*this, tok::l_paren);
3269  if (T.expectAndConsume())
3270  return ExprError();
3271 
3272  ExprResult ControllingExpr;
3273  {
3274  // C11 6.5.1.1p3 "The controlling expression of a generic selection is
3275  // not evaluated."
3278  ControllingExpr =
3280  if (ControllingExpr.isInvalid()) {
3281  SkipUntil(tok::r_paren, StopAtSemi);
3282  return ExprError();
3283  }
3284  }
3285 
3286  if (ExpectAndConsume(tok::comma)) {
3287  SkipUntil(tok::r_paren, StopAtSemi);
3288  return ExprError();
3289  }
3290 
3291  SourceLocation DefaultLoc;
3293  ExprVector Exprs;
3294  do {
3295  ParsedType Ty;
3296  if (Tok.is(tok::kw_default)) {
3297  // C11 6.5.1.1p2 "A generic selection shall have no more than one default
3298  // generic association."
3299  if (!DefaultLoc.isInvalid()) {
3300  Diag(Tok, diag::err_duplicate_default_assoc);
3301  Diag(DefaultLoc, diag::note_previous_default_assoc);
3302  SkipUntil(tok::r_paren, StopAtSemi);
3303  return ExprError();
3304  }
3305  DefaultLoc = ConsumeToken();
3306  Ty = nullptr;
3307  } else {
3310  if (TR.isInvalid()) {
3311  SkipUntil(tok::r_paren, StopAtSemi);
3312  return ExprError();
3313  }
3314  Ty = TR.get();
3315  }
3316  Types.push_back(Ty);
3317 
3318  if (ExpectAndConsume(tok::colon)) {
3319  SkipUntil(tok::r_paren, StopAtSemi);
3320  return ExprError();
3321  }
3322 
3323  // FIXME: These expressions should be parsed in a potentially potentially
3324  // evaluated context.
3325  ExprResult ER(
3327  if (ER.isInvalid()) {
3328  SkipUntil(tok::r_paren, StopAtSemi);
3329  return ExprError();
3330  }
3331  Exprs.push_back(ER.get());
3332  } while (TryConsumeToken(tok::comma));
3333 
3334  T.consumeClose();
3335  if (T.getCloseLocation().isInvalid())
3336  return ExprError();
3337 
3338  return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
3339  T.getCloseLocation(),
3340  ControllingExpr.get(),
3341  Types, Exprs);
3342 }
3343 
3344 /// Parse A C++1z fold-expression after the opening paren and optional
3345 /// left-hand-side expression.
3346 ///
3347 /// \verbatim
3348 /// fold-expression:
3349 /// ( cast-expression fold-operator ... )
3350 /// ( ... fold-operator cast-expression )
3351 /// ( cast-expression fold-operator ... fold-operator cast-expression )
3352 ExprResult Parser::ParseFoldExpression(ExprResult LHS,
3354  if (LHS.isInvalid()) {
3355  T.skipToEnd();
3356  return true;
3357  }
3358 
3359  tok::TokenKind Kind = tok::unknown;
3360  SourceLocation FirstOpLoc;
3361  if (LHS.isUsable()) {
3362  Kind = Tok.getKind();
3363  assert(isFoldOperator(Kind) && "missing fold-operator");
3364  FirstOpLoc = ConsumeToken();
3365  }
3366 
3367  assert(Tok.is(tok::ellipsis) && "not a fold-expression");
3368  SourceLocation EllipsisLoc = ConsumeToken();
3369 
3370  ExprResult RHS;
3371  if (Tok.isNot(tok::r_paren)) {
3372  if (!isFoldOperator(Tok.getKind()))
3373  return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
3374 
3375  if (Kind != tok::unknown && Tok.getKind() != Kind)
3376  Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
3377  << SourceRange(FirstOpLoc);
3378  Kind = Tok.getKind();
3379  ConsumeToken();
3380 
3381  RHS = ParseExpression();
3382  if (RHS.isInvalid()) {
3383  T.skipToEnd();
3384  return true;
3385  }
3386  }
3387 
3388  Diag(EllipsisLoc, getLangOpts().CPlusPlus17
3389  ? diag::warn_cxx14_compat_fold_expression
3390  : diag::ext_fold_expression);
3391 
3392  T.consumeClose();
3393  return Actions.ActOnCXXFoldExpr(getCurScope(), T.getOpenLocation(), LHS.get(),
3394  Kind, EllipsisLoc, RHS.get(),
3395  T.getCloseLocation());
3396 }
3397 
3398 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
3399 ///
3400 /// \verbatim
3401 /// argument-expression-list:
3402 /// assignment-expression
3403 /// argument-expression-list , assignment-expression
3404 ///
3405 /// [C++] expression-list:
3406 /// [C++] assignment-expression
3407 /// [C++] expression-list , assignment-expression
3408 ///
3409 /// [C++0x] expression-list:
3410 /// [C++0x] initializer-list
3411 ///
3412 /// [C++0x] initializer-list
3413 /// [C++0x] initializer-clause ...[opt]
3414 /// [C++0x] initializer-list , initializer-clause ...[opt]
3415 ///
3416 /// [C++0x] initializer-clause:
3417 /// [C++0x] assignment-expression
3418 /// [C++0x] braced-init-list
3419 /// \endverbatim
3420 bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
3421  llvm::function_ref<void()> ExpressionStarts,
3422  bool FailImmediatelyOnInvalidExpr,
3423  bool EarlyTypoCorrection) {
3424  bool SawError = false;
3425  while (true) {
3426  if (ExpressionStarts)
3427  ExpressionStarts();
3428 
3429  ExprResult Expr;
3430  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3431  Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3432  Expr = ParseBraceInitializer();
3433  } else
3435 
3436  if (EarlyTypoCorrection)
3437  Expr = Actions.CorrectDelayedTyposInExpr(Expr);
3438 
3439  if (Tok.is(tok::ellipsis))
3440  Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
3441  else if (Tok.is(tok::code_completion)) {
3442  // There's nothing to suggest in here as we parsed a full expression.
3443  // Instead fail and propogate the error since caller might have something
3444  // the suggest, e.g. signature help in function call. Note that this is
3445  // performed before pushing the \p Expr, so that signature help can report
3446  // current argument correctly.
3447  SawError = true;
3448  cutOffParsing();
3449  break;
3450  }
3451  if (Expr.isInvalid()) {
3452  SawError = true;
3453  if (FailImmediatelyOnInvalidExpr)
3454  break;
3455  SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
3456  } else {
3457  Exprs.push_back(Expr.get());
3458  }
3459 
3460  if (Tok.isNot(tok::comma))
3461  break;
3462  // Move to the next argument, remember where the comma was.
3463  Token Comma = Tok;
3464  ConsumeToken();
3465  checkPotentialAngleBracketDelimiter(Comma);
3466  }
3467  if (SawError) {
3468  // Ensure typos get diagnosed when errors were encountered while parsing the
3469  // expression list.
3470  for (auto &E : Exprs) {
3472  if (Expr.isUsable()) E = Expr.get();
3473  }
3474  }
3475  return SawError;
3476 }
3477 
3478 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
3479 /// used for misc language extensions.
3480 ///
3481 /// \verbatim
3482 /// simple-expression-list:
3483 /// assignment-expression
3484 /// simple-expression-list , assignment-expression
3485 /// \endverbatim
3486 bool Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr *> &Exprs) {
3487  while (true) {
3489  if (Expr.isInvalid())
3490  return true;
3491 
3492  Exprs.push_back(Expr.get());
3493 
3494  // We might be parsing the LHS of a fold-expression. If we reached the fold
3495  // operator, stop.
3496  if (Tok.isNot(tok::comma) || NextToken().is(tok::ellipsis))
3497  return false;
3498 
3499  // Move to the next argument, remember where the comma was.
3500  Token Comma = Tok;
3501  ConsumeToken();
3502  checkPotentialAngleBracketDelimiter(Comma);
3503  }
3504 }
3505 
3506 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
3507 ///
3508 /// \verbatim
3509 /// [clang] block-id:
3510 /// [clang] specifier-qualifier-list block-declarator
3511 /// \endverbatim
3512 void Parser::ParseBlockId(SourceLocation CaretLoc) {
3513  if (Tok.is(tok::code_completion)) {
3514  cutOffParsing();
3516  return;
3517  }
3518 
3519  // Parse the specifier-qualifier-list piece.
3520  DeclSpec DS(AttrFactory);
3521  ParseSpecifierQualifierList(DS);
3522 
3523  // Parse the block-declarator.
3524  Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
3526  DeclaratorInfo.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
3527  ParseDeclarator(DeclaratorInfo);
3528 
3529  MaybeParseGNUAttributes(DeclaratorInfo);
3530 
3531  // Inform sema that we are starting a block.
3532  Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
3533 }
3534 
3535 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
3536 /// like ^(int x){ return x+1; }
3537 ///
3538 /// \verbatim
3539 /// block-literal:
3540 /// [clang] '^' block-args[opt] compound-statement
3541 /// [clang] '^' block-id compound-statement
3542 /// [clang] block-args:
3543 /// [clang] '(' parameter-list ')'
3544 /// \endverbatim
3545 ExprResult Parser::ParseBlockLiteralExpression() {
3546  assert(Tok.is(tok::caret) && "block literal starts with ^");
3547  SourceLocation CaretLoc = ConsumeToken();
3548 
3549  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
3550  "block literal parsing");
3551 
3552  // Enter a scope to hold everything within the block. This includes the
3553  // argument decls, decls within the compound expression, etc. This also
3554  // allows determining whether a variable reference inside the block is
3555  // within or outside of the block.
3556  ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
3558 
3559  // Inform sema that we are starting a block.
3560  Actions.ActOnBlockStart(CaretLoc, getCurScope());
3561 
3562  // Parse the return type if present.
3563  DeclSpec DS(AttrFactory);
3564  Declarator ParamInfo(DS, ParsedAttributesView::none(),
3566  ParamInfo.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
3567  // FIXME: Since the return type isn't actually parsed, it can't be used to
3568  // fill ParamInfo with an initial valid range, so do it manually.
3569  ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
3570 
3571  // If this block has arguments, parse them. There is no ambiguity here with
3572  // the expression case, because the expression case requires a parameter list.
3573  if (Tok.is(tok::l_paren)) {
3574  ParseParenDeclarator(ParamInfo);
3575  // Parse the pieces after the identifier as if we had "int(...)".
3576  // SetIdentifier sets the source range end, but in this case we're past
3577  // that location.
3578  SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
3579  ParamInfo.SetIdentifier(nullptr, CaretLoc);
3580  ParamInfo.SetRangeEnd(Tmp);
3581  if (ParamInfo.isInvalidType()) {
3582  // If there was an error parsing the arguments, they may have
3583  // tried to use ^(x+y) which requires an argument list. Just
3584  // skip the whole block literal.
3585  Actions.ActOnBlockError(CaretLoc, getCurScope());
3586  return ExprError();
3587  }
3588 
3589  MaybeParseGNUAttributes(ParamInfo);
3590 
3591  // Inform sema that we are starting a block.
3592  Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3593  } else if (!Tok.is(tok::l_brace)) {
3594  ParseBlockId(CaretLoc);
3595  } else {
3596  // Otherwise, pretend we saw (void).
3597  SourceLocation NoLoc;
3598  ParamInfo.AddTypeInfo(
3599  DeclaratorChunk::getFunction(/*HasProto=*/true,
3600  /*IsAmbiguous=*/false,
3601  /*RParenLoc=*/NoLoc,
3602  /*ArgInfo=*/nullptr,
3603  /*NumParams=*/0,
3604  /*EllipsisLoc=*/NoLoc,
3605  /*RParenLoc=*/NoLoc,
3606  /*RefQualifierIsLvalueRef=*/true,
3607  /*RefQualifierLoc=*/NoLoc,
3608  /*MutableLoc=*/NoLoc, EST_None,
3609  /*ESpecRange=*/SourceRange(),
3610  /*Exceptions=*/nullptr,
3611  /*ExceptionRanges=*/nullptr,
3612  /*NumExceptions=*/0,
3613  /*NoexceptExpr=*/nullptr,
3614  /*ExceptionSpecTokens=*/nullptr,
3615  /*DeclsInPrototype=*/None, CaretLoc,
3616  CaretLoc, ParamInfo),
3617  CaretLoc);
3618 
3619  MaybeParseGNUAttributes(ParamInfo);
3620 
3621  // Inform sema that we are starting a block.
3622  Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3623  }
3624 
3625 
3626  ExprResult Result(true);
3627  if (!Tok.is(tok::l_brace)) {
3628  // Saw something like: ^expr
3629  Diag(Tok, diag::err_expected_expression);
3630  Actions.ActOnBlockError(CaretLoc, getCurScope());
3631  return ExprError();
3632  }
3633 
3634  StmtResult Stmt(ParseCompoundStatementBody());
3635  BlockScope.Exit();
3636  if (!Stmt.isInvalid())
3637  Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
3638  else
3639  Actions.ActOnBlockError(CaretLoc, getCurScope());
3640  return Result;
3641 }
3642 
3643 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
3644 ///
3645 /// '__objc_yes'
3646 /// '__objc_no'
3647 ExprResult Parser::ParseObjCBoolLiteral() {
3648  tok::TokenKind Kind = Tok.getKind();
3649  return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
3650 }
3651 
3652 /// Validate availability spec list, emitting diagnostics if necessary. Returns
3653 /// true if invalid.
3655  ArrayRef<AvailabilitySpec> AvailSpecs) {
3656  llvm::SmallSet<StringRef, 4> Platforms;
3657  bool HasOtherPlatformSpec = false;
3658  bool Valid = true;
3659  for (const auto &Spec : AvailSpecs) {
3660  if (Spec.isOtherPlatformSpec()) {
3661  if (HasOtherPlatformSpec) {
3662  P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
3663  Valid = false;
3664  }
3665 
3666  HasOtherPlatformSpec = true;
3667  continue;
3668  }
3669 
3670  bool Inserted = Platforms.insert(Spec.getPlatform()).second;
3671  if (!Inserted) {
3672  // Rule out multiple version specs referring to the same platform.
3673  // For example, we emit an error for:
3674  // @available(macos 10.10, macos 10.11, *)
3675  StringRef Platform = Spec.getPlatform();
3676  P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
3677  << Spec.getEndLoc() << Platform;
3678  Valid = false;
3679  }
3680  }
3681 
3682  if (!HasOtherPlatformSpec) {
3683  SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
3684  P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
3685  << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
3686  return true;
3687  }
3688 
3689  return !Valid;
3690 }
3691 
3692 /// Parse availability query specification.
3693 ///
3694 /// availability-spec:
3695 /// '*'
3696 /// identifier version-tuple
3697 Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
3698  if (Tok.is(tok::star)) {
3699  return AvailabilitySpec(ConsumeToken());
3700  } else {
3701  // Parse the platform name.
3702  if (Tok.is(tok::code_completion)) {
3703  cutOffParsing();
3705  return None;
3706  }
3707  if (Tok.isNot(tok::identifier)) {
3708  Diag(Tok, diag::err_avail_query_expected_platform_name);
3709  return None;
3710  }
3711 
3712  IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
3713  SourceRange VersionRange;
3714  VersionTuple Version = ParseVersionTuple(VersionRange);
3715 
3716  if (Version.empty())
3717  return None;
3718 
3719  StringRef GivenPlatform = PlatformIdentifier->Ident->getName();
3720  StringRef Platform =
3721  AvailabilityAttr::canonicalizePlatformName(GivenPlatform);
3722 
3723  if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
3724  Diag(PlatformIdentifier->Loc,
3725  diag::err_avail_query_unrecognized_platform_name)
3726  << GivenPlatform;
3727  return None;
3728  }
3729 
3730  return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
3731  VersionRange.getEnd());
3732  }
3733 }
3734 
3735 ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
3736  assert(Tok.is(tok::kw___builtin_available) ||
3737  Tok.isObjCAtKeyword(tok::objc_available));
3738 
3739  // Eat the available or __builtin_available.
3740  ConsumeToken();
3741 
3742  BalancedDelimiterTracker Parens(*this, tok::l_paren);
3743  if (Parens.expectAndConsume())
3744  return ExprError();
3745 
3747  bool HasError = false;
3748  while (true) {
3749  Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
3750  if (!Spec)
3751  HasError = true;
3752  else
3753  AvailSpecs.push_back(*Spec);
3754 
3755  if (!TryConsumeToken(tok::comma))
3756  break;
3757  }
3758 
3759  if (HasError) {
3760  SkipUntil(tok::r_paren, StopAtSemi);
3761  return ExprError();
3762  }
3763 
3764  CheckAvailabilitySpecList(*this, AvailSpecs);
3765 
3766  if (Parens.consumeClose())
3767  return ExprError();
3768 
3769  return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
3770  Parens.getCloseLocation());
3771 }
clang::OpenCL
@ OpenCL
Definition: LangStandard.h:62
clang::UnqualifiedId
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:973
clang::Sema::CurContext
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:421
clang::prec::Comma
@ Comma
Definition: OperatorPrecedence.h:28
clang::ObjCBridgeCastKind
ObjCBridgeCastKind
The kind of bridging performed by the Objective-C bridge cast.
Definition: OperationKinds.h:36
clang::prec::Conditional
@ Conditional
Definition: OperatorPrecedence.h:30
clang::OpaquePtr::get
PtrTy get() const
Definition: Ownership.h:80
clang::Parser::TypeCastState
TypeCastState
TypeCastState - State whether an expression is or may be a type cast.
Definition: Parser.h:1759
clang::CorrectionCandidateCallback::ValidateCandidate
virtual bool ValidateCandidate(const TypoCorrection &candidate)
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
Definition: SemaLookup.cpp:5518
clang::IdentifierLoc::Ident
IdentifierInfo * Ident
Definition: ParsedAttr.h:213
clang::PreferredTypeBuilder::enterBinary
void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op)
Definition: SemaCodeComplete.cpp:556
clang::Sema::ActOnNoexceptExpr
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen)
Definition: SemaExprCXX.cpp:8095
clang::prec::LogicalAnd
@ LogicalAnd
Definition: OperatorPrecedence.h:32
clang::TemplateIdAnnotation
Information about a template-id annotation token.
Definition: ParsedTemplate.h:149
clang::Scope::FnScope
@ FnScope
This indicates that the scope corresponds to a function, which means that labels are set here.
Definition: Scope.h:47
clang::SourceLocExpr::IdentKind
IdentKind
Definition: Expr.h:4692
clang::Token::isObjCAtKeyword
bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const
Return true if we have an ObjC keyword identifier.
Definition: Lexer.cpp:58
clang::Sema::ActOnParenListExpr
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:8102
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:210
clang::Sema::ActOnGNUNullExpr
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:16706
clang::DeclContext
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1389
clang::TypoCorrection
Simple class containing the result of Sema::CorrectTypo.
Definition: TypoCorrection.h:42
clang::ParsedAttributesView::none
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:927
clang::FixItHint::CreateInsertion
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:97
clang::InMessageExpressionRAIIObject
Definition: RAIIObjectsForParser.h:328
clang::Parser::SkipUntil
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
Definition: Parser.h:1231
clang::Sema::getASTContext
ASTContext & getASTContext() const
Definition: Sema.h:1637
clang::SourceLocExpr::Column
@ Column
Definition: Expr.h:4692
clang::TST_typename
@ TST_typename
Definition: Specifiers.h:81
clang::Sema::ActOnIdExpression
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2484
llvm::SmallVector
Definition: LLVM.h:38
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::Sema::ActOnBinOp
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15351
clang::Sema::ActOnStartCXXMemberReference
ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor)
Definition: SemaExprCXX.cpp:7507
clang::SourceLocation::getLocWithOffset
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
Definition: SourceLocation.h:134
clang::NamedDecl
This represents a decl that may have a name.
Definition: Decl.h:247
clang::SourceRange::getBegin
SourceLocation getBegin() const
Definition: SourceLocation.h:219
clang::Scope::BlockScope
@ BlockScope
This is a scope that corresponds to a block/closure object.
Definition: Scope.h:71
clang::Stmt::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:324
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:737
clang::Sema::ActOnAsTypeExpr
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_astype(...)
Definition: SemaExpr.cpp:6873
clang::EST_None
@ EST_None
no exception specification
Definition: ExceptionSpecificationType.h:21
AttributeLangSupport::C
@ C
Definition: SemaDeclAttr.cpp:56
clang::Token::getIdentifierInfo
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:181
clang::OBC_BridgeRetained
@ OBC_BridgeRetained
Bridging via __bridge_retain, which makes an ARC object available as a +1 C pointer.
Definition: OperationKinds.h:45
TypoCorrection.h
clang::SourceLocExpr::SourceLocStruct
@ SourceLocStruct
Definition: Expr.h:4692
clang::PreferredTypeBuilder::enterSubscript
void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS)
Definition: SemaCodeComplete.cpp:586
clang::Sema::ActOnMemberAccessExpr
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl)
The main callback when the parser finds something like expression .
Definition: SemaExprMember.cpp:1703
clang::SourceLocExpr::File
@ File
Definition: Expr.h:4692
clang::Token::isAtStartOfLine
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:270
clang::C99
@ C99
Definition: LangStandard.h:49
clang::Parser
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:60
clang::Parser::ParseAssignmentExpression
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast=NotTypeCast)
Parse an expr that doesn't include (top-level) commas.
Definition: ParseExpr.cpp:160
clang::Sema::ActOnCastExpr
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:7927
llvm::Optional
Definition: LLVM.h:40
clang::ActionResult::isUnset
bool isUnset() const
Definition: Ownership.h:167
RAIIObjectsForParser.h
clang::ColonProtectionRAIIObject
ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and restores it when destroyed.
Definition: RAIIObjectsForParser.h:273
clang::prec::Assignment
@ Assignment
Definition: OperatorPrecedence.h:29
DeclSpec.h
clang::Preprocessor::EnterToken
void EnterToken(const Token &Tok, bool IsReinject)
Enters a token in the token stream to be lexed next.
Definition: Preprocessor.h:1698
clang::Sema::ActOnCXXNullPtrLiteral
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc)
ActOnCXXNullPtrLiteral - Parse 'nullptr'.
Definition: SemaExprCXX.cpp:819
clang::Sema::ActOnPostfixUnaryOp
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4740
clang::tooling::X
static ToolExecutorPluginRegistry::Add< AllTUsToolExecutorPlugin > X("all-TUs", "Runs FrontendActions on all TUs in the compilation database. " "Tool results are stored in memory.")
clang::CXXScopeSpec
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:65
clang::Sema::isSimpleTypeSpecifier
bool isSimpleTypeSpecifier(tok::TokenKind Kind) const
Determine whether the token kind starts a simple-type-specifier.
Definition: SemaDecl.cpp:127
clang::Sema::ActOnStmtExpr
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:15906
clang::Sema::ExprEvalContexts
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:1378
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
clang::BalancedDelimiterTracker
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ....
Definition: RAIIObjectsForParser.h:388
clang::Sema::OffsetOfComponent
Definition: Sema.h:5909
clang::Preprocessor::isCodeCompletionReached
bool isCodeCompletionReached() const
Returns true if code-completion is enabled and we have hit the code-completion point.
Definition: Preprocessor.h:1824
clang::Sema::ActOnBlockError
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
Definition: SemaExpr.cpp:16349
clang::IdentifierLoc::Loc
SourceLocation Loc
Definition: ParsedAttr.h:212
clang::DeclaratorChunk::getFunction
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:161
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:636
clang::Type
The base class of the type hierarchy.
Definition: Type.h:1565
clang::ExprError
ExprResult ExprError()
Definition: Ownership.h:278
clang::Sema::ActOnStringLiteral
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e....
Definition: SemaExpr.cpp:1857
clang::Parser::ParseConstraintExpression
ExprResult ParseConstraintExpression()
Parse a constraint-expression.
Definition: ParseExpr.cpp:235
clang::CPlusPlus17
@ CPlusPlus17
Definition: LangStandard.h:56
clang::Sema::ActOnBlockArguments
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:16231
clang::ExprEmpty
ExprResult ExprEmpty()
Definition: Ownership.h:289
clang::Sema::ActOnArraySubscriptExpr
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
Definition: SemaExpr.cpp:4815
clang::DeclaratorContext::Association
@ Association
clang::prec::Unknown
@ Unknown
Definition: OperatorPrecedence.h:27
clang::Parser::NotTypeCast
@ NotTypeCast
Definition: Parser.h:1760
clang::Sema::ActOnObjCAvailabilityCheckExpr
ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef< AvailabilitySpec > AvailSpecs, SourceLocation AtLoc, SourceLocation RParen)
Definition: SemaExpr.cpp:20880
clang::CompoundStmt
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1410
clang::Sema::ActOnClassPropertyRefExpr
ExprResult ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, IdentifierInfo &propertyName, SourceLocation receiverNameLoc, SourceLocation propertyNameLoc)
Definition: SemaExprObjC.cpp:2159
clang::SourceLocExpr::Line
@ Line
Definition: Expr.h:4692
clang::Sema::ActOnObjCBridgedCast
ExprResult ActOnObjCBridgedCast(Scope *S, SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, ParsedType Type, SourceLocation RParenLoc, Expr *SubExpr)
Definition: SemaExprObjC.cpp:4751
clang::Sema::ActOnTypeName
TypeResult ActOnTypeName(Scope *S, Declarator &D)
Definition: SemaType.cpp:6571
clang::Sema::ActOnChooseExpr
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16163
clang::Sema::ActOnCUDAExecConfigExpr
ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc)
Definition: SemaCUDA.cpp:50
clang::PreferredTypeBuilder::get
QualType get(SourceLocation Tok) const
Get the expected type associated with this location, if any.
Definition: Sema.h:336
clang::Sema::ActOnBuiltinOffsetOf
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:16144
clang::C11
@ C11
Definition: LangStandard.h:50
Id
int Id
Definition: ASTDiff.cpp:189
clang::XRayInstrKind::None
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
clang::Parser::ParseUnqualifiedId
bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
Definition: ParseExprCXX.cpp:2847
clang::BalancedDelimiterTracker::getCloseLocation
SourceLocation getCloseLocation() const
Definition: RAIIObjectsForParser.h:431
clang::PreferredTypeBuilder::enterUnary
void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc)
Definition: SemaCodeComplete.cpp:576
clang::SourceRange::getEnd
SourceLocation getEnd() const
Definition: SourceLocation.h:220
clang::Sema::ActOnCXXFoldExpr
ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc)
Handle a C++1z fold-expression: ( expr op ... op expr ).
Definition: SemaTemplateVariadic.cpp:1193
clang::Token::getKind
tok::TokenKind getKind() const
Definition: Token.h:93
clang::ExprResult
ActionResult< Expr * > ExprResult
Definition: Ownership.h:262
clang::Preprocessor::isAtStartOfMacroExpansion
bool isAtStartOfMacroExpansion(SourceLocation loc, SourceLocation *MacroBegin=nullptr) const
Returns true if the given MacroID location points at the first token of the macro expansion.
Definition: Preprocessor.h:2032
clang::CPlusPlus
@ CPlusPlus
Definition: LangStandard.h:53
clang::Parser::StopBeforeMatch
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition: Parser.h:1212
clang::Scope::CompoundStmtScope
@ CompoundStmtScope
This is a compound statement scope.
Definition: Scope.h:130
clang::Sema::ExpressionEvaluationContext::Unevaluated
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
clang::Sema::CodeCompleteExpression
void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data)
Perform code-completion in an expression context when we know what type we're looking for.
Definition: SemaCodeComplete.cpp:4758
clang::Expr::containsErrors
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:238
clang::Type::isVectorType
bool isVectorType() const
Definition: Type.h:6985
clang::Parser::getLangOpts
const LangOptions & getLangOpts() const
Definition: Parser.h:442
clang::DeclaratorContext::BlockLiteral
@ BlockLiteral
clang::LabelDecl
Represents the declaration of a label.
Definition: Decl.h:496
clang::TypoCorrection::isKeyword
bool isKeyword() const
Definition: TypoCorrection.h:202
clang::Sema::ActOnBlockStart
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:16202
clang::Token::is
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:98
clang::Stmt::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:348
clang::Parser::ParseExpression
ExprResult ParseExpression(TypeCastState isTypeCast=NotTypeCast)
Simple precedence-based parser for binary/ternary operators.
Definition: ParseExpr.cpp:123
clang::Type::isFunctionType
bool isFunctionType() const
Definition: Type.h:6879
clang::Sema::CodeCompleteOrdinaryName
void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext)
Definition: SemaCodeComplete.cpp:4331
clang::TemplateIdAnnotation::Kind
TemplateNameKind Kind
The kind of template that Template refers to.
Definition: ParsedTemplate.h:174
clang::Sema::ActOnVAArg
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16547
clang::Token::getAnnotationEndLoc
SourceLocation getAnnotationEndLoc() const
Definition: Token.h:140
ASTContext.h
clang::SourceLocation::isFileID
bool isFileID() const
Definition: SourceLocation.h:102
clang::Sema::CodeCompleteMemberReferenceExpr
void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement, QualType PreferredType)
Definition: SemaCodeComplete.cpp:5599
clang::Sema::TentativeAnalysisScope
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:9672
ExprCXX.h
Base
clang::Parser::getCurScope
Scope * getCurScope() const
Definition: Parser.h:449
clang::DeclContext::isRecord
bool isRecord() const
Definition: DeclBase.h:2002
clang::SourceLocExpr::Function
@ Function
Definition: Expr.h:4692
clang::Parser::Diag
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition: Parser.cpp:73
clang::Token::isNot
bool isNot(tok::TokenKind K) const
Definition: Token.h:99
clang::Parser::MaybeTypeCast
@ MaybeTypeCast
Definition: Parser.h:1761
getKind
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1024
clang::Parser::ParseStringLiteralExpression
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral=false)
clang::Sema::ActOnUnaryExprOrTypeTraitExpr
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
Definition: SemaExpr.cpp:4686
clang::AvailabilitySpec
One specifier in an @available expression.
Definition: Availability.h:30
clang::Parser::StopAtSemi
@ StopAtSemi
Stop skipping at semicolon.
Definition: Parser.h:1210
clang::Sema::ActOnSYCLUniqueStableNameExpr
ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, ParsedType ParsedTy)
Definition: SemaExpr.cpp:3585
PrettyStackTrace.h
clang::Sema::ActOnSourceLocExpr
ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16791
clang::Sema::ActOnObjCBoolLiteral
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
Definition: SemaExpr.cpp:20861
clang::OpaquePtr< QualType >
clang::Preprocessor::getSourceManager
SourceManager & getSourceManager() const
Definition: Preprocessor.h:1069
clang::CPlusPlus2b
@ CPlusPlus2b
Definition: LangStandard.h:58
clang::Preprocessor::getSpelling
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
Definition: Preprocessor.h:1914
clang::syntax::NodeRole::Operand
@ Operand
clang::tok::TokenKind
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
clang::Parser::ParseCaseExpression
ExprResult ParseCaseExpression(SourceLocation CaseLoc)
Definition: ParseExpr.cpp:221
P
StringRef P
Definition: ASTMatchersInternal.cpp:563
clang::Sema::ActOnUnaryOp
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15879
clang::Parser::ParseConstantExpression
ExprResult ParseConstantExpression()
Definition: ParseExpr.cpp:211
clang::Parser::ParseConstraintLogicalOrExpression
ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-or-expression.
Definition: ParseExpr.cpp:349
clang::Parser::ConsumeToken
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition: Parser.h:492
clang::Sema::ActOnCoawaitExpr
ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E)
Definition: SemaCoroutine.cpp:790
clang::ActionResult::get
PtrTy get() const
Definition: Ownership.h:169
clang::TNK_Type_template
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
clang::Sema::ActOnCharacterConstant
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3617
clang::DeclContext::getParent
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1923
clang::Expr::getExprLoc
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:329
clang::ASTContext::getPrintingPolicy
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:713
clang::OBC_BridgeTransfer
@ OBC_BridgeTransfer
Bridging via __bridge_transfer, which transfers ownership of an Objective-C pointer into ARC.
Definition: OperationKinds.h:42
clang::Type::isSpecificPlaceholderType
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:7169
clang::C2x
@ C2x
Definition: LangStandard.h:52
clang::QualType::isNull
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:802
clang::Parser::ParseTypeName
TypeResult ParseTypeName(SourceRange *Range=nullptr, DeclaratorContext Context=DeclaratorContext::TypeName, AccessSpecifier AS=AS_none, Decl **OwnedType=nullptr, ParsedAttributes *Attrs=nullptr)
ParseTypeName type-name: [C99 6.7.6] specifier-qualifier-list abstract-declarator[opt].
Definition: ParseDecl.cpp:44
llvm::ArrayRef
Definition: LLVM.h:34
clang::Sema::ProduceCallSignatureHelp
QualType ProduceCallSignatureHelp(Expr *Fn, ArrayRef< Expr * > Args, SourceLocation OpenParLoc)
Determines the preferred type of the current function argument, by examining the signatures of all po...
Definition: SemaCodeComplete.cpp:6072
Scope.h
clang::EnterExpressionEvaluationContext
RAII object that enters a new expression evaluation context.
Definition: Sema.h:13804
clang::Sema::ActOnStartStmtExpr
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:15894
clang::TypeLoc
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:58
clang::ActionResult::isInvalid
bool isInvalid() const
Definition: Ownership.h:165
clang::FunctionDefinitionKind::Definition
@ Definition
clang::Sema::ActOnConditionalOp
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?: operation.
Definition: SemaExpr.cpp:9116
clang::Token::getName
const char * getName() const
Definition: Token.h:168
clang::Parser::TryConsumeToken
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:500
clang::DeclContext::isFileContext
bool isFileContext() const
Definition: DeclBase.h:1993
clang::Sema::ContextRAII
A RAII object to temporarily push a declaration context.
Definition: Sema.h:994
clang::Sema::ActOnNumericConstant
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3743
clang::BalancedDelimiterTracker::getOpenLocation
SourceLocation getOpenLocation() const
Definition: RAIIObjectsForParser.h:430
clang::Sema::CodeCompletePostfixExpression
void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, QualType PreferredType)
Definition: SemaCodeComplete.cpp:4835
clang::Sema::getExprRange
SourceRange getExprRange(Expr *E) const
Definition: SemaExpr.cpp:495
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:85
clang::Token::getLocation
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:126
clang::SourceLocation::isMacroID
bool isMacroID() const
Definition: SourceLocation.h:103
clang::PrettyStackTraceLoc
If a crash happens while one of these objects are live, the message is printed out along with the spe...
Definition: PrettyStackTrace.h:26
clang::ObjCPropertyAttribute::Kind
Kind
Definition: DeclObjCCommon.h:22
clang::Sema::ActOnPackExpansion
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc)
Invoked when parsing a template argument followed by an ellipsis, which creates a pack expansion.
Definition: SemaTemplateVariadic.cpp:569
clang::ActionResult< Expr * >
clang::ExtensionRAIIObject
ExtensionRAIIObject - This saves the state of extension warnings when constructed and disables them.
Definition: RAIIObjectsForParser.h:255
clang::Sema::ReuseLambdaContextDecl
@ ReuseLambdaContextDecl
Definition: Sema.h:5350
clang::Sema::ActOnConstantExpression
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19442
clang::Sema::ExpressionEvaluationContext::ConstantEvaluated
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
clang::Sema::CodeCompleteAvailabilityPlatformName
void CodeCompleteAvailabilityPlatformName()
Definition: SemaCodeComplete.cpp:10081
clang::Sema::ActOnConvertVectorExpr
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_convertvector(...)
Definition: SemaExpr.cpp:6900
clang::StmtResult
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:263
clang::Parser::ParseConstraintLogicalAndExpression
ExprResult ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-and-expression.
Definition: ParseExpr.cpp:257
clang::DeclaratorContext::TypeName
@ TypeName
clang::IdentifierInfo::getName
StringRef getName() const
Return the actual identifier string.
Definition: IdentifierTable.h:196
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:111
clang::BalancedDelimiterTracker::skipToEnd
void skipToEnd()
Definition: Parser.cpp:2717
clang
Definition: CalledOnceCheck.h:17
clang::Sema::CreateRecoveryExpr
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:20913
clang::Parser::getActions
Sema & getActions() const
Definition: Parser.h:445
clang::prec::LogicalOr
@ LogicalOr
Definition: OperatorPrecedence.h:31
clang::Sema::LookupOrCreateLabel
LabelDecl * LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc=SourceLocation())
LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Definition: SemaLookup.cpp:4400
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:71
clang::Declarator
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1834
clang::SourceManager::isInSystemHeader
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
Definition: SourceManager.h:1504
clang::prec::Level
Level
Definition: OperatorPrecedence.h:26
clang::TypoCorrection::getCorrectionDecl
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
Definition: TypoCorrection.h:151
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:110
clang::CorrectionCandidateCallback
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
Definition: TypoCorrection.h:281
clang::FixItHint::CreateRemoval
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
clang::getBinOpPrecedence
prec::Level getBinOpPrecedence(tok::TokenKind Kind, bool GreaterThanIsOperator, bool CPlusPlus11)
Return the precedence of the specified binary operator token.
Definition: OperatorPrecedence.cpp:17
clang::Preprocessor::getLocForEndOfToken
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
Definition: Preprocessor.h:2023
clang::Token::setKind
void setKind(tok::TokenKind K)
Definition: Token.h:94
clang::Sema::ActOnParenExpr
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4159
clang::Parser::ParseConstantExpressionInExprEvalContext
ExprResult ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast=NotTypeCast)
Definition: ParseExpr.cpp:201
CheckAvailabilitySpecList
static bool CheckAvailabilitySpecList(Parser &P, ArrayRef< AvailabilitySpec > AvailSpecs)
Validate availability spec list, emitting diagnostics if necessary.
Definition: ParseExpr.cpp:3654
clang::Sema::ActOnAddrLabel
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:15886
clang::Stmt::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:336
clang::prec::InclusiveOr
@ InclusiveOr
Definition: OperatorPrecedence.h:33
clang::BalancedDelimiterTracker::consumeClose
bool consumeClose()
Definition: RAIIObjectsForParser.h:449
clang::Sema::getTypeName
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:327
clang::Parser::TryAnnotateTypeOrScopeToken
bool TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
Definition: Parser.cpp:1933
clang::OpaquePtr::getAsOpaquePtr
void * getAsOpaquePtr() const
Definition: Ownership.h:90
clang::Token::isOneOf
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:100
clang::Token::getLastLoc
SourceLocation getLastLoc() const
Definition: Token.h:149
clang::Parser::getTypeAnnotation
static TypeResult getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition: Parser.h:816
clang::Sema::ActOnSizeofParameterPackExpr
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.
Definition: SemaTemplateVariadic.cpp:1011
REVERTIBLE_TYPE_TRAIT
#define REVERTIBLE_TYPE_TRAIT(Name)
clang::Sema::ActOnOMPArrayShapingExpr
ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, SourceLocation RParenLoc, ArrayRef< Expr * > Dims, ArrayRef< SourceRange > Brackets)
Definition: SemaExpr.cpp:5274
clang::ImplicitTypenameContext::Yes
@ Yes
clang::CPlusPlus11
@ CPlusPlus11
Definition: LangStandard.h:54
llvm::SmallVectorImpl
Definition: Randstruct.h:18
clang::Scope::DeclScope
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:59
clang::Sema::ActOnCaseExpr
ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val)
Definition: SemaStmt.cpp:458
clang::Sema::ActOnPredefinedExpr
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3600
clang::Expr
This represents one expression.
Definition: Expr.h:109
clang::IdentifierInfo::hasRevertedTokenIDToIdentifier
bool hasRevertedTokenIDToIdentifier() const
True if revertTokenIDToIdentifier() was called.
Definition: IdentifierTable.h:265
SM
#define SM(sm)
Definition: Cuda.cpp:79
clang::Sema::ActOnOMPArraySectionExpr
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc)
Definition: SemaExpr.cpp:5088
clang::IdentifierLoc
Wraps an identifier and optional source location for the identifier.
Definition: ParsedAttr.h:211
clang::CastExpr
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3480
clang::Parser::NextToken
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:811
clang::Sema::ActOnCompoundLiteral
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:7207
clang::Sema::PCC_Type
@ PCC_Type
Code completion occurs where only a type is permitted.
Definition: Sema.h:13130
clang::Parser::IsTypeCast
@ IsTypeCast
Definition: Parser.h:1762
clang::Sema::ActOnNameClassifiedAsOverloadSet
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Definition: SemaDecl.cpp:1299
clang::OBC_Bridge
@ OBC_Bridge
Bridging via __bridge, which does nothing but reinterpret the bits.
Definition: OperationKinds.h:39
clang::Sema::CheckConstraintExpression
bool CheckConstraintExpression(const Expr *CE, Token NextToken=Token(), bool *PossibleNonPrimary=nullptr, bool IsTrailingRequiresClause=false)
Check whether the given expression is a valid constraint expression.
Definition: SemaConcept.cpp:87
clang::Sema::CodeCompleteObjCClassPropertyRefExpr
void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, SourceLocation ClassNameLoc, bool IsBaseExprStatement)
Definition: SemaCodeComplete.cpp:5756
clang::ActionResult::isUsable
bool isUsable() const
Definition: Ownership.h:166
clang::Sema::ActOnCallExpr
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6606
clang::Sema::ActOnStmtExprError
void ActOnStmtExprError()
Definition: SemaExpr.cpp:15898
clang::CXXScopeSpec::isNotEmpty
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:193
clang::FixItHint::CreateReplacement
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:134
clang::Sema::ActOnBlockStmtExpr
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
Definition: SemaExpr.cpp:16361
clang::DeclSpec
Captures information about "declaration specifiers".
Definition: DeclSpec.h:230
clang::prec::Spaceship
@ Spaceship
Definition: OperatorPrecedence.h:38
ParsedTemplate.h
clang::Sema::ActOnGenericSelectionExpr
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr * > ArgExprs)
Definition: SemaExpr.cpp:1609
clang::UnaryExprOrTypeTrait
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:51
clang::Sema::CorrectDelayedTyposInExpr
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, 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...
Definition: SemaExprCXX.cpp:8743
Parser.h