clang  10.0.0git
ParseDecl.cpp
Go to the documentation of this file.
1 //===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
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 // This file implements the Declaration portions of the Parser interfaces.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Parse/Parser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclTemplate.h"
19 #include "clang/Basic/Attributes.h"
20 #include "clang/Basic/CharInfo.h"
21 #include "clang/Basic/TargetInfo.h"
23 #include "clang/Sema/Lookup.h"
25 #include "clang/Sema/Scope.h"
26 #include "llvm/ADT/Optional.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringSwitch.h"
30 
31 using namespace clang;
32 
33 //===----------------------------------------------------------------------===//
34 // C99 6.7: Declarations.
35 //===----------------------------------------------------------------------===//
36 
37 /// ParseTypeName
38 /// type-name: [C99 6.7.6]
39 /// specifier-qualifier-list abstract-declarator[opt]
40 ///
41 /// Called type-id in C++.
43  DeclaratorContext Context,
44  AccessSpecifier AS,
45  Decl **OwnedType,
46  ParsedAttributes *Attrs) {
47  DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
48  if (DSC == DeclSpecContext::DSC_normal)
49  DSC = DeclSpecContext::DSC_type_specifier;
50 
51  // Parse the common declaration-specifiers piece.
52  DeclSpec DS(AttrFactory);
53  if (Attrs)
54  DS.addAttributes(*Attrs);
55  ParseSpecifierQualifierList(DS, AS, DSC);
56  if (OwnedType)
57  *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
58 
59  // Parse the abstract-declarator, if present.
60  Declarator DeclaratorInfo(DS, Context);
61  ParseDeclarator(DeclaratorInfo);
62  if (Range)
63  *Range = DeclaratorInfo.getSourceRange();
64 
65  if (DeclaratorInfo.isInvalidType())
66  return true;
67 
68  return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
69 }
70 
71 /// Normalizes an attribute name by dropping prefixed and suffixed __.
72 static StringRef normalizeAttrName(StringRef Name) {
73  if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
74  return Name.drop_front(2).drop_back(2);
75  return Name;
76 }
77 
78 /// isAttributeLateParsed - Return true if the attribute has arguments that
79 /// require late parsing.
80 static bool isAttributeLateParsed(const IdentifierInfo &II) {
81 #define CLANG_ATTR_LATE_PARSED_LIST
82  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
83 #include "clang/Parse/AttrParserStringSwitches.inc"
84  .Default(false);
85 #undef CLANG_ATTR_LATE_PARSED_LIST
86 }
87 
88 /// Check if the a start and end source location expand to the same macro.
90  SourceLocation EndLoc) {
91  if (!StartLoc.isMacroID() || !EndLoc.isMacroID())
92  return false;
93 
95  if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
96  return false;
97 
98  bool AttrStartIsInMacro =
100  bool AttrEndIsInMacro =
102  return AttrStartIsInMacro && AttrEndIsInMacro;
103 }
104 
105 /// ParseGNUAttributes - Parse a non-empty attributes list.
106 ///
107 /// [GNU] attributes:
108 /// attribute
109 /// attributes attribute
110 ///
111 /// [GNU] attribute:
112 /// '__attribute__' '(' '(' attribute-list ')' ')'
113 ///
114 /// [GNU] attribute-list:
115 /// attrib
116 /// attribute_list ',' attrib
117 ///
118 /// [GNU] attrib:
119 /// empty
120 /// attrib-name
121 /// attrib-name '(' identifier ')'
122 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
123 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
124 ///
125 /// [GNU] attrib-name:
126 /// identifier
127 /// typespec
128 /// typequal
129 /// storageclass
130 ///
131 /// Whether an attribute takes an 'identifier' is determined by the
132 /// attrib-name. GCC's behavior here is not worth imitating:
133 ///
134 /// * In C mode, if the attribute argument list starts with an identifier
135 /// followed by a ',' or an ')', and the identifier doesn't resolve to
136 /// a type, it is parsed as an identifier. If the attribute actually
137 /// wanted an expression, it's out of luck (but it turns out that no
138 /// attributes work that way, because C constant expressions are very
139 /// limited).
140 /// * In C++ mode, if the attribute argument list starts with an identifier,
141 /// and the attribute *wants* an identifier, it is parsed as an identifier.
142 /// At block scope, any additional tokens between the identifier and the
143 /// ',' or ')' are ignored, otherwise they produce a parse error.
144 ///
145 /// We follow the C++ model, but don't allow junk after the identifier.
146 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
147  SourceLocation *endLoc,
148  LateParsedAttrList *LateAttrs,
149  Declarator *D) {
150  assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
151 
152  while (Tok.is(tok::kw___attribute)) {
153  SourceLocation AttrTokLoc = ConsumeToken();
154  unsigned OldNumAttrs = attrs.size();
155  unsigned OldNumLateAttrs = LateAttrs ? LateAttrs->size() : 0;
156 
157  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
158  "attribute")) {
159  SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
160  return;
161  }
162  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
163  SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
164  return;
165  }
166  // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
167  do {
168  // Eat preceeding commas to allow __attribute__((,,,foo))
169  while (TryConsumeToken(tok::comma))
170  ;
171 
172  // Expect an identifier or declaration specifier (const, int, etc.)
173  if (Tok.isAnnotation())
174  break;
175  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
176  if (!AttrName)
177  break;
178 
179  SourceLocation AttrNameLoc = ConsumeToken();
180 
181  if (Tok.isNot(tok::l_paren)) {
182  attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
184  continue;
185  }
186 
187  // Handle "parameterized" attributes
188  if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
189  ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
191  continue;
192  }
193 
194  // Handle attributes with arguments that require late parsing.
195  LateParsedAttribute *LA =
196  new LateParsedAttribute(this, *AttrName, AttrNameLoc);
197  LateAttrs->push_back(LA);
198 
199  // Attributes in a class are parsed at the end of the class, along
200  // with other late-parsed declarations.
201  if (!ClassStack.empty() && !LateAttrs->parseSoon())
202  getCurrentClass().LateParsedDeclarations.push_back(LA);
203 
204  // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
205  // recursively consumes balanced parens.
206  LA->Toks.push_back(Tok);
207  ConsumeParen();
208  // Consume everything up to and including the matching right parens.
209  ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
210 
211  Token Eof;
212  Eof.startToken();
213  Eof.setLocation(Tok.getLocation());
214  LA->Toks.push_back(Eof);
215  } while (Tok.is(tok::comma));
216 
217  if (ExpectAndConsume(tok::r_paren))
218  SkipUntil(tok::r_paren, StopAtSemi);
219  SourceLocation Loc = Tok.getLocation();
220  if (ExpectAndConsume(tok::r_paren))
221  SkipUntil(tok::r_paren, StopAtSemi);
222  if (endLoc)
223  *endLoc = Loc;
224 
225  // If this was declared in a macro, attach the macro IdentifierInfo to the
226  // parsed attribute.
227  auto &SM = PP.getSourceManager();
228  if (!SM.isWrittenInBuiltinFile(SM.getSpellingLoc(AttrTokLoc)) &&
229  FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)) {
230  CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
231  StringRef FoundName =
232  Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
233  IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
234 
235  for (unsigned i = OldNumAttrs; i < attrs.size(); ++i)
236  attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
237 
238  if (LateAttrs) {
239  for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); ++i)
240  (*LateAttrs)[i]->MacroII = MacroII;
241  }
242  }
243  }
244 }
245 
246 /// Determine whether the given attribute has an identifier argument.
248 #define CLANG_ATTR_IDENTIFIER_ARG_LIST
249  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
250 #include "clang/Parse/AttrParserStringSwitches.inc"
251  .Default(false);
252 #undef CLANG_ATTR_IDENTIFIER_ARG_LIST
253 }
254 
255 /// Determine whether the given attribute has a variadic identifier argument.
257 #define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
258  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
259 #include "clang/Parse/AttrParserStringSwitches.inc"
260  .Default(false);
261 #undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
262 }
263 
264 /// Determine whether the given attribute treats kw_this as an identifier.
266 #define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
267  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
268 #include "clang/Parse/AttrParserStringSwitches.inc"
269  .Default(false);
270 #undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
271 }
272 
273 /// Determine whether the given attribute parses a type argument.
274 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
275 #define CLANG_ATTR_TYPE_ARG_LIST
276  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
277 #include "clang/Parse/AttrParserStringSwitches.inc"
278  .Default(false);
279 #undef CLANG_ATTR_TYPE_ARG_LIST
280 }
281 
282 /// Determine whether the given attribute requires parsing its arguments
283 /// in an unevaluated context or not.
285 #define CLANG_ATTR_ARG_CONTEXT_LIST
286  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
287 #include "clang/Parse/AttrParserStringSwitches.inc"
288  .Default(false);
289 #undef CLANG_ATTR_ARG_CONTEXT_LIST
290 }
291 
292 IdentifierLoc *Parser::ParseIdentifierLoc() {
293  assert(Tok.is(tok::identifier) && "expected an identifier");
295  Tok.getLocation(),
296  Tok.getIdentifierInfo());
297  ConsumeToken();
298  return IL;
299 }
300 
301 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
302  SourceLocation AttrNameLoc,
303  ParsedAttributes &Attrs,
304  SourceLocation *EndLoc,
305  IdentifierInfo *ScopeName,
306  SourceLocation ScopeLoc,
307  ParsedAttr::Syntax Syntax) {
308  BalancedDelimiterTracker Parens(*this, tok::l_paren);
309  Parens.consumeOpen();
310 
311  TypeResult T;
312  if (Tok.isNot(tok::r_paren))
313  T = ParseTypeName();
314 
315  if (Parens.consumeClose())
316  return;
317 
318  if (T.isInvalid())
319  return;
320 
321  if (T.isUsable())
322  Attrs.addNewTypeAttr(&AttrName,
323  SourceRange(AttrNameLoc, Parens.getCloseLocation()),
324  ScopeName, ScopeLoc, T.get(), Syntax);
325  else
326  Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
327  ScopeName, ScopeLoc, nullptr, 0, Syntax);
328 }
329 
330 unsigned Parser::ParseAttributeArgsCommon(
331  IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
332  ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
333  SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
334  // Ignore the left paren location for now.
335  ConsumeParen();
336 
337  bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
338  bool AttributeIsTypeArgAttr = attributeIsTypeArgAttr(*AttrName);
339 
340  // Interpret "kw_this" as an identifier if the attributed requests it.
341  if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
342  Tok.setKind(tok::identifier);
343 
344  ArgsVector ArgExprs;
345  if (Tok.is(tok::identifier)) {
346  // If this attribute wants an 'identifier' argument, make it so.
347  bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName) ||
349  ParsedAttr::Kind AttrKind =
350  ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
351 
352  // If we don't know how to parse this attribute, but this is the only
353  // token in this argument, assume it's meant to be an identifier.
354  if (AttrKind == ParsedAttr::UnknownAttribute ||
355  AttrKind == ParsedAttr::IgnoredAttribute) {
356  const Token &Next = NextToken();
357  IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
358  }
359 
360  if (IsIdentifierArg)
361  ArgExprs.push_back(ParseIdentifierLoc());
362  }
363 
364  ParsedType TheParsedType;
365  if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
366  // Eat the comma.
367  if (!ArgExprs.empty())
368  ConsumeToken();
369 
370  // Parse the non-empty comma-separated list of expressions.
371  do {
372  // Interpret "kw_this" as an identifier if the attributed requests it.
373  if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
374  Tok.setKind(tok::identifier);
375 
376  ExprResult ArgExpr;
377  if (AttributeIsTypeArgAttr) {
379  if (T.isInvalid()) {
380  SkipUntil(tok::r_paren, StopAtSemi);
381  return 0;
382  }
383  if (T.isUsable())
384  TheParsedType = T.get();
385  break; // FIXME: Multiple type arguments are not implemented.
386  } else if (Tok.is(tok::identifier) &&
388  ArgExprs.push_back(ParseIdentifierLoc());
389  } else {
390  bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
392  Actions,
395 
396  ExprResult ArgExpr(
398  if (ArgExpr.isInvalid()) {
399  SkipUntil(tok::r_paren, StopAtSemi);
400  return 0;
401  }
402  ArgExprs.push_back(ArgExpr.get());
403  }
404  // Eat the comma, move to the next argument
405  } while (TryConsumeToken(tok::comma));
406  }
407 
408  SourceLocation RParen = Tok.getLocation();
409  if (!ExpectAndConsume(tok::r_paren)) {
410  SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
411 
412  if (AttributeIsTypeArgAttr && !TheParsedType.get().isNull()) {
413  Attrs.addNewTypeAttr(AttrName, SourceRange(AttrNameLoc, RParen),
414  ScopeName, ScopeLoc, TheParsedType, Syntax);
415  } else {
416  Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
417  ArgExprs.data(), ArgExprs.size(), Syntax);
418  }
419  }
420 
421  if (EndLoc)
422  *EndLoc = RParen;
423 
424  return static_cast<unsigned>(ArgExprs.size() + !TheParsedType.get().isNull());
425 }
426 
427 /// Parse the arguments to a parameterized GNU attribute or
428 /// a C++11 attribute in "gnu" namespace.
429 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
430  SourceLocation AttrNameLoc,
431  ParsedAttributes &Attrs,
432  SourceLocation *EndLoc,
433  IdentifierInfo *ScopeName,
434  SourceLocation ScopeLoc,
435  ParsedAttr::Syntax Syntax,
436  Declarator *D) {
437 
438  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
439 
440  ParsedAttr::Kind AttrKind =
441  ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
442 
443  if (AttrKind == ParsedAttr::AT_Availability) {
444  ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
445  ScopeLoc, Syntax);
446  return;
447  } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
448  ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
449  ScopeName, ScopeLoc, Syntax);
450  return;
451  } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
452  ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
453  ScopeName, ScopeLoc, Syntax);
454  return;
455  } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
456  ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
457  ScopeName, ScopeLoc, Syntax);
458  return;
459  } else if (attributeIsTypeArgAttr(*AttrName)) {
460  ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
461  ScopeLoc, Syntax);
462  return;
463  }
464 
465  // These may refer to the function arguments, but need to be parsed early to
466  // participate in determining whether it's a redeclaration.
467  llvm::Optional<ParseScope> PrototypeScope;
468  if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
469  D && D->isFunctionDeclarator()) {
471  PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
474  for (unsigned i = 0; i != FTI.NumParams; ++i) {
475  ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
477  }
478  }
479 
480  ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
481  ScopeLoc, Syntax);
482 }
483 
484 unsigned Parser::ParseClangAttributeArgs(
485  IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
486  ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
487  SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
488  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
489 
490  ParsedAttr::Kind AttrKind =
491  ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
492 
493  switch (AttrKind) {
494  default:
495  return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
496  ScopeName, ScopeLoc, Syntax);
497  case ParsedAttr::AT_ExternalSourceSymbol:
498  ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
499  ScopeName, ScopeLoc, Syntax);
500  break;
501  case ParsedAttr::AT_Availability:
502  ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
503  ScopeLoc, Syntax);
504  break;
505  case ParsedAttr::AT_ObjCBridgeRelated:
506  ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
507  ScopeName, ScopeLoc, Syntax);
508  break;
509  case ParsedAttr::AT_TypeTagForDatatype:
510  ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
511  ScopeName, ScopeLoc, Syntax);
512  break;
513  }
514  return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
515 }
516 
517 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
518  SourceLocation AttrNameLoc,
519  ParsedAttributes &Attrs) {
520  // If the attribute isn't known, we will not attempt to parse any
521  // arguments.
522  if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
523  getTargetInfo(), getLangOpts())) {
524  // Eat the left paren, then skip to the ending right paren.
525  ConsumeParen();
526  SkipUntil(tok::r_paren);
527  return false;
528  }
529 
530  SourceLocation OpenParenLoc = Tok.getLocation();
531 
532  if (AttrName->getName() == "property") {
533  // The property declspec is more complex in that it can take one or two
534  // assignment expressions as a parameter, but the lhs of the assignment
535  // must be named get or put.
536 
537  BalancedDelimiterTracker T(*this, tok::l_paren);
538  T.expectAndConsume(diag::err_expected_lparen_after,
539  AttrName->getNameStart(), tok::r_paren);
540 
541  enum AccessorKind {
542  AK_Invalid = -1,
543  AK_Put = 0,
544  AK_Get = 1 // indices into AccessorNames
545  };
546  IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
547  bool HasInvalidAccessor = false;
548 
549  // Parse the accessor specifications.
550  while (true) {
551  // Stop if this doesn't look like an accessor spec.
552  if (!Tok.is(tok::identifier)) {
553  // If the user wrote a completely empty list, use a special diagnostic.
554  if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
555  AccessorNames[AK_Put] == nullptr &&
556  AccessorNames[AK_Get] == nullptr) {
557  Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
558  break;
559  }
560 
561  Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
562  break;
563  }
564 
565  AccessorKind Kind;
566  SourceLocation KindLoc = Tok.getLocation();
567  StringRef KindStr = Tok.getIdentifierInfo()->getName();
568  if (KindStr == "get") {
569  Kind = AK_Get;
570  } else if (KindStr == "put") {
571  Kind = AK_Put;
572 
573  // Recover from the common mistake of using 'set' instead of 'put'.
574  } else if (KindStr == "set") {
575  Diag(KindLoc, diag::err_ms_property_has_set_accessor)
576  << FixItHint::CreateReplacement(KindLoc, "put");
577  Kind = AK_Put;
578 
579  // Handle the mistake of forgetting the accessor kind by skipping
580  // this accessor.
581  } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
582  Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
583  ConsumeToken();
584  HasInvalidAccessor = true;
585  goto next_property_accessor;
586 
587  // Otherwise, complain about the unknown accessor kind.
588  } else {
589  Diag(KindLoc, diag::err_ms_property_unknown_accessor);
590  HasInvalidAccessor = true;
591  Kind = AK_Invalid;
592 
593  // Try to keep parsing unless it doesn't look like an accessor spec.
594  if (!NextToken().is(tok::equal))
595  break;
596  }
597 
598  // Consume the identifier.
599  ConsumeToken();
600 
601  // Consume the '='.
602  if (!TryConsumeToken(tok::equal)) {
603  Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
604  << KindStr;
605  break;
606  }
607 
608  // Expect the method name.
609  if (!Tok.is(tok::identifier)) {
610  Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
611  break;
612  }
613 
614  if (Kind == AK_Invalid) {
615  // Just drop invalid accessors.
616  } else if (AccessorNames[Kind] != nullptr) {
617  // Complain about the repeated accessor, ignore it, and keep parsing.
618  Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
619  } else {
620  AccessorNames[Kind] = Tok.getIdentifierInfo();
621  }
622  ConsumeToken();
623 
624  next_property_accessor:
625  // Keep processing accessors until we run out.
626  if (TryConsumeToken(tok::comma))
627  continue;
628 
629  // If we run into the ')', stop without consuming it.
630  if (Tok.is(tok::r_paren))
631  break;
632 
633  Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
634  break;
635  }
636 
637  // Only add the property attribute if it was well-formed.
638  if (!HasInvalidAccessor)
639  Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
640  AccessorNames[AK_Get], AccessorNames[AK_Put],
642  T.skipToEnd();
643  return !HasInvalidAccessor;
644  }
645 
646  unsigned NumArgs =
647  ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
649 
650  // If this attribute's args were parsed, and it was expected to have
651  // arguments but none were provided, emit a diagnostic.
652  if (!Attrs.empty() && Attrs.begin()->getMaxArgs() && !NumArgs) {
653  Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
654  return false;
655  }
656  return true;
657 }
658 
659 /// [MS] decl-specifier:
660 /// __declspec ( extended-decl-modifier-seq )
661 ///
662 /// [MS] extended-decl-modifier-seq:
663 /// extended-decl-modifier[opt]
664 /// extended-decl-modifier extended-decl-modifier-seq
665 void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
666  SourceLocation *End) {
667  assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
668  assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
669 
670  while (Tok.is(tok::kw___declspec)) {
671  ConsumeToken();
672  BalancedDelimiterTracker T(*this, tok::l_paren);
673  if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
674  tok::r_paren))
675  return;
676 
677  // An empty declspec is perfectly legal and should not warn. Additionally,
678  // you can specify multiple attributes per declspec.
679  while (Tok.isNot(tok::r_paren)) {
680  // Attribute not present.
681  if (TryConsumeToken(tok::comma))
682  continue;
683 
684  // We expect either a well-known identifier or a generic string. Anything
685  // else is a malformed declspec.
686  bool IsString = Tok.getKind() == tok::string_literal;
687  if (!IsString && Tok.getKind() != tok::identifier &&
688  Tok.getKind() != tok::kw_restrict) {
689  Diag(Tok, diag::err_ms_declspec_type);
690  T.skipToEnd();
691  return;
692  }
693 
694  IdentifierInfo *AttrName;
695  SourceLocation AttrNameLoc;
696  if (IsString) {
697  SmallString<8> StrBuffer;
698  bool Invalid = false;
699  StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
700  if (Invalid) {
701  T.skipToEnd();
702  return;
703  }
704  AttrName = PP.getIdentifierInfo(Str);
705  AttrNameLoc = ConsumeStringToken();
706  } else {
707  AttrName = Tok.getIdentifierInfo();
708  AttrNameLoc = ConsumeToken();
709  }
710 
711  bool AttrHandled = false;
712 
713  // Parse attribute arguments.
714  if (Tok.is(tok::l_paren))
715  AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
716  else if (AttrName->getName() == "property")
717  // The property attribute must have an argument list.
718  Diag(Tok.getLocation(), diag::err_expected_lparen_after)
719  << AttrName->getName();
720 
721  if (!AttrHandled)
722  Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
724  }
725  T.consumeClose();
726  if (End)
727  *End = T.getCloseLocation();
728  }
729 }
730 
731 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
732  // Treat these like attributes
733  while (true) {
734  switch (Tok.getKind()) {
735  case tok::kw___fastcall:
736  case tok::kw___stdcall:
737  case tok::kw___thiscall:
738  case tok::kw___regcall:
739  case tok::kw___cdecl:
740  case tok::kw___vectorcall:
741  case tok::kw___ptr64:
742  case tok::kw___w64:
743  case tok::kw___ptr32:
744  case tok::kw___sptr:
745  case tok::kw___uptr: {
746  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
747  SourceLocation AttrNameLoc = ConsumeToken();
748  attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
750  break;
751  }
752  default:
753  return;
754  }
755  }
756 }
757 
758 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
759  SourceLocation StartLoc = Tok.getLocation();
760  SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
761 
762  if (EndLoc.isValid()) {
763  SourceRange Range(StartLoc, EndLoc);
764  Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
765  }
766 }
767 
768 SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
769  SourceLocation EndLoc;
770 
771  while (true) {
772  switch (Tok.getKind()) {
773  case tok::kw_const:
774  case tok::kw_volatile:
775  case tok::kw___fastcall:
776  case tok::kw___stdcall:
777  case tok::kw___thiscall:
778  case tok::kw___cdecl:
779  case tok::kw___vectorcall:
780  case tok::kw___ptr32:
781  case tok::kw___ptr64:
782  case tok::kw___w64:
783  case tok::kw___unaligned:
784  case tok::kw___sptr:
785  case tok::kw___uptr:
786  EndLoc = ConsumeToken();
787  break;
788  default:
789  return EndLoc;
790  }
791  }
792 }
793 
794 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
795  // Treat these like attributes
796  while (Tok.is(tok::kw___pascal)) {
797  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
798  SourceLocation AttrNameLoc = ConsumeToken();
799  attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
801  }
802 }
803 
804 void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
805  // Treat these like attributes
806  while (Tok.is(tok::kw___kernel)) {
807  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
808  SourceLocation AttrNameLoc = ConsumeToken();
809  attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
811  }
812 }
813 
814 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
815  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
816  SourceLocation AttrNameLoc = Tok.getLocation();
817  Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
819 }
820 
821 void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
822  // Treat these like attributes, even though they're type specifiers.
823  while (true) {
824  switch (Tok.getKind()) {
825  case tok::kw__Nonnull:
826  case tok::kw__Nullable:
827  case tok::kw__Null_unspecified: {
828  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
829  SourceLocation AttrNameLoc = ConsumeToken();
830  if (!getLangOpts().ObjC)
831  Diag(AttrNameLoc, diag::ext_nullability)
832  << AttrName;
833  attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
835  break;
836  }
837  default:
838  return;
839  }
840  }
841 }
842 
843 static bool VersionNumberSeparator(const char Separator) {
844  return (Separator == '.' || Separator == '_');
845 }
846 
847 /// Parse a version number.
848 ///
849 /// version:
850 /// simple-integer
851 /// simple-integer '.' simple-integer
852 /// simple-integer '_' simple-integer
853 /// simple-integer '.' simple-integer '.' simple-integer
854 /// simple-integer '_' simple-integer '_' simple-integer
855 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
856  Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
857 
858  if (!Tok.is(tok::numeric_constant)) {
859  Diag(Tok, diag::err_expected_version);
860  SkipUntil(tok::comma, tok::r_paren,
862  return VersionTuple();
863  }
864 
865  // Parse the major (and possibly minor and subminor) versions, which
866  // are stored in the numeric constant. We utilize a quirk of the
867  // lexer, which is that it handles something like 1.2.3 as a single
868  // numeric constant, rather than two separate tokens.
869  SmallString<512> Buffer;
870  Buffer.resize(Tok.getLength()+1);
871  const char *ThisTokBegin = &Buffer[0];
872 
873  // Get the spelling of the token, which eliminates trigraphs, etc.
874  bool Invalid = false;
875  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
876  if (Invalid)
877  return VersionTuple();
878 
879  // Parse the major version.
880  unsigned AfterMajor = 0;
881  unsigned Major = 0;
882  while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
883  Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
884  ++AfterMajor;
885  }
886 
887  if (AfterMajor == 0) {
888  Diag(Tok, diag::err_expected_version);
889  SkipUntil(tok::comma, tok::r_paren,
891  return VersionTuple();
892  }
893 
894  if (AfterMajor == ActualLength) {
895  ConsumeToken();
896 
897  // We only had a single version component.
898  if (Major == 0) {
899  Diag(Tok, diag::err_zero_version);
900  return VersionTuple();
901  }
902 
903  return VersionTuple(Major);
904  }
905 
906  const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
907  if (!VersionNumberSeparator(AfterMajorSeparator)
908  || (AfterMajor + 1 == ActualLength)) {
909  Diag(Tok, diag::err_expected_version);
910  SkipUntil(tok::comma, tok::r_paren,
912  return VersionTuple();
913  }
914 
915  // Parse the minor version.
916  unsigned AfterMinor = AfterMajor + 1;
917  unsigned Minor = 0;
918  while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
919  Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
920  ++AfterMinor;
921  }
922 
923  if (AfterMinor == ActualLength) {
924  ConsumeToken();
925 
926  // We had major.minor.
927  if (Major == 0 && Minor == 0) {
928  Diag(Tok, diag::err_zero_version);
929  return VersionTuple();
930  }
931 
932  return VersionTuple(Major, Minor);
933  }
934 
935  const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
936  // If what follows is not a '.' or '_', we have a problem.
937  if (!VersionNumberSeparator(AfterMinorSeparator)) {
938  Diag(Tok, diag::err_expected_version);
939  SkipUntil(tok::comma, tok::r_paren,
941  return VersionTuple();
942  }
943 
944  // Warn if separators, be it '.' or '_', do not match.
945  if (AfterMajorSeparator != AfterMinorSeparator)
946  Diag(Tok, diag::warn_expected_consistent_version_separator);
947 
948  // Parse the subminor version.
949  unsigned AfterSubminor = AfterMinor + 1;
950  unsigned Subminor = 0;
951  while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
952  Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
953  ++AfterSubminor;
954  }
955 
956  if (AfterSubminor != ActualLength) {
957  Diag(Tok, diag::err_expected_version);
958  SkipUntil(tok::comma, tok::r_paren,
960  return VersionTuple();
961  }
962  ConsumeToken();
963  return VersionTuple(Major, Minor, Subminor);
964 }
965 
966 /// Parse the contents of the "availability" attribute.
967 ///
968 /// availability-attribute:
969 /// 'availability' '(' platform ',' opt-strict version-arg-list,
970 /// opt-replacement, opt-message')'
971 ///
972 /// platform:
973 /// identifier
974 ///
975 /// opt-strict:
976 /// 'strict' ','
977 ///
978 /// version-arg-list:
979 /// version-arg
980 /// version-arg ',' version-arg-list
981 ///
982 /// version-arg:
983 /// 'introduced' '=' version
984 /// 'deprecated' '=' version
985 /// 'obsoleted' = version
986 /// 'unavailable'
987 /// opt-replacement:
988 /// 'replacement' '=' <string>
989 /// opt-message:
990 /// 'message' '=' <string>
991 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
992  SourceLocation AvailabilityLoc,
993  ParsedAttributes &attrs,
994  SourceLocation *endLoc,
995  IdentifierInfo *ScopeName,
996  SourceLocation ScopeLoc,
997  ParsedAttr::Syntax Syntax) {
998  enum { Introduced, Deprecated, Obsoleted, Unknown };
999  AvailabilityChange Changes[Unknown];
1000  ExprResult MessageExpr, ReplacementExpr;
1001 
1002  // Opening '('.
1003  BalancedDelimiterTracker T(*this, tok::l_paren);
1004  if (T.consumeOpen()) {
1005  Diag(Tok, diag::err_expected) << tok::l_paren;
1006  return;
1007  }
1008 
1009  // Parse the platform name.
1010  if (Tok.isNot(tok::identifier)) {
1011  Diag(Tok, diag::err_availability_expected_platform);
1012  SkipUntil(tok::r_paren, StopAtSemi);
1013  return;
1014  }
1015  IdentifierLoc *Platform = ParseIdentifierLoc();
1016  if (const IdentifierInfo *const Ident = Platform->Ident) {
1017  // Canonicalize platform name from "macosx" to "macos".
1018  if (Ident->getName() == "macosx")
1019  Platform->Ident = PP.getIdentifierInfo("macos");
1020  // Canonicalize platform name from "macosx_app_extension" to
1021  // "macos_app_extension".
1022  else if (Ident->getName() == "macosx_app_extension")
1023  Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1024  else
1025  Platform->Ident = PP.getIdentifierInfo(
1026  AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1027  }
1028 
1029  // Parse the ',' following the platform name.
1030  if (ExpectAndConsume(tok::comma)) {
1031  SkipUntil(tok::r_paren, StopAtSemi);
1032  return;
1033  }
1034 
1035  // If we haven't grabbed the pointers for the identifiers
1036  // "introduced", "deprecated", and "obsoleted", do so now.
1037  if (!Ident_introduced) {
1038  Ident_introduced = PP.getIdentifierInfo("introduced");
1039  Ident_deprecated = PP.getIdentifierInfo("deprecated");
1040  Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
1041  Ident_unavailable = PP.getIdentifierInfo("unavailable");
1042  Ident_message = PP.getIdentifierInfo("message");
1043  Ident_strict = PP.getIdentifierInfo("strict");
1044  Ident_replacement = PP.getIdentifierInfo("replacement");
1045  }
1046 
1047  // Parse the optional "strict", the optional "replacement" and the set of
1048  // introductions/deprecations/removals.
1049  SourceLocation UnavailableLoc, StrictLoc;
1050  do {
1051  if (Tok.isNot(tok::identifier)) {
1052  Diag(Tok, diag::err_availability_expected_change);
1053  SkipUntil(tok::r_paren, StopAtSemi);
1054  return;
1055  }
1056  IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1057  SourceLocation KeywordLoc = ConsumeToken();
1058 
1059  if (Keyword == Ident_strict) {
1060  if (StrictLoc.isValid()) {
1061  Diag(KeywordLoc, diag::err_availability_redundant)
1062  << Keyword << SourceRange(StrictLoc);
1063  }
1064  StrictLoc = KeywordLoc;
1065  continue;
1066  }
1067 
1068  if (Keyword == Ident_unavailable) {
1069  if (UnavailableLoc.isValid()) {
1070  Diag(KeywordLoc, diag::err_availability_redundant)
1071  << Keyword << SourceRange(UnavailableLoc);
1072  }
1073  UnavailableLoc = KeywordLoc;
1074  continue;
1075  }
1076 
1077  if (Keyword == Ident_deprecated && Platform->Ident &&
1078  Platform->Ident->isStr("swift")) {
1079  // For swift, we deprecate for all versions.
1080  if (Changes[Deprecated].KeywordLoc.isValid()) {
1081  Diag(KeywordLoc, diag::err_availability_redundant)
1082  << Keyword
1083  << SourceRange(Changes[Deprecated].KeywordLoc);
1084  }
1085 
1086  Changes[Deprecated].KeywordLoc = KeywordLoc;
1087  // Use a fake version here.
1088  Changes[Deprecated].Version = VersionTuple(1);
1089  continue;
1090  }
1091 
1092  if (Tok.isNot(tok::equal)) {
1093  Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1094  SkipUntil(tok::r_paren, StopAtSemi);
1095  return;
1096  }
1097  ConsumeToken();
1098  if (Keyword == Ident_message || Keyword == Ident_replacement) {
1099  if (Tok.isNot(tok::string_literal)) {
1100  Diag(Tok, diag::err_expected_string_literal)
1101  << /*Source='availability attribute'*/2;
1102  SkipUntil(tok::r_paren, StopAtSemi);
1103  return;
1104  }
1105  if (Keyword == Ident_message)
1106  MessageExpr = ParseStringLiteralExpression();
1107  else
1108  ReplacementExpr = ParseStringLiteralExpression();
1109  // Also reject wide string literals.
1110  if (StringLiteral *MessageStringLiteral =
1111  cast_or_null<StringLiteral>(MessageExpr.get())) {
1112  if (MessageStringLiteral->getCharByteWidth() != 1) {
1113  Diag(MessageStringLiteral->getSourceRange().getBegin(),
1114  diag::err_expected_string_literal)
1115  << /*Source='availability attribute'*/ 2;
1116  SkipUntil(tok::r_paren, StopAtSemi);
1117  return;
1118  }
1119  }
1120  if (Keyword == Ident_message)
1121  break;
1122  else
1123  continue;
1124  }
1125 
1126  // Special handling of 'NA' only when applied to introduced or
1127  // deprecated.
1128  if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1129  Tok.is(tok::identifier)) {
1130  IdentifierInfo *NA = Tok.getIdentifierInfo();
1131  if (NA->getName() == "NA") {
1132  ConsumeToken();
1133  if (Keyword == Ident_introduced)
1134  UnavailableLoc = KeywordLoc;
1135  continue;
1136  }
1137  }
1138 
1139  SourceRange VersionRange;
1140  VersionTuple Version = ParseVersionTuple(VersionRange);
1141 
1142  if (Version.empty()) {
1143  SkipUntil(tok::r_paren, StopAtSemi);
1144  return;
1145  }
1146 
1147  unsigned Index;
1148  if (Keyword == Ident_introduced)
1149  Index = Introduced;
1150  else if (Keyword == Ident_deprecated)
1151  Index = Deprecated;
1152  else if (Keyword == Ident_obsoleted)
1153  Index = Obsoleted;
1154  else
1155  Index = Unknown;
1156 
1157  if (Index < Unknown) {
1158  if (!Changes[Index].KeywordLoc.isInvalid()) {
1159  Diag(KeywordLoc, diag::err_availability_redundant)
1160  << Keyword
1161  << SourceRange(Changes[Index].KeywordLoc,
1162  Changes[Index].VersionRange.getEnd());
1163  }
1164 
1165  Changes[Index].KeywordLoc = KeywordLoc;
1166  Changes[Index].Version = Version;
1167  Changes[Index].VersionRange = VersionRange;
1168  } else {
1169  Diag(KeywordLoc, diag::err_availability_unknown_change)
1170  << Keyword << VersionRange;
1171  }
1172 
1173  } while (TryConsumeToken(tok::comma));
1174 
1175  // Closing ')'.
1176  if (T.consumeClose())
1177  return;
1178 
1179  if (endLoc)
1180  *endLoc = T.getCloseLocation();
1181 
1182  // The 'unavailable' availability cannot be combined with any other
1183  // availability changes. Make sure that hasn't happened.
1184  if (UnavailableLoc.isValid()) {
1185  bool Complained = false;
1186  for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1187  if (Changes[Index].KeywordLoc.isValid()) {
1188  if (!Complained) {
1189  Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1190  << SourceRange(Changes[Index].KeywordLoc,
1191  Changes[Index].VersionRange.getEnd());
1192  Complained = true;
1193  }
1194 
1195  // Clear out the availability.
1196  Changes[Index] = AvailabilityChange();
1197  }
1198  }
1199  }
1200 
1201  // Record this attribute
1202  attrs.addNew(&Availability,
1203  SourceRange(AvailabilityLoc, T.getCloseLocation()),
1204  ScopeName, ScopeLoc,
1205  Platform,
1206  Changes[Introduced],
1207  Changes[Deprecated],
1208  Changes[Obsoleted],
1209  UnavailableLoc, MessageExpr.get(),
1210  Syntax, StrictLoc, ReplacementExpr.get());
1211 }
1212 
1213 /// Parse the contents of the "external_source_symbol" attribute.
1214 ///
1215 /// external-source-symbol-attribute:
1216 /// 'external_source_symbol' '(' keyword-arg-list ')'
1217 ///
1218 /// keyword-arg-list:
1219 /// keyword-arg
1220 /// keyword-arg ',' keyword-arg-list
1221 ///
1222 /// keyword-arg:
1223 /// 'language' '=' <string>
1224 /// 'defined_in' '=' <string>
1225 /// 'generated_declaration'
1226 void Parser::ParseExternalSourceSymbolAttribute(
1227  IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1228  ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1229  SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1230  // Opening '('.
1231  BalancedDelimiterTracker T(*this, tok::l_paren);
1232  if (T.expectAndConsume())
1233  return;
1234 
1235  // Initialize the pointers for the keyword identifiers when required.
1236  if (!Ident_language) {
1237  Ident_language = PP.getIdentifierInfo("language");
1238  Ident_defined_in = PP.getIdentifierInfo("defined_in");
1239  Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1240  }
1241 
1243  bool HasLanguage = false;
1244  ExprResult DefinedInExpr;
1245  bool HasDefinedIn = false;
1246  IdentifierLoc *GeneratedDeclaration = nullptr;
1247 
1248  // Parse the language/defined_in/generated_declaration keywords
1249  do {
1250  if (Tok.isNot(tok::identifier)) {
1251  Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1252  SkipUntil(tok::r_paren, StopAtSemi);
1253  return;
1254  }
1255 
1256  SourceLocation KeywordLoc = Tok.getLocation();
1257  IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1258  if (Keyword == Ident_generated_declaration) {
1259  if (GeneratedDeclaration) {
1260  Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1261  SkipUntil(tok::r_paren, StopAtSemi);
1262  return;
1263  }
1264  GeneratedDeclaration = ParseIdentifierLoc();
1265  continue;
1266  }
1267 
1268  if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1269  Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1270  SkipUntil(tok::r_paren, StopAtSemi);
1271  return;
1272  }
1273 
1274  ConsumeToken();
1275  if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1276  Keyword->getName())) {
1277  SkipUntil(tok::r_paren, StopAtSemi);
1278  return;
1279  }
1280 
1281  bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1282  if (Keyword == Ident_language)
1283  HasLanguage = true;
1284  else
1285  HasDefinedIn = true;
1286 
1287  if (Tok.isNot(tok::string_literal)) {
1288  Diag(Tok, diag::err_expected_string_literal)
1289  << /*Source='external_source_symbol attribute'*/ 3
1290  << /*language | source container*/ (Keyword != Ident_language);
1291  SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1292  continue;
1293  }
1294  if (Keyword == Ident_language) {
1295  if (HadLanguage) {
1296  Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1297  << Keyword;
1298  ParseStringLiteralExpression();
1299  continue;
1300  }
1301  Language = ParseStringLiteralExpression();
1302  } else {
1303  assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1304  if (HadDefinedIn) {
1305  Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1306  << Keyword;
1307  ParseStringLiteralExpression();
1308  continue;
1309  }
1310  DefinedInExpr = ParseStringLiteralExpression();
1311  }
1312  } while (TryConsumeToken(tok::comma));
1313 
1314  // Closing ')'.
1315  if (T.consumeClose())
1316  return;
1317  if (EndLoc)
1318  *EndLoc = T.getCloseLocation();
1319 
1320  ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1321  GeneratedDeclaration};
1322  Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1323  ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1324 }
1325 
1326 /// Parse the contents of the "objc_bridge_related" attribute.
1327 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1328 /// related_class:
1329 /// Identifier
1330 ///
1331 /// opt-class_method:
1332 /// Identifier: | <empty>
1333 ///
1334 /// opt-instance_method:
1335 /// Identifier | <empty>
1336 ///
1337 void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1338  SourceLocation ObjCBridgeRelatedLoc,
1339  ParsedAttributes &attrs,
1340  SourceLocation *endLoc,
1341  IdentifierInfo *ScopeName,
1342  SourceLocation ScopeLoc,
1343  ParsedAttr::Syntax Syntax) {
1344  // Opening '('.
1345  BalancedDelimiterTracker T(*this, tok::l_paren);
1346  if (T.consumeOpen()) {
1347  Diag(Tok, diag::err_expected) << tok::l_paren;
1348  return;
1349  }
1350 
1351  // Parse the related class name.
1352  if (Tok.isNot(tok::identifier)) {
1353  Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1354  SkipUntil(tok::r_paren, StopAtSemi);
1355  return;
1356  }
1357  IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1358  if (ExpectAndConsume(tok::comma)) {
1359  SkipUntil(tok::r_paren, StopAtSemi);
1360  return;
1361  }
1362 
1363  // Parse class method name. It's non-optional in the sense that a trailing
1364  // comma is required, but it can be the empty string, and then we record a
1365  // nullptr.
1366  IdentifierLoc *ClassMethod = nullptr;
1367  if (Tok.is(tok::identifier)) {
1368  ClassMethod = ParseIdentifierLoc();
1369  if (!TryConsumeToken(tok::colon)) {
1370  Diag(Tok, diag::err_objcbridge_related_selector_name);
1371  SkipUntil(tok::r_paren, StopAtSemi);
1372  return;
1373  }
1374  }
1375  if (!TryConsumeToken(tok::comma)) {
1376  if (Tok.is(tok::colon))
1377  Diag(Tok, diag::err_objcbridge_related_selector_name);
1378  else
1379  Diag(Tok, diag::err_expected) << tok::comma;
1380  SkipUntil(tok::r_paren, StopAtSemi);
1381  return;
1382  }
1383 
1384  // Parse instance method name. Also non-optional but empty string is
1385  // permitted.
1386  IdentifierLoc *InstanceMethod = nullptr;
1387  if (Tok.is(tok::identifier))
1388  InstanceMethod = ParseIdentifierLoc();
1389  else if (Tok.isNot(tok::r_paren)) {
1390  Diag(Tok, diag::err_expected) << tok::r_paren;
1391  SkipUntil(tok::r_paren, StopAtSemi);
1392  return;
1393  }
1394 
1395  // Closing ')'.
1396  if (T.consumeClose())
1397  return;
1398 
1399  if (endLoc)
1400  *endLoc = T.getCloseLocation();
1401 
1402  // Record this attribute
1403  attrs.addNew(&ObjCBridgeRelated,
1404  SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1405  ScopeName, ScopeLoc,
1406  RelatedClass,
1407  ClassMethod,
1408  InstanceMethod,
1409  Syntax);
1410 }
1411 
1412 // Late Parsed Attributes:
1413 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1414 
1415 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1416 
1417 void Parser::LateParsedClass::ParseLexedAttributes() {
1418  Self->ParseLexedAttributes(*Class);
1419 }
1420 
1421 void Parser::LateParsedAttribute::ParseLexedAttributes() {
1422  Self->ParseLexedAttribute(*this, true, false);
1423 }
1424 
1425 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1426 /// scope appropriately.
1427 void Parser::ParseLexedAttributes(ParsingClass &Class) {
1428  // Deal with templates
1429  // FIXME: Test cases to make sure this does the right thing for templates.
1430  bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1431  ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1432  HasTemplateScope);
1433  if (HasTemplateScope)
1434  Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1435 
1436  // Set or update the scope flags.
1437  bool AlreadyHasClassScope = Class.TopLevelClass;
1438  unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
1439  ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1440  ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1441 
1442  // Enter the scope of nested classes
1443  if (!AlreadyHasClassScope)
1445  Class.TagOrTemplate);
1446  if (!Class.LateParsedDeclarations.empty()) {
1447  for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1448  Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1449  }
1450  }
1451 
1452  if (!AlreadyHasClassScope)
1454  Class.TagOrTemplate);
1455 }
1456 
1457 /// Parse all attributes in LAs, and attach them to Decl D.
1458 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1459  bool EnterScope, bool OnDefinition) {
1460  assert(LAs.parseSoon() &&
1461  "Attribute list should be marked for immediate parsing.");
1462  for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1463  if (D)
1464  LAs[i]->addDecl(D);
1465  ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1466  delete LAs[i];
1467  }
1468  LAs.clear();
1469 }
1470 
1471 /// Finish parsing an attribute for which parsing was delayed.
1472 /// This will be called at the end of parsing a class declaration
1473 /// for each LateParsedAttribute. We consume the saved tokens and
1474 /// create an attribute with the arguments filled in. We add this
1475 /// to the Attribute list for the decl.
1476 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1477  bool EnterScope, bool OnDefinition) {
1478  // Create a fake EOF so that attribute parsing won't go off the end of the
1479  // attribute.
1480  Token AttrEnd;
1481  AttrEnd.startToken();
1482  AttrEnd.setKind(tok::eof);
1483  AttrEnd.setLocation(Tok.getLocation());
1484  AttrEnd.setEofData(LA.Toks.data());
1485  LA.Toks.push_back(AttrEnd);
1486 
1487  // Append the current token at the end of the new token stream so that it
1488  // doesn't get lost.
1489  LA.Toks.push_back(Tok);
1490  PP.EnterTokenStream(LA.Toks, true, /*IsReinject=*/true);
1491  // Consume the previously pushed token.
1492  ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1493 
1494  ParsedAttributes Attrs(AttrFactory);
1495  SourceLocation endLoc;
1496 
1497  if (LA.Decls.size() > 0) {
1498  Decl *D = LA.Decls[0];
1499  NamedDecl *ND = dyn_cast<NamedDecl>(D);
1500  RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1501 
1502  // Allow 'this' within late-parsed attributes.
1503  Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
1504  ND && ND->isCXXInstanceMember());
1505 
1506  if (LA.Decls.size() == 1) {
1507  // If the Decl is templatized, add template parameters to scope.
1508  bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1509  ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1510  if (HasTemplateScope)
1511  Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1512 
1513  // If the Decl is on a function, add function parameters to the scope.
1514  bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1515  ParseScope FnScope(
1517  HasFunScope);
1518  if (HasFunScope)
1519  Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1520 
1521  ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1522  nullptr, SourceLocation(), ParsedAttr::AS_GNU,
1523  nullptr);
1524 
1525  if (HasFunScope) {
1526  Actions.ActOnExitFunctionContext();
1527  FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1528  }
1529  if (HasTemplateScope) {
1530  TempScope.Exit();
1531  }
1532  } else {
1533  // If there are multiple decls, then the decl cannot be within the
1534  // function scope.
1535  ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1536  nullptr, SourceLocation(), ParsedAttr::AS_GNU,
1537  nullptr);
1538  }
1539  } else {
1540  Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1541  }
1542 
1543  if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
1544  Attrs.begin()->isKnownToGCC())
1545  Diag(Tok, diag::warn_attribute_on_function_definition)
1546  << &LA.AttrName;
1547 
1548  for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
1549  Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1550 
1551  // Due to a parsing error, we either went over the cached tokens or
1552  // there are still cached tokens left, so we skip the leftover tokens.
1553  while (Tok.isNot(tok::eof))
1554  ConsumeAnyToken();
1555 
1556  if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1557  ConsumeAnyToken();
1558 }
1559 
1560 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1561  SourceLocation AttrNameLoc,
1562  ParsedAttributes &Attrs,
1563  SourceLocation *EndLoc,
1564  IdentifierInfo *ScopeName,
1565  SourceLocation ScopeLoc,
1566  ParsedAttr::Syntax Syntax) {
1567  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1568 
1569  BalancedDelimiterTracker T(*this, tok::l_paren);
1570  T.consumeOpen();
1571 
1572  if (Tok.isNot(tok::identifier)) {
1573  Diag(Tok, diag::err_expected) << tok::identifier;
1574  T.skipToEnd();
1575  return;
1576  }
1577  IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1578 
1579  if (ExpectAndConsume(tok::comma)) {
1580  T.skipToEnd();
1581  return;
1582  }
1583 
1584  SourceRange MatchingCTypeRange;
1585  TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1586  if (MatchingCType.isInvalid()) {
1587  T.skipToEnd();
1588  return;
1589  }
1590 
1591  bool LayoutCompatible = false;
1592  bool MustBeNull = false;
1593  while (TryConsumeToken(tok::comma)) {
1594  if (Tok.isNot(tok::identifier)) {
1595  Diag(Tok, diag::err_expected) << tok::identifier;
1596  T.skipToEnd();
1597  return;
1598  }
1599  IdentifierInfo *Flag = Tok.getIdentifierInfo();
1600  if (Flag->isStr("layout_compatible"))
1601  LayoutCompatible = true;
1602  else if (Flag->isStr("must_be_null"))
1603  MustBeNull = true;
1604  else {
1605  Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1606  T.skipToEnd();
1607  return;
1608  }
1609  ConsumeToken(); // consume flag
1610  }
1611 
1612  if (!T.consumeClose()) {
1613  Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1614  ArgumentKind, MatchingCType.get(),
1615  LayoutCompatible, MustBeNull, Syntax);
1616  }
1617 
1618  if (EndLoc)
1619  *EndLoc = T.getCloseLocation();
1620 }
1621 
1622 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1623 /// of a C++11 attribute-specifier in a location where an attribute is not
1624 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1625 /// situation.
1626 ///
1627 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1628 /// this doesn't appear to actually be an attribute-specifier, and the caller
1629 /// should try to parse it.
1630 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1631  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1632 
1633  switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1634  case CAK_NotAttributeSpecifier:
1635  // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1636  return false;
1637 
1638  case CAK_InvalidAttributeSpecifier:
1639  Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1640  return false;
1641 
1642  case CAK_AttributeSpecifier:
1643  // Parse and discard the attributes.
1644  SourceLocation BeginLoc = ConsumeBracket();
1645  ConsumeBracket();
1646  SkipUntil(tok::r_square);
1647  assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1648  SourceLocation EndLoc = ConsumeBracket();
1649  Diag(BeginLoc, diag::err_attributes_not_allowed)
1650  << SourceRange(BeginLoc, EndLoc);
1651  return true;
1652  }
1653  llvm_unreachable("All cases handled above.");
1654 }
1655 
1656 /// We have found the opening square brackets of a C++11
1657 /// attribute-specifier in a location where an attribute is not permitted, but
1658 /// we know where the attributes ought to be written. Parse them anyway, and
1659 /// provide a fixit moving them to the right place.
1660 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1661  SourceLocation CorrectLocation) {
1662  assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1663  Tok.is(tok::kw_alignas));
1664 
1665  // Consume the attributes.
1666  SourceLocation Loc = Tok.getLocation();
1667  ParseCXX11Attributes(Attrs);
1668  CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1669  // FIXME: use err_attributes_misplaced
1670  Diag(Loc, diag::err_attributes_not_allowed)
1671  << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1672  << FixItHint::CreateRemoval(AttrRange);
1673 }
1674 
1675 void Parser::DiagnoseProhibitedAttributes(
1676  const SourceRange &Range, const SourceLocation CorrectLocation) {
1677  if (CorrectLocation.isValid()) {
1678  CharSourceRange AttrRange(Range, true);
1679  Diag(CorrectLocation, diag::err_attributes_misplaced)
1680  << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1681  << FixItHint::CreateRemoval(AttrRange);
1682  } else
1683  Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
1684 }
1685 
1686 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1687  unsigned DiagID) {
1688  for (const ParsedAttr &AL : Attrs) {
1689  if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
1690  continue;
1691  if (AL.getKind() == ParsedAttr::UnknownAttribute)
1692  Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL;
1693  else {
1694  Diag(AL.getLoc(), DiagID) << AL;
1695  AL.setInvalid();
1696  }
1697  }
1698 }
1699 
1700 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1701 // applies to var, not the type Foo.
1702 // As an exception to the rule, __declspec(align(...)) before the
1703 // class-key affects the type instead of the variable.
1704 // Also, Microsoft-style [attributes] seem to affect the type instead of the
1705 // variable.
1706 // This function moves attributes that should apply to the type off DS to Attrs.
1707 void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1708  DeclSpec &DS,
1709  Sema::TagUseKind TUK) {
1710  if (TUK == Sema::TUK_Reference)
1711  return;
1712 
1714 
1715  for (ParsedAttr &AL : DS.getAttributes()) {
1716  if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1717  AL.isDeclspecAttribute()) ||
1718  AL.isMicrosoftAttribute())
1719  ToBeMoved.push_back(&AL);
1720  }
1721 
1722  for (ParsedAttr *AL : ToBeMoved) {
1723  DS.getAttributes().remove(AL);
1724  Attrs.addAtEnd(AL);
1725  }
1726 }
1727 
1728 /// ParseDeclaration - Parse a full 'declaration', which consists of
1729 /// declaration-specifiers, some number of declarators, and a semicolon.
1730 /// 'Context' should be a DeclaratorContext value. This returns the
1731 /// location of the semicolon in DeclEnd.
1732 ///
1733 /// declaration: [C99 6.7]
1734 /// block-declaration ->
1735 /// simple-declaration
1736 /// others [FIXME]
1737 /// [C++] template-declaration
1738 /// [C++] namespace-definition
1739 /// [C++] using-directive
1740 /// [C++] using-declaration
1741 /// [C++11/C11] static_assert-declaration
1742 /// others... [FIXME]
1743 ///
1745 Parser::ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
1746  ParsedAttributesWithRange &attrs,
1747  SourceLocation *DeclSpecStart) {
1748  ParenBraceBracketBalancer BalancerRAIIObj(*this);
1749  // Must temporarily exit the objective-c container scope for
1750  // parsing c none objective-c decls.
1751  ObjCDeclContextSwitch ObjCDC(*this);
1752 
1753  Decl *SingleDecl = nullptr;
1754  switch (Tok.getKind()) {
1755  case tok::kw_template:
1756  case tok::kw_export:
1757  ProhibitAttributes(attrs);
1758  SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
1759  break;
1760  case tok::kw_inline:
1761  // Could be the start of an inline namespace. Allowed as an ext in C++03.
1762  if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1763  ProhibitAttributes(attrs);
1764  SourceLocation InlineLoc = ConsumeToken();
1765  return ParseNamespace(Context, DeclEnd, InlineLoc);
1766  }
1767  return ParseSimpleDeclaration(Context, DeclEnd, attrs, true, nullptr,
1768  DeclSpecStart);
1769  case tok::kw_namespace:
1770  ProhibitAttributes(attrs);
1771  return ParseNamespace(Context, DeclEnd);
1772  case tok::kw_using:
1773  return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1774  DeclEnd, attrs);
1775  case tok::kw_static_assert:
1776  case tok::kw__Static_assert:
1777  ProhibitAttributes(attrs);
1778  SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1779  break;
1780  default:
1781  return ParseSimpleDeclaration(Context, DeclEnd, attrs, true, nullptr,
1782  DeclSpecStart);
1783  }
1784 
1785  // This routine returns a DeclGroup, if the thing we parsed only contains a
1786  // single decl, convert it now.
1787  return Actions.ConvertDeclToDeclGroup(SingleDecl);
1788 }
1789 
1790 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1791 /// declaration-specifiers init-declarator-list[opt] ';'
1792 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1793 /// init-declarator-list ';'
1794 ///[C90/C++]init-declarator-list ';' [TODO]
1795 /// [OMP] threadprivate-directive
1796 /// [OMP] allocate-directive [TODO]
1797 ///
1798 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1799 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1800 ///
1801 /// If RequireSemi is false, this does not check for a ';' at the end of the
1802 /// declaration. If it is true, it checks for and eats it.
1803 ///
1804 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1805 /// of a simple-declaration. If we find that we are, we also parse the
1806 /// for-range-initializer, and place it here.
1807 ///
1808 /// DeclSpecStart is used when decl-specifiers are parsed before parsing
1809 /// the Declaration. The SourceLocation for this Decl is set to
1810 /// DeclSpecStart if DeclSpecStart is non-null.
1811 Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(
1812  DeclaratorContext Context, SourceLocation &DeclEnd,
1813  ParsedAttributesWithRange &Attrs, bool RequireSemi, ForRangeInit *FRI,
1814  SourceLocation *DeclSpecStart) {
1815  // Parse the common declaration-specifiers piece.
1816  ParsingDeclSpec DS(*this);
1817 
1818  DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1819  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1820 
1821  // If we had a free-standing type definition with a missing semicolon, we
1822  // may get this far before the problem becomes obvious.
1823  if (DS.hasTagDefinition() &&
1824  DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1825  return nullptr;
1826 
1827  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1828  // declaration-specifiers init-declarator-list[opt] ';'
1829  if (Tok.is(tok::semi)) {
1830  ProhibitAttributes(Attrs);
1831  DeclEnd = Tok.getLocation();
1832  if (RequireSemi) ConsumeToken();
1833  RecordDecl *AnonRecord = nullptr;
1834  Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1835  DS, AnonRecord);
1836  DS.complete(TheDecl);
1837  if (AnonRecord) {
1838  Decl* decls[] = {AnonRecord, TheDecl};
1839  return Actions.BuildDeclaratorGroup(decls);
1840  }
1841  return Actions.ConvertDeclToDeclGroup(TheDecl);
1842  }
1843 
1844  if (DeclSpecStart)
1845  DS.SetRangeStart(*DeclSpecStart);
1846 
1847  DS.takeAttributesFrom(Attrs);
1848  return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1849 }
1850 
1851 /// Returns true if this might be the start of a declarator, or a common typo
1852 /// for a declarator.
1853 bool Parser::MightBeDeclarator(DeclaratorContext Context) {
1854  switch (Tok.getKind()) {
1855  case tok::annot_cxxscope:
1856  case tok::annot_template_id:
1857  case tok::caret:
1858  case tok::code_completion:
1859  case tok::coloncolon:
1860  case tok::ellipsis:
1861  case tok::kw___attribute:
1862  case tok::kw_operator:
1863  case tok::l_paren:
1864  case tok::star:
1865  return true;
1866 
1867  case tok::amp:
1868  case tok::ampamp:
1869  return getLangOpts().CPlusPlus;
1870 
1871  case tok::l_square: // Might be an attribute on an unnamed bit-field.
1872  return Context == DeclaratorContext::MemberContext &&
1873  getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
1874 
1875  case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1876  return Context == DeclaratorContext::MemberContext ||
1877  getLangOpts().CPlusPlus;
1878 
1879  case tok::identifier:
1880  switch (NextToken().getKind()) {
1881  case tok::code_completion:
1882  case tok::coloncolon:
1883  case tok::comma:
1884  case tok::equal:
1885  case tok::equalequal: // Might be a typo for '='.
1886  case tok::kw_alignas:
1887  case tok::kw_asm:
1888  case tok::kw___attribute:
1889  case tok::l_brace:
1890  case tok::l_paren:
1891  case tok::l_square:
1892  case tok::less:
1893  case tok::r_brace:
1894  case tok::r_paren:
1895  case tok::r_square:
1896  case tok::semi:
1897  return true;
1898 
1899  case tok::colon:
1900  // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1901  // and in block scope it's probably a label. Inside a class definition,
1902  // this is a bit-field.
1903  return Context == DeclaratorContext::MemberContext ||
1904  (getLangOpts().CPlusPlus &&
1905  Context == DeclaratorContext::FileContext);
1906 
1907  case tok::identifier: // Possible virt-specifier.
1908  return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1909 
1910  default:
1911  return false;
1912  }
1913 
1914  default:
1915  return false;
1916  }
1917 }
1918 
1919 /// Skip until we reach something which seems like a sensible place to pick
1920 /// up parsing after a malformed declaration. This will sometimes stop sooner
1921 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1923  while (true) {
1924  switch (Tok.getKind()) {
1925  case tok::l_brace:
1926  // Skip until matching }, then stop. We've probably skipped over
1927  // a malformed class or function definition or similar.
1928  ConsumeBrace();
1929  SkipUntil(tok::r_brace);
1930  if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1931  // This declaration isn't over yet. Keep skipping.
1932  continue;
1933  }
1934  TryConsumeToken(tok::semi);
1935  return;
1936 
1937  case tok::l_square:
1938  ConsumeBracket();
1939  SkipUntil(tok::r_square);
1940  continue;
1941 
1942  case tok::l_paren:
1943  ConsumeParen();
1944  SkipUntil(tok::r_paren);
1945  continue;
1946 
1947  case tok::r_brace:
1948  return;
1949 
1950  case tok::semi:
1951  ConsumeToken();
1952  return;
1953 
1954  case tok::kw_inline:
1955  // 'inline namespace' at the start of a line is almost certainly
1956  // a good place to pick back up parsing, except in an Objective-C
1957  // @interface context.
1958  if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1959  (!ParsingInObjCContainer || CurParsedObjCImpl))
1960  return;
1961  break;
1962 
1963  case tok::kw_namespace:
1964  // 'namespace' at the start of a line is almost certainly a good
1965  // place to pick back up parsing, except in an Objective-C
1966  // @interface context.
1967  if (Tok.isAtStartOfLine() &&
1968  (!ParsingInObjCContainer || CurParsedObjCImpl))
1969  return;
1970  break;
1971 
1972  case tok::at:
1973  // @end is very much like } in Objective-C contexts.
1974  if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1975  ParsingInObjCContainer)
1976  return;
1977  break;
1978 
1979  case tok::minus:
1980  case tok::plus:
1981  // - and + probably start new method declarations in Objective-C contexts.
1982  if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1983  return;
1984  break;
1985 
1986  case tok::eof:
1987  case tok::annot_module_begin:
1988  case tok::annot_module_end:
1989  case tok::annot_module_include:
1990  return;
1991 
1992  default:
1993  break;
1994  }
1995 
1996  ConsumeAnyToken();
1997  }
1998 }
1999 
2000 /// ParseDeclGroup - Having concluded that this is either a function
2001 /// definition or a group of object declarations, actually parse the
2002 /// result.
2003 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
2004  DeclaratorContext Context,
2005  SourceLocation *DeclEnd,
2006  ForRangeInit *FRI) {
2007  // Parse the first declarator.
2008  ParsingDeclarator D(*this, DS, Context);
2009  ParseDeclarator(D);
2010 
2011  // Bail out if the first declarator didn't seem well-formed.
2012  if (!D.hasName() && !D.mayOmitIdentifier()) {
2014  return nullptr;
2015  }
2016 
2017  if (Tok.is(tok::kw_requires))
2018  ParseTrailingRequiresClause(D);
2019 
2020  // Save late-parsed attributes for now; they need to be parsed in the
2021  // appropriate function scope after the function Decl has been constructed.
2022  // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
2023  LateParsedAttrList LateParsedAttrs(true);
2024  if (D.isFunctionDeclarator()) {
2025  MaybeParseGNUAttributes(D, &LateParsedAttrs);
2026 
2027  // The _Noreturn keyword can't appear here, unlike the GNU noreturn
2028  // attribute. If we find the keyword here, tell the user to put it
2029  // at the start instead.
2030  if (Tok.is(tok::kw__Noreturn)) {
2031  SourceLocation Loc = ConsumeToken();
2032  const char *PrevSpec;
2033  unsigned DiagID;
2034 
2035  // We can offer a fixit if it's valid to mark this function as _Noreturn
2036  // and we don't have any other declarators in this declaration.
2037  bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2038  MaybeParseGNUAttributes(D, &LateParsedAttrs);
2039  Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
2040 
2041  Diag(Loc, diag::err_c11_noreturn_misplaced)
2042  << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
2043  << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
2044  : FixItHint());
2045  }
2046  }
2047 
2048  // Check to see if we have a function *definition* which must have a body.
2049  if (D.isFunctionDeclarator() &&
2050  // Look at the next token to make sure that this isn't a function
2051  // declaration. We have to check this because __attribute__ might be the
2052  // start of a function definition in GCC-extended K&R C.
2053  !isDeclarationAfterDeclarator()) {
2054 
2055  // Function definitions are only allowed at file scope and in C++ classes.
2056  // The C++ inline method definition case is handled elsewhere, so we only
2057  // need to handle the file scope definition case.
2058  if (Context == DeclaratorContext::FileContext) {
2059  if (isStartOfFunctionDefinition(D)) {
2061  Diag(Tok, diag::err_function_declared_typedef);
2062 
2063  // Recover by treating the 'typedef' as spurious.
2065  }
2066 
2067  Decl *TheDecl =
2068  ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
2069  return Actions.ConvertDeclToDeclGroup(TheDecl);
2070  }
2071 
2072  if (isDeclarationSpecifier()) {
2073  // If there is an invalid declaration specifier right after the
2074  // function prototype, then we must be in a missing semicolon case
2075  // where this isn't actually a body. Just fall through into the code
2076  // that handles it as a prototype, and let the top-level code handle
2077  // the erroneous declspec where it would otherwise expect a comma or
2078  // semicolon.
2079  } else {
2080  Diag(Tok, diag::err_expected_fn_body);
2081  SkipUntil(tok::semi);
2082  return nullptr;
2083  }
2084  } else {
2085  if (Tok.is(tok::l_brace)) {
2086  Diag(Tok, diag::err_function_definition_not_allowed);
2088  return nullptr;
2089  }
2090  }
2091  }
2092 
2093  if (ParseAsmAttributesAfterDeclarator(D))
2094  return nullptr;
2095 
2096  // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2097  // must parse and analyze the for-range-initializer before the declaration is
2098  // analyzed.
2099  //
2100  // Handle the Objective-C for-in loop variable similarly, although we
2101  // don't need to parse the container in advance.
2102  if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2103  bool IsForRangeLoop = false;
2104  if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2105  IsForRangeLoop = true;
2106  if (getLangOpts().OpenMP)
2107  Actions.startOpenMPCXXRangeFor();
2108  if (Tok.is(tok::l_brace))
2109  FRI->RangeExpr = ParseBraceInitializer();
2110  else
2111  FRI->RangeExpr = ParseExpression();
2112  }
2113 
2114  Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2115  if (IsForRangeLoop) {
2116  Actions.ActOnCXXForRangeDecl(ThisDecl);
2117  } else {
2118  // Obj-C for loop
2119  if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2120  VD->setObjCForDecl(true);
2121  }
2122  Actions.FinalizeDeclaration(ThisDecl);
2123  D.complete(ThisDecl);
2124  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2125  }
2126 
2127  SmallVector<Decl *, 8> DeclsInGroup;
2128  Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2129  D, ParsedTemplateInfo(), FRI);
2130  if (LateParsedAttrs.size() > 0)
2131  ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2132  D.complete(FirstDecl);
2133  if (FirstDecl)
2134  DeclsInGroup.push_back(FirstDecl);
2135 
2136  bool ExpectSemi = Context != DeclaratorContext::ForContext;
2137 
2138  // If we don't have a comma, it is either the end of the list (a ';') or an
2139  // error, bail out.
2140  SourceLocation CommaLoc;
2141  while (TryConsumeToken(tok::comma, CommaLoc)) {
2142  if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2143  // This comma was followed by a line-break and something which can't be
2144  // the start of a declarator. The comma was probably a typo for a
2145  // semicolon.
2146  Diag(CommaLoc, diag::err_expected_semi_declaration)
2147  << FixItHint::CreateReplacement(CommaLoc, ";");
2148  ExpectSemi = false;
2149  break;
2150  }
2151 
2152  // Parse the next declarator.
2153  D.clear();
2154  D.setCommaLoc(CommaLoc);
2155 
2156  // Accept attributes in an init-declarator. In the first declarator in a
2157  // declaration, these would be part of the declspec. In subsequent
2158  // declarators, they become part of the declarator itself, so that they
2159  // don't apply to declarators after *this* one. Examples:
2160  // short __attribute__((common)) var; -> declspec
2161  // short var __attribute__((common)); -> declarator
2162  // short x, __attribute__((common)) var; -> declarator
2163  MaybeParseGNUAttributes(D);
2164 
2165  // MSVC parses but ignores qualifiers after the comma as an extension.
2166  if (getLangOpts().MicrosoftExt)
2167  DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2168 
2169  ParseDeclarator(D);
2170  if (!D.isInvalidType()) {
2171  // C++2a [dcl.decl]p1
2172  // init-declarator:
2173  // declarator initializer[opt]
2174  // declarator requires-clause
2175  if (Tok.is(tok::kw_requires))
2176  ParseTrailingRequiresClause(D);
2177  Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2178  D.complete(ThisDecl);
2179  if (ThisDecl)
2180  DeclsInGroup.push_back(ThisDecl);
2181  }
2182  }
2183 
2184  if (DeclEnd)
2185  *DeclEnd = Tok.getLocation();
2186 
2187  if (ExpectSemi &&
2188  ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
2189  ? diag::err_invalid_token_after_toplevel_declarator
2190  : diag::err_expected_semi_declaration)) {
2191  // Okay, there was no semicolon and one was expected. If we see a
2192  // declaration specifier, just assume it was missing and continue parsing.
2193  // Otherwise things are very confused and we skip to recover.
2194  if (!isDeclarationSpecifier()) {
2195  SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2196  TryConsumeToken(tok::semi);
2197  }
2198  }
2199 
2200  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2201 }
2202 
2203 /// Parse an optional simple-asm-expr and attributes, and attach them to a
2204 /// declarator. Returns true on an error.
2205 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2206  // If a simple-asm-expr is present, parse it.
2207  if (Tok.is(tok::kw_asm)) {
2208  SourceLocation Loc;
2209  ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2210  if (AsmLabel.isInvalid()) {
2211  SkipUntil(tok::semi, StopBeforeMatch);
2212  return true;
2213  }
2214 
2215  D.setAsmLabel(AsmLabel.get());
2216  D.SetRangeEnd(Loc);
2217  }
2218 
2219  MaybeParseGNUAttributes(D);
2220  return false;
2221 }
2222 
2223 /// Parse 'declaration' after parsing 'declaration-specifiers
2224 /// declarator'. This method parses the remainder of the declaration
2225 /// (including any attributes or initializer, among other things) and
2226 /// finalizes the declaration.
2227 ///
2228 /// init-declarator: [C99 6.7]
2229 /// declarator
2230 /// declarator '=' initializer
2231 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2232 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2233 /// [C++] declarator initializer[opt]
2234 ///
2235 /// [C++] initializer:
2236 /// [C++] '=' initializer-clause
2237 /// [C++] '(' expression-list ')'
2238 /// [C++0x] '=' 'default' [TODO]
2239 /// [C++0x] '=' 'delete'
2240 /// [C++0x] braced-init-list
2241 ///
2242 /// According to the standard grammar, =default and =delete are function
2243 /// definitions, but that definitely doesn't fit with the parser here.
2244 ///
2245 Decl *Parser::ParseDeclarationAfterDeclarator(
2246  Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2247  if (ParseAsmAttributesAfterDeclarator(D))
2248  return nullptr;
2249 
2250  return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2251 }
2252 
2253 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2254  Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2255  // RAII type used to track whether we're inside an initializer.
2256  struct InitializerScopeRAII {
2257  Parser &P;
2258  Declarator &D;
2259  Decl *ThisDecl;
2260 
2261  InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2262  : P(P), D(D), ThisDecl(ThisDecl) {
2263  if (ThisDecl && P.getLangOpts().CPlusPlus) {
2264  Scope *S = nullptr;
2265  if (D.getCXXScopeSpec().isSet()) {
2266  P.EnterScope(0);
2267  S = P.getCurScope();
2268  }
2269  P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2270  }
2271  }
2272  ~InitializerScopeRAII() { pop(); }
2273  void pop() {
2274  if (ThisDecl && P.getLangOpts().CPlusPlus) {
2275  Scope *S = nullptr;
2276  if (D.getCXXScopeSpec().isSet())
2277  S = P.getCurScope();
2278  P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2279  if (S)
2280  P.ExitScope();
2281  }
2282  ThisDecl = nullptr;
2283  }
2284  };
2285 
2286  // Inform the current actions module that we just parsed this declarator.
2287  Decl *ThisDecl = nullptr;
2288  switch (TemplateInfo.Kind) {
2289  case ParsedTemplateInfo::NonTemplate:
2290  ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2291  break;
2292 
2293  case ParsedTemplateInfo::Template:
2294  case ParsedTemplateInfo::ExplicitSpecialization: {
2295  ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2296  *TemplateInfo.TemplateParams,
2297  D);
2298  if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
2299  // Re-direct this decl to refer to the templated decl so that we can
2300  // initialize it.
2301  ThisDecl = VT->getTemplatedDecl();
2302  break;
2303  }
2304  case ParsedTemplateInfo::ExplicitInstantiation: {
2305  if (Tok.is(tok::semi)) {
2306  DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2307  getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2308  if (ThisRes.isInvalid()) {
2309  SkipUntil(tok::semi, StopBeforeMatch);
2310  return nullptr;
2311  }
2312  ThisDecl = ThisRes.get();
2313  } else {
2314  // FIXME: This check should be for a variable template instantiation only.
2315 
2316  // Check that this is a valid instantiation
2318  // If the declarator-id is not a template-id, issue a diagnostic and
2319  // recover by ignoring the 'template' keyword.
2320  Diag(Tok, diag::err_template_defn_explicit_instantiation)
2321  << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2322  ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2323  } else {
2324  SourceLocation LAngleLoc =
2325  PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2326  Diag(D.getIdentifierLoc(),
2327  diag::err_explicit_instantiation_with_definition)
2328  << SourceRange(TemplateInfo.TemplateLoc)
2329  << FixItHint::CreateInsertion(LAngleLoc, "<>");
2330 
2331  // Recover as if it were an explicit specialization.
2332  TemplateParameterLists FakedParamLists;
2333  FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2334  0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
2335  LAngleLoc, nullptr));
2336 
2337  ThisDecl =
2338  Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2339  }
2340  }
2341  break;
2342  }
2343  }
2344 
2345  // Parse declarator '=' initializer.
2346  // If a '==' or '+=' is found, suggest a fixit to '='.
2347  if (isTokenEqualOrEqualTypo()) {
2348  SourceLocation EqualLoc = ConsumeToken();
2349 
2350  if (Tok.is(tok::kw_delete)) {
2351  if (D.isFunctionDeclarator())
2352  Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2353  << 1 /* delete */;
2354  else
2355  Diag(ConsumeToken(), diag::err_deleted_non_function);
2356  } else if (Tok.is(tok::kw_default)) {
2357  if (D.isFunctionDeclarator())
2358  Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2359  << 0 /* default */;
2360  else
2361  Diag(ConsumeToken(), diag::err_default_special_members)
2362  << getLangOpts().CPlusPlus2a;
2363  } else {
2364  InitializerScopeRAII InitScope(*this, D, ThisDecl);
2365 
2366  if (Tok.is(tok::code_completion)) {
2367  Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2368  Actions.FinalizeDeclaration(ThisDecl);
2369  cutOffParsing();
2370  return nullptr;
2371  }
2372 
2373  PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2374  ExprResult Init = ParseInitializer();
2375 
2376  // If this is the only decl in (possibly) range based for statement,
2377  // our best guess is that the user meant ':' instead of '='.
2378  if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2379  Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2380  << FixItHint::CreateReplacement(EqualLoc, ":");
2381  // We are trying to stop parser from looking for ';' in this for
2382  // statement, therefore preventing spurious errors to be issued.
2383  FRI->ColonLoc = EqualLoc;
2384  Init = ExprError();
2385  FRI->RangeExpr = Init;
2386  }
2387 
2388  InitScope.pop();
2389 
2390  if (Init.isInvalid()) {
2391  SmallVector<tok::TokenKind, 2> StopTokens;
2392  StopTokens.push_back(tok::comma);
2395  StopTokens.push_back(tok::r_paren);
2396  SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2397  Actions.ActOnInitializerError(ThisDecl);
2398  } else
2399  Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2400  /*DirectInit=*/false);
2401  }
2402  } else if (Tok.is(tok::l_paren)) {
2403  // Parse C++ direct initializer: '(' expression-list ')'
2404  BalancedDelimiterTracker T(*this, tok::l_paren);
2405  T.consumeOpen();
2406 
2407  ExprVector Exprs;
2408  CommaLocsTy CommaLocs;
2409 
2410  InitializerScopeRAII InitScope(*this, D, ThisDecl);
2411 
2412  auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2413  auto RunSignatureHelp = [&]() {
2414  QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2415  getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2416  ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2417  CalledSignatureHelp = true;
2418  return PreferredType;
2419  };
2420  auto SetPreferredType = [&] {
2421  PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2422  };
2423 
2424  llvm::function_ref<void()> ExpressionStarts;
2425  if (ThisVarDecl) {
2426  // ParseExpressionList can sometimes succeed even when ThisDecl is not
2427  // VarDecl. This is an error and it is reported in a call to
2428  // Actions.ActOnInitializerError(). However, we call
2429  // ProduceConstructorSignatureHelp only on VarDecls.
2430  ExpressionStarts = SetPreferredType;
2431  }
2432  if (ParseExpressionList(Exprs, CommaLocs, ExpressionStarts)) {
2433  if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2434  Actions.ProduceConstructorSignatureHelp(
2435  getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2436  ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2437  CalledSignatureHelp = true;
2438  }
2439  Actions.ActOnInitializerError(ThisDecl);
2440  SkipUntil(tok::r_paren, StopAtSemi);
2441  } else {
2442  // Match the ')'.
2443  T.consumeClose();
2444 
2445  assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2446  "Unexpected number of commas!");
2447 
2448  InitScope.pop();
2449 
2450  ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2451  T.getCloseLocation(),
2452  Exprs);
2453  Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2454  /*DirectInit=*/true);
2455  }
2456  } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2457  (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
2458  // Parse C++0x braced-init-list.
2459  Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2460 
2461  InitializerScopeRAII InitScope(*this, D, ThisDecl);
2462 
2463  ExprResult Init(ParseBraceInitializer());
2464 
2465  InitScope.pop();
2466 
2467  if (Init.isInvalid()) {
2468  Actions.ActOnInitializerError(ThisDecl);
2469  } else
2470  Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2471 
2472  } else {
2473  Actions.ActOnUninitializedDecl(ThisDecl);
2474  }
2475 
2476  Actions.FinalizeDeclaration(ThisDecl);
2477 
2478  return ThisDecl;
2479 }
2480 
2481 /// ParseSpecifierQualifierList
2482 /// specifier-qualifier-list:
2483 /// type-specifier specifier-qualifier-list[opt]
2484 /// type-qualifier specifier-qualifier-list[opt]
2485 /// [GNU] attributes specifier-qualifier-list[opt]
2486 ///
2487 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2488  DeclSpecContext DSC) {
2489  /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2490  /// parse declaration-specifiers and complain about extra stuff.
2491  /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2492  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2493 
2494  // Validate declspec for type-name.
2495  unsigned Specs = DS.getParsedSpecifiers();
2496  if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2497  Diag(Tok, diag::err_expected_type);
2498  DS.SetTypeSpecError();
2499  } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2500  Diag(Tok, diag::err_typename_requires_specqual);
2501  if (!DS.hasTypeSpecifier())
2502  DS.SetTypeSpecError();
2503  }
2504 
2505  // Issue diagnostic and remove storage class if present.
2506  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2507  if (DS.getStorageClassSpecLoc().isValid())
2508  Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2509  else
2511  diag::err_typename_invalid_storageclass);
2513  }
2514 
2515  // Issue diagnostic and remove function specifier if present.
2516  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2517  if (DS.isInlineSpecified())
2518  Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2519  if (DS.isVirtualSpecified())
2520  Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2521  if (DS.hasExplicitSpecifier())
2522  Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2523  DS.ClearFunctionSpecs();
2524  }
2525 
2526  // Issue diagnostic and remove constexpr specifier if present.
2527  if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2528  Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2529  << DS.getConstexprSpecifier();
2530  DS.ClearConstexprSpec();
2531  }
2532 }
2533 
2534 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2535 /// specified token is valid after the identifier in a declarator which
2536 /// immediately follows the declspec. For example, these things are valid:
2537 ///
2538 /// int x [ 4]; // direct-declarator
2539 /// int x ( int y); // direct-declarator
2540 /// int(int x ) // direct-declarator
2541 /// int x ; // simple-declaration
2542 /// int x = 17; // init-declarator-list
2543 /// int x , y; // init-declarator-list
2544 /// int x __asm__ ("foo"); // init-declarator-list
2545 /// int x : 4; // struct-declarator
2546 /// int x { 5}; // C++'0x unified initializers
2547 ///
2548 /// This is not, because 'x' does not immediately follow the declspec (though
2549 /// ')' happens to be valid anyway).
2550 /// int (x)
2551 ///
2553  return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2554  tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2555  tok::colon);
2556 }
2557 
2558 /// ParseImplicitInt - This method is called when we have an non-typename
2559 /// identifier in a declspec (which normally terminates the decl spec) when
2560 /// the declspec has no type specifier. In this case, the declspec is either
2561 /// malformed or is "implicit int" (in K&R and C89).
2562 ///
2563 /// This method handles diagnosing this prettily and returns false if the
2564 /// declspec is done being processed. If it recovers and thinks there may be
2565 /// other pieces of declspec after it, it returns true.
2566 ///
2567 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2568  const ParsedTemplateInfo &TemplateInfo,
2569  AccessSpecifier AS, DeclSpecContext DSC,
2570  ParsedAttributesWithRange &Attrs) {
2571  assert(Tok.is(tok::identifier) && "should have identifier");
2572 
2573  SourceLocation Loc = Tok.getLocation();
2574  // If we see an identifier that is not a type name, we normally would
2575  // parse it as the identifier being declared. However, when a typename
2576  // is typo'd or the definition is not included, this will incorrectly
2577  // parse the typename as the identifier name and fall over misparsing
2578  // later parts of the diagnostic.
2579  //
2580  // As such, we try to do some look-ahead in cases where this would
2581  // otherwise be an "implicit-int" case to see if this is invalid. For
2582  // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2583  // an identifier with implicit int, we'd get a parse error because the
2584  // next token is obviously invalid for a type. Parse these as a case
2585  // with an invalid type specifier.
2586  assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2587 
2588  // Since we know that this either implicit int (which is rare) or an
2589  // error, do lookahead to try to do better recovery. This never applies
2590  // within a type specifier. Outside of C++, we allow this even if the
2591  // language doesn't "officially" support implicit int -- we support
2592  // implicit int as an extension in C99 and C11.
2593  if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2595  // If this token is valid for implicit int, e.g. "static x = 4", then
2596  // we just avoid eating the identifier, so it will be parsed as the
2597  // identifier in the declarator.
2598  return false;
2599  }
2600 
2601  // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2602  // for incomplete declarations such as `pipe p`.
2603  if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
2604  return false;
2605 
2606  if (getLangOpts().CPlusPlus &&
2608  // Don't require a type specifier if we have the 'auto' storage class
2609  // specifier in C++98 -- we'll promote it to a type specifier.
2610  if (SS)
2611  AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2612  return false;
2613  }
2614 
2615  if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2616  getLangOpts().MSVCCompat) {
2617  // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2618  // Give Sema a chance to recover if we are in a template with dependent base
2619  // classes.
2620  if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2621  *Tok.getIdentifierInfo(), Tok.getLocation(),
2622  DSC == DeclSpecContext::DSC_template_type_arg)) {
2623  const char *PrevSpec;
2624  unsigned DiagID;
2625  DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2626  Actions.getASTContext().getPrintingPolicy());
2627  DS.SetRangeEnd(Tok.getLocation());
2628  ConsumeToken();
2629  return false;
2630  }
2631  }
2632 
2633  // Otherwise, if we don't consume this token, we are going to emit an
2634  // error anyway. Try to recover from various common problems. Check
2635  // to see if this was a reference to a tag name without a tag specified.
2636  // This is a common problem in C (saying 'foo' instead of 'struct foo').
2637  //
2638  // C++ doesn't need this, and isTagName doesn't take SS.
2639  if (SS == nullptr) {
2640  const char *TagName = nullptr, *FixitTagName = nullptr;
2641  tok::TokenKind TagKind = tok::unknown;
2642 
2643  switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2644  default: break;
2645  case DeclSpec::TST_enum:
2646  TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2647  case DeclSpec::TST_union:
2648  TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2649  case DeclSpec::TST_struct:
2650  TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2652  TagName="__interface"; FixitTagName = "__interface ";
2653  TagKind=tok::kw___interface;break;
2654  case DeclSpec::TST_class:
2655  TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2656  }
2657 
2658  if (TagName) {
2659  IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2660  LookupResult R(Actions, TokenName, SourceLocation(),
2662 
2663  Diag(Loc, diag::err_use_of_tag_name_without_tag)
2664  << TokenName << TagName << getLangOpts().CPlusPlus
2665  << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2666 
2667  if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2668  for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2669  I != IEnd; ++I)
2670  Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2671  << TokenName << TagName;
2672  }
2673 
2674  // Parse this as a tag as if the missing tag were present.
2675  if (TagKind == tok::kw_enum)
2676  ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2677  DeclSpecContext::DSC_normal);
2678  else
2679  ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2680  /*EnteringContext*/ false,
2681  DeclSpecContext::DSC_normal, Attrs);
2682  return true;
2683  }
2684  }
2685 
2686  // Determine whether this identifier could plausibly be the name of something
2687  // being declared (with a missing type).
2688  if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2689  DSC == DeclSpecContext::DSC_class)) {
2690  // Look ahead to the next token to try to figure out what this declaration
2691  // was supposed to be.
2692  switch (NextToken().getKind()) {
2693  case tok::l_paren: {
2694  // static x(4); // 'x' is not a type
2695  // x(int n); // 'x' is not a type
2696  // x (*p)[]; // 'x' is a type
2697  //
2698  // Since we're in an error case, we can afford to perform a tentative
2699  // parse to determine which case we're in.
2700  TentativeParsingAction PA(*this);
2701  ConsumeToken();
2702  TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2703  PA.Revert();
2704 
2705  if (TPR != TPResult::False) {
2706  // The identifier is followed by a parenthesized declarator.
2707  // It's supposed to be a type.
2708  break;
2709  }
2710 
2711  // If we're in a context where we could be declaring a constructor,
2712  // check whether this is a constructor declaration with a bogus name.
2713  if (DSC == DeclSpecContext::DSC_class ||
2714  (DSC == DeclSpecContext::DSC_top_level && SS)) {
2715  IdentifierInfo *II = Tok.getIdentifierInfo();
2716  if (Actions.isCurrentClassNameTypo(II, SS)) {
2717  Diag(Loc, diag::err_constructor_bad_name)
2718  << Tok.getIdentifierInfo() << II
2719  << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2720  Tok.setIdentifierInfo(II);
2721  }
2722  }
2723  // Fall through.
2724  LLVM_FALLTHROUGH;
2725  }
2726  case tok::comma:
2727  case tok::equal:
2728  case tok::kw_asm:
2729  case tok::l_brace:
2730  case tok::l_square:
2731  case tok::semi:
2732  // This looks like a variable or function declaration. The type is
2733  // probably missing. We're done parsing decl-specifiers.
2734  // But only if we are not in a function prototype scope.
2735  if (getCurScope()->isFunctionPrototypeScope())
2736  break;
2737  if (SS)
2738  AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2739  return false;
2740 
2741  default:
2742  // This is probably supposed to be a type. This includes cases like:
2743  // int f(itn);
2744  // struct S { unsinged : 4; };
2745  break;
2746  }
2747  }
2748 
2749  // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2750  // and attempt to recover.
2751  ParsedType T;
2752  IdentifierInfo *II = Tok.getIdentifierInfo();
2753  bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2754  Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2755  IsTemplateName);
2756  if (T) {
2757  // The action has suggested that the type T could be used. Set that as
2758  // the type in the declaration specifiers, consume the would-be type
2759  // name token, and we're done.
2760  const char *PrevSpec;
2761  unsigned DiagID;
2762  DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2763  Actions.getASTContext().getPrintingPolicy());
2764  DS.SetRangeEnd(Tok.getLocation());
2765  ConsumeToken();
2766  // There may be other declaration specifiers after this.
2767  return true;
2768  } else if (II != Tok.getIdentifierInfo()) {
2769  // If no type was suggested, the correction is to a keyword
2770  Tok.setKind(II->getTokenID());
2771  // There may be other declaration specifiers after this.
2772  return true;
2773  }
2774 
2775  // Otherwise, the action had no suggestion for us. Mark this as an error.
2776  DS.SetTypeSpecError();
2777  DS.SetRangeEnd(Tok.getLocation());
2778  ConsumeToken();
2779 
2780  // Eat any following template arguments.
2781  if (IsTemplateName) {
2782  SourceLocation LAngle, RAngle;
2783  TemplateArgList Args;
2784  ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2785  }
2786 
2787  // TODO: Could inject an invalid typedef decl in an enclosing scope to
2788  // avoid rippling error messages on subsequent uses of the same type,
2789  // could be useful if #include was forgotten.
2790  return true;
2791 }
2792 
2793 /// Determine the declaration specifier context from the declarator
2794 /// context.
2795 ///
2796 /// \param Context the declarator context, which is one of the
2797 /// DeclaratorContext enumerator values.
2798 Parser::DeclSpecContext
2799 Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2800  if (Context == DeclaratorContext::MemberContext)
2801  return DeclSpecContext::DSC_class;
2802  if (Context == DeclaratorContext::FileContext)
2803  return DeclSpecContext::DSC_top_level;
2805  return DeclSpecContext::DSC_template_param;
2806  if (Context == DeclaratorContext::TemplateArgContext ||
2808  return DeclSpecContext::DSC_template_type_arg;
2811  return DeclSpecContext::DSC_trailing;
2812  if (Context == DeclaratorContext::AliasDeclContext ||
2814  return DeclSpecContext::DSC_alias_declaration;
2815  return DeclSpecContext::DSC_normal;
2816 }
2817 
2818 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2819 ///
2820 /// FIXME: Simply returns an alignof() expression if the argument is a
2821 /// type. Ideally, the type should be propagated directly into Sema.
2822 ///
2823 /// [C11] type-id
2824 /// [C11] constant-expression
2825 /// [C++0x] type-id ...[opt]
2826 /// [C++0x] assignment-expression ...[opt]
2827 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2828  SourceLocation &EllipsisLoc) {
2829  ExprResult ER;
2830  if (isTypeIdInParens()) {
2831  SourceLocation TypeLoc = Tok.getLocation();
2832  ParsedType Ty = ParseTypeName().get();
2833  SourceRange TypeRange(Start, Tok.getLocation());
2834  ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2835  Ty.getAsOpaquePtr(), TypeRange);
2836  } else
2837  ER = ParseConstantExpression();
2838 
2839  if (getLangOpts().CPlusPlus11)
2840  TryConsumeToken(tok::ellipsis, EllipsisLoc);
2841 
2842  return ER;
2843 }
2844 
2845 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2846 /// attribute to Attrs.
2847 ///
2848 /// alignment-specifier:
2849 /// [C11] '_Alignas' '(' type-id ')'
2850 /// [C11] '_Alignas' '(' constant-expression ')'
2851 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2852 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2853 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2854  SourceLocation *EndLoc) {
2855  assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2856  "Not an alignment-specifier!");
2857 
2858  IdentifierInfo *KWName = Tok.getIdentifierInfo();
2859  SourceLocation KWLoc = ConsumeToken();
2860 
2861  BalancedDelimiterTracker T(*this, tok::l_paren);
2862  if (T.expectAndConsume())
2863  return;
2864 
2865  SourceLocation EllipsisLoc;
2866  ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2867  if (ArgExpr.isInvalid()) {
2868  T.skipToEnd();
2869  return;
2870  }
2871 
2872  T.consumeClose();
2873  if (EndLoc)
2874  *EndLoc = T.getCloseLocation();
2875 
2876  ArgsVector ArgExprs;
2877  ArgExprs.push_back(ArgExpr.get());
2878  Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2879  ParsedAttr::AS_Keyword, EllipsisLoc);
2880 }
2881 
2882 /// Determine whether we're looking at something that might be a declarator
2883 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2884 /// diagnose a missing semicolon after a prior tag definition in the decl
2885 /// specifier.
2886 ///
2887 /// \return \c true if an error occurred and this can't be any kind of
2888 /// declaration.
2889 bool
2890 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2891  DeclSpecContext DSContext,
2892  LateParsedAttrList *LateAttrs) {
2893  assert(DS.hasTagDefinition() && "shouldn't call this");
2894 
2895  bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2896  DSContext == DeclSpecContext::DSC_top_level);
2897 
2898  if (getLangOpts().CPlusPlus &&
2899  Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2900  tok::annot_template_id) &&
2901  TryAnnotateCXXScopeToken(EnteringContext)) {
2903  return true;
2904  }
2905 
2906  bool HasScope = Tok.is(tok::annot_cxxscope);
2907  // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2908  Token AfterScope = HasScope ? NextToken() : Tok;
2909 
2910  // Determine whether the following tokens could possibly be a
2911  // declarator.
2912  bool MightBeDeclarator = true;
2913  if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2914  // A declarator-id can't start with 'typename'.
2915  MightBeDeclarator = false;
2916  } else if (AfterScope.is(tok::annot_template_id)) {
2917  // If we have a type expressed as a template-id, this cannot be a
2918  // declarator-id (such a type cannot be redeclared in a simple-declaration).
2919  TemplateIdAnnotation *Annot =
2920  static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2921  if (Annot->Kind == TNK_Type_template)
2922  MightBeDeclarator = false;
2923  } else if (AfterScope.is(tok::identifier)) {
2924  const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2925 
2926  // These tokens cannot come after the declarator-id in a
2927  // simple-declaration, and are likely to come after a type-specifier.
2928  if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2929  tok::annot_cxxscope, tok::coloncolon)) {
2930  // Missing a semicolon.
2931  MightBeDeclarator = false;
2932  } else if (HasScope) {
2933  // If the declarator-id has a scope specifier, it must redeclare a
2934  // previously-declared entity. If that's a type (and this is not a
2935  // typedef), that's an error.
2936  CXXScopeSpec SS;
2937  Actions.RestoreNestedNameSpecifierAnnotation(
2938  Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2939  IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2940  Sema::NameClassification Classification = Actions.ClassifyName(
2941  getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2942  /*CCC=*/nullptr);
2943  switch (Classification.getKind()) {
2944  case Sema::NC_Error:
2946  return true;
2947 
2948  case Sema::NC_Keyword:
2949  llvm_unreachable("typo correction is not possible here");
2950 
2951  case Sema::NC_Type:
2952  case Sema::NC_TypeTemplate:
2955  // Not a previously-declared non-type entity.
2956  MightBeDeclarator = false;
2957  break;
2958 
2959  case Sema::NC_Unknown:
2960  case Sema::NC_NonType:
2963  case Sema::NC_VarTemplate:
2965  case Sema::NC_Concept:
2966  // Might be a redeclaration of a prior entity.
2967  break;
2968  }
2969  }
2970  }
2971 
2972  if (MightBeDeclarator)
2973  return false;
2974 
2975  const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2976  Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
2977  diag::err_expected_after)
2978  << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2979 
2980  // Try to recover from the typo, by dropping the tag definition and parsing
2981  // the problematic tokens as a type.
2982  //
2983  // FIXME: Split the DeclSpec into pieces for the standalone
2984  // declaration and pieces for the following declaration, instead
2985  // of assuming that all the other pieces attach to new declaration,
2986  // and call ParsedFreeStandingDeclSpec as appropriate.
2987  DS.ClearTypeSpecType();
2988  ParsedTemplateInfo NotATemplate;
2989  ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2990  return false;
2991 }
2992 
2993 // Choose the apprpriate diagnostic error for why fixed point types are
2994 // disabled, set the previous specifier, and mark as invalid.
2995 static void SetupFixedPointError(const LangOptions &LangOpts,
2996  const char *&PrevSpec, unsigned &DiagID,
2997  bool &isInvalid) {
2998  assert(!LangOpts.FixedPoint);
2999  DiagID = diag::err_fixed_point_not_enabled;
3000  PrevSpec = ""; // Not used by diagnostic
3001  isInvalid = true;
3002 }
3003 
3004 /// ParseDeclarationSpecifiers
3005 /// declaration-specifiers: [C99 6.7]
3006 /// storage-class-specifier declaration-specifiers[opt]
3007 /// type-specifier declaration-specifiers[opt]
3008 /// [C99] function-specifier declaration-specifiers[opt]
3009 /// [C11] alignment-specifier declaration-specifiers[opt]
3010 /// [GNU] attributes declaration-specifiers[opt]
3011 /// [Clang] '__module_private__' declaration-specifiers[opt]
3012 /// [ObjC1] '__kindof' declaration-specifiers[opt]
3013 ///
3014 /// storage-class-specifier: [C99 6.7.1]
3015 /// 'typedef'
3016 /// 'extern'
3017 /// 'static'
3018 /// 'auto'
3019 /// 'register'
3020 /// [C++] 'mutable'
3021 /// [C++11] 'thread_local'
3022 /// [C11] '_Thread_local'
3023 /// [GNU] '__thread'
3024 /// function-specifier: [C99 6.7.4]
3025 /// [C99] 'inline'
3026 /// [C++] 'virtual'
3027 /// [C++] 'explicit'
3028 /// [OpenCL] '__kernel'
3029 /// 'friend': [C++ dcl.friend]
3030 /// 'constexpr': [C++0x dcl.constexpr]
3031 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
3032  const ParsedTemplateInfo &TemplateInfo,
3033  AccessSpecifier AS,
3034  DeclSpecContext DSContext,
3035  LateParsedAttrList *LateAttrs) {
3036  if (DS.getSourceRange().isInvalid()) {
3037  // Start the range at the current token but make the end of the range
3038  // invalid. This will make the entire range invalid unless we successfully
3039  // consume a token.
3040  DS.SetRangeStart(Tok.getLocation());
3042  }
3043 
3044  bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3045  DSContext == DeclSpecContext::DSC_top_level);
3046  bool AttrsLastTime = false;
3047  ParsedAttributesWithRange attrs(AttrFactory);
3048  // We use Sema's policy to get bool macros right.
3049  PrintingPolicy Policy = Actions.getPrintingPolicy();
3050  while (1) {
3051  bool isInvalid = false;
3052  bool isStorageClass = false;
3053  const char *PrevSpec = nullptr;
3054  unsigned DiagID = 0;
3055 
3056  // This value needs to be set to the location of the last token if the last
3057  // token of the specifier is already consumed.
3058  SourceLocation ConsumedEnd;
3059 
3060  // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3061  // implementation for VS2013 uses _Atomic as an identifier for one of the
3062  // classes in <atomic>.
3063  //
3064  // A typedef declaration containing _Atomic<...> is among the places where
3065  // the class is used. If we are currently parsing such a declaration, treat
3066  // the token as an identifier.
3067  if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3069  !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3070  Tok.setKind(tok::identifier);
3071 
3072  SourceLocation Loc = Tok.getLocation();
3073 
3074  switch (Tok.getKind()) {
3075  default:
3076  DoneWithDeclSpec:
3077  if (!AttrsLastTime)
3078  ProhibitAttributes(attrs);
3079  else {
3080  // Reject C++11 attributes that appertain to decl specifiers as
3081  // we don't support any C++11 attributes that appertain to decl
3082  // specifiers. This also conforms to what g++ 4.8 is doing.
3083  ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
3084 
3085  DS.takeAttributesFrom(attrs);
3086  }
3087 
3088  // If this is not a declaration specifier token, we're done reading decl
3089  // specifiers. First verify that DeclSpec's are consistent.
3090  DS.Finish(Actions, Policy);
3091  return;
3092 
3093  case tok::l_square:
3094  case tok::kw_alignas:
3095  if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
3096  goto DoneWithDeclSpec;
3097 
3098  ProhibitAttributes(attrs);
3099  // FIXME: It would be good to recover by accepting the attributes,
3100  // but attempting to do that now would cause serious
3101  // madness in terms of diagnostics.
3102  attrs.clear();
3103  attrs.Range = SourceRange();
3104 
3105  ParseCXX11Attributes(attrs);
3106  AttrsLastTime = true;
3107  continue;
3108 
3109  case tok::code_completion: {
3111  if (DS.hasTypeSpecifier()) {
3112  bool AllowNonIdentifiers
3117  Scope::AtCatchScope)) == 0;
3118  bool AllowNestedNameSpecifiers
3119  = DSContext == DeclSpecContext::DSC_top_level ||
3120  (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3121 
3122  Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3123  AllowNonIdentifiers,
3124  AllowNestedNameSpecifiers);
3125  return cutOffParsing();
3126  }
3127 
3128  if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3130  else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3131  CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3133  else if (DSContext == DeclSpecContext::DSC_class)
3134  CCC = Sema::PCC_Class;
3135  else if (CurParsedObjCImpl)
3137 
3138  Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3139  return cutOffParsing();
3140  }
3141 
3142  case tok::coloncolon: // ::foo::bar
3143  // C++ scope specifier. Annotate and loop, or bail out on error.
3144  if (TryAnnotateCXXScopeToken(EnteringContext)) {
3145  if (!DS.hasTypeSpecifier())
3146  DS.SetTypeSpecError();
3147  goto DoneWithDeclSpec;
3148  }
3149  if (Tok.is(tok::coloncolon)) // ::new or ::delete
3150  goto DoneWithDeclSpec;
3151  continue;
3152 
3153  case tok::annot_cxxscope: {
3154  if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3155  goto DoneWithDeclSpec;
3156 
3157  CXXScopeSpec SS;
3158  Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3159  Tok.getAnnotationRange(),
3160  SS);
3161 
3162  // We are looking for a qualified typename.
3163  Token Next = NextToken();
3164  if (Next.is(tok::annot_template_id) &&
3165  static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3166  ->Kind == TNK_Type_template) {
3167  // We have a qualified template-id, e.g., N::A<int>
3168 
3169  // If this would be a valid constructor declaration with template
3170  // arguments, we will reject the attempt to form an invalid type-id
3171  // referring to the injected-class-name when we annotate the token,
3172  // per C++ [class.qual]p2.
3173  //
3174  // To improve diagnostics for this case, parse the declaration as a
3175  // constructor (and reject the extra template arguments later).
3176  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
3177  if ((DSContext == DeclSpecContext::DSC_top_level ||
3178  DSContext == DeclSpecContext::DSC_class) &&
3179  TemplateId->Name &&
3180  Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3181  isConstructorDeclarator(/*Unqualified=*/false)) {
3182  // The user meant this to be an out-of-line constructor
3183  // definition, but template arguments are not allowed
3184  // there. Just allow this as a constructor; we'll
3185  // complain about it later.
3186  goto DoneWithDeclSpec;
3187  }
3188 
3189  DS.getTypeSpecScope() = SS;
3190  ConsumeAnnotationToken(); // The C++ scope.
3191  assert(Tok.is(tok::annot_template_id) &&
3192  "ParseOptionalCXXScopeSpecifier not working");
3193  AnnotateTemplateIdTokenAsType(SS);
3194  continue;
3195  }
3196 
3197  if (Next.is(tok::annot_template_id) &&
3198  static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3199  ->Kind == TNK_Concept_template &&
3200  GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype)) {
3201  DS.getTypeSpecScope() = SS;
3202  // This is a qualified placeholder-specifier, e.g., ::C<int> auto ...
3203  // Consume the scope annotation and continue to consume the template-id
3204  // as a placeholder-specifier.
3205  ConsumeAnnotationToken();
3206  continue;
3207  }
3208 
3209  if (Next.is(tok::annot_typename)) {
3210  DS.getTypeSpecScope() = SS;
3211  ConsumeAnnotationToken(); // The C++ scope.
3212  if (Tok.getAnnotationValue()) {
3213  ParsedType T = getTypeAnnotation(Tok);
3214  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3215  Tok.getAnnotationEndLoc(),
3216  PrevSpec, DiagID, T, Policy);
3217  if (isInvalid)
3218  break;
3219  }
3220  else
3221  DS.SetTypeSpecError();
3222  DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3223  ConsumeAnnotationToken(); // The typename
3224  }
3225 
3226  if (Next.isNot(tok::identifier))
3227  goto DoneWithDeclSpec;
3228 
3229  // Check whether this is a constructor declaration. If we're in a
3230  // context where the identifier could be a class name, and it has the
3231  // shape of a constructor declaration, process it as one.
3232  if ((DSContext == DeclSpecContext::DSC_top_level ||
3233  DSContext == DeclSpecContext::DSC_class) &&
3234  Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3235  &SS) &&
3236  isConstructorDeclarator(/*Unqualified*/ false))
3237  goto DoneWithDeclSpec;
3238 
3239  ParsedType TypeRep =
3240  Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3241  getCurScope(), &SS, false, false, nullptr,
3242  /*IsCtorOrDtorName=*/false,
3243  /*WantNontrivialTypeSourceInfo=*/true,
3244  isClassTemplateDeductionContext(DSContext));
3245 
3246  // If the referenced identifier is not a type, then this declspec is
3247  // erroneous: We already checked about that it has no type specifier, and
3248  // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3249  // typename.
3250  if (!TypeRep) {
3251  if (TryAnnotateTypeConstraint())
3252  goto DoneWithDeclSpec;
3253  if (isTypeConstraintAnnotation())
3254  continue;
3255  // Eat the scope spec so the identifier is current.
3256  ConsumeAnnotationToken();
3257  ParsedAttributesWithRange Attrs(AttrFactory);
3258  if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3259  if (!Attrs.empty()) {
3260  AttrsLastTime = true;
3261  attrs.takeAllFrom(Attrs);
3262  }
3263  continue;
3264  }
3265  goto DoneWithDeclSpec;
3266  }
3267 
3268  DS.getTypeSpecScope() = SS;
3269  ConsumeAnnotationToken(); // The C++ scope.
3270 
3271  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3272  DiagID, TypeRep, Policy);
3273  if (isInvalid)
3274  break;
3275 
3276  DS.SetRangeEnd(Tok.getLocation());
3277  ConsumeToken(); // The typename.
3278 
3279  continue;
3280  }
3281 
3282  case tok::annot_typename: {
3283  // If we've previously seen a tag definition, we were almost surely
3284  // missing a semicolon after it.
3285  if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3286  goto DoneWithDeclSpec;
3287 
3288  if (Tok.getAnnotationValue()) {
3289  ParsedType T = getTypeAnnotation(Tok);
3290  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3291  DiagID, T, Policy);
3292  } else
3293  DS.SetTypeSpecError();
3294 
3295  if (isInvalid)
3296  break;
3297 
3298  DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3299  ConsumeAnnotationToken(); // The typename
3300 
3301  continue;
3302  }
3303 
3304  case tok::kw___is_signed:
3305  // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3306  // typically treats it as a trait. If we see __is_signed as it appears
3307  // in libstdc++, e.g.,
3308  //
3309  // static const bool __is_signed;
3310  //
3311  // then treat __is_signed as an identifier rather than as a keyword.
3312  if (DS.getTypeSpecType() == TST_bool &&
3315  TryKeywordIdentFallback(true);
3316 
3317  // We're done with the declaration-specifiers.
3318  goto DoneWithDeclSpec;
3319 
3320  // typedef-name
3321  case tok::kw___super:
3322  case tok::kw_decltype:
3323  case tok::identifier: {
3324  // This identifier can only be a typedef name if we haven't already seen
3325  // a type-specifier. Without this check we misparse:
3326  // typedef int X; struct Y { short X; }; as 'short int'.
3327  if (DS.hasTypeSpecifier())
3328  goto DoneWithDeclSpec;
3329 
3330  // If the token is an identifier named "__declspec" and Microsoft
3331  // extensions are not enabled, it is likely that there will be cascading
3332  // parse errors if this really is a __declspec attribute. Attempt to
3333  // recognize that scenario and recover gracefully.
3334  if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3335  Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3336  Diag(Loc, diag::err_ms_attributes_not_enabled);
3337 
3338  // The next token should be an open paren. If it is, eat the entire
3339  // attribute declaration and continue.
3340  if (NextToken().is(tok::l_paren)) {
3341  // Consume the __declspec identifier.
3342  ConsumeToken();
3343 
3344  // Eat the parens and everything between them.
3345  BalancedDelimiterTracker T(*this, tok::l_paren);
3346  if (T.consumeOpen()) {
3347  assert(false && "Not a left paren?");
3348  return;
3349  }
3350  T.skipToEnd();
3351  continue;
3352  }
3353  }
3354 
3355  // In C++, check to see if this is a scope specifier like foo::bar::, if
3356  // so handle it as such. This is important for ctor parsing.
3357  if (getLangOpts().CPlusPlus) {
3358  if (TryAnnotateCXXScopeToken(EnteringContext)) {
3359  DS.SetTypeSpecError();
3360  goto DoneWithDeclSpec;
3361  }
3362  if (!Tok.is(tok::identifier))
3363  continue;
3364  }
3365 
3366  // Check for need to substitute AltiVec keyword tokens.
3367  if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3368  break;
3369 
3370  // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3371  // allow the use of a typedef name as a type specifier.
3372  if (DS.isTypeAltiVecVector())
3373  goto DoneWithDeclSpec;
3374 
3375  if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3376  isObjCInstancetype()) {
3377  ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3378  assert(TypeRep);
3379  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3380  DiagID, TypeRep, Policy);
3381  if (isInvalid)
3382  break;
3383 
3384  DS.SetRangeEnd(Loc);
3385  ConsumeToken();
3386  continue;
3387  }
3388 
3389  // If we're in a context where the identifier could be a class name,
3390  // check whether this is a constructor declaration.
3391  if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3392  Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3393  isConstructorDeclarator(/*Unqualified*/true))
3394  goto DoneWithDeclSpec;
3395 
3396  ParsedType TypeRep = Actions.getTypeName(
3397  *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3398  false, false, nullptr, false, false,
3399  isClassTemplateDeductionContext(DSContext));
3400 
3401  // If this is not a typedef name, don't parse it as part of the declspec,
3402  // it must be an implicit int or an error.
3403  if (!TypeRep) {
3404  if (TryAnnotateTypeConstraint())
3405  goto DoneWithDeclSpec;
3406  if (isTypeConstraintAnnotation())
3407  continue;
3408  ParsedAttributesWithRange Attrs(AttrFactory);
3409  if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3410  if (!Attrs.empty()) {
3411  AttrsLastTime = true;
3412  attrs.takeAllFrom(Attrs);
3413  }
3414  continue;
3415  }
3416  goto DoneWithDeclSpec;
3417  }
3418 
3419  // Likewise, if this is a context where the identifier could be a template
3420  // name, check whether this is a deduction guide declaration.
3421  if (getLangOpts().CPlusPlus17 &&
3422  (DSContext == DeclSpecContext::DSC_class ||
3423  DSContext == DeclSpecContext::DSC_top_level) &&
3424  Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3425  Tok.getLocation()) &&
3426  isConstructorDeclarator(/*Unqualified*/ true,
3427  /*DeductionGuide*/ true))
3428  goto DoneWithDeclSpec;
3429 
3430  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3431  DiagID, TypeRep, Policy);
3432  if (isInvalid)
3433  break;
3434 
3435  DS.SetRangeEnd(Tok.getLocation());
3436  ConsumeToken(); // The identifier
3437 
3438  // Objective-C supports type arguments and protocol references
3439  // following an Objective-C object or object pointer
3440  // type. Handle either one of them.
3441  if (Tok.is(tok::less) && getLangOpts().ObjC) {
3442  SourceLocation NewEndLoc;
3443  TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3444  Loc, TypeRep, /*consumeLastToken=*/true,
3445  NewEndLoc);
3446  if (NewTypeRep.isUsable()) {
3447  DS.UpdateTypeRep(NewTypeRep.get());
3448  DS.SetRangeEnd(NewEndLoc);
3449  }
3450  }
3451 
3452  // Need to support trailing type qualifiers (e.g. "id<p> const").
3453  // If a type specifier follows, it will be diagnosed elsewhere.
3454  continue;
3455  }
3456 
3457  // type-name or placeholder-specifier
3458  case tok::annot_template_id: {
3459  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3460  if (TemplateId->Kind == TNK_Concept_template) {
3461  if (NextToken().is(tok::identifier)) {
3462  Diag(Loc, diag::err_placeholder_expected_auto_or_decltype_auto)
3463  << FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
3464  // Attempt to continue as if 'auto' was placed here.
3465  isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3466  TemplateId, Policy);
3467  break;
3468  }
3469  if (!NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
3470  goto DoneWithDeclSpec;
3471  ConsumeAnnotationToken();
3472  SourceLocation AutoLoc = Tok.getLocation();
3473  if (TryConsumeToken(tok::kw_decltype)) {
3474  BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3475  if (Tracker.consumeOpen()) {
3476  // Something like `void foo(Iterator decltype i)`
3477  Diag(Tok, diag::err_expected) << tok::l_paren;
3478  } else {
3479  if (!TryConsumeToken(tok::kw_auto)) {
3480  // Something like `void foo(Iterator decltype(int) i)`
3481  Tracker.skipToEnd();
3482  Diag(Tok, diag::err_placeholder_expected_auto_or_decltype_auto)
3484  Tok.getLocation()),
3485  "auto");
3486  } else {
3487  Tracker.consumeClose();
3488  }
3489  }
3490  ConsumedEnd = Tok.getLocation();
3491  // Even if something went wrong above, continue as if we've seen
3492  // `decltype(auto)`.
3493  isInvalid = DS.SetTypeSpecType(TST_decltype_auto, Loc, PrevSpec,
3494  DiagID, TemplateId, Policy);
3495  } else {
3496  isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3497  TemplateId, Policy);
3498  }
3499  break;
3500  }
3501 
3502  if (TemplateId->Kind != TNK_Type_template &&
3503  TemplateId->Kind != TNK_Undeclared_template) {
3504  // This template-id does not refer to a type name, so we're
3505  // done with the type-specifiers.
3506  goto DoneWithDeclSpec;
3507  }
3508 
3509  // If we're in a context where the template-id could be a
3510  // constructor name or specialization, check whether this is a
3511  // constructor declaration.
3512  if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3513  Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3514  isConstructorDeclarator(/*Unqualified=*/true))
3515  goto DoneWithDeclSpec;
3516 
3517  // Turn the template-id annotation token into a type annotation
3518  // token, then try again to parse it as a type-specifier.
3519  CXXScopeSpec SS;
3520  AnnotateTemplateIdTokenAsType(SS);
3521  continue;
3522  }
3523 
3524  // GNU attributes support.
3525  case tok::kw___attribute:
3526  ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3527  continue;
3528 
3529  // Microsoft declspec support.
3530  case tok::kw___declspec:
3531  ParseMicrosoftDeclSpecs(DS.getAttributes());
3532  continue;
3533 
3534  // Microsoft single token adornments.
3535  case tok::kw___forceinline: {
3536  isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3537  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3538  SourceLocation AttrNameLoc = Tok.getLocation();
3539  DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3540  nullptr, 0, ParsedAttr::AS_Keyword);
3541  break;
3542  }
3543 
3544  case tok::kw___unaligned:
3545  isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3546  getLangOpts());
3547  break;
3548 
3549  case tok::kw___sptr:
3550  case tok::kw___uptr:
3551  case tok::kw___ptr64:
3552  case tok::kw___ptr32:
3553  case tok::kw___w64:
3554  case tok::kw___cdecl:
3555  case tok::kw___stdcall:
3556  case tok::kw___fastcall:
3557  case tok::kw___thiscall:
3558  case tok::kw___regcall:
3559  case tok::kw___vectorcall:
3560  ParseMicrosoftTypeAttributes(DS.getAttributes());
3561  continue;
3562 
3563  // Borland single token adornments.
3564  case tok::kw___pascal:
3565  ParseBorlandTypeAttributes(DS.getAttributes());
3566  continue;
3567 
3568  // OpenCL single token adornments.
3569  case tok::kw___kernel:
3570  ParseOpenCLKernelAttributes(DS.getAttributes());
3571  continue;
3572 
3573  // Nullability type specifiers.
3574  case tok::kw__Nonnull:
3575  case tok::kw__Nullable:
3576  case tok::kw__Null_unspecified:
3577  ParseNullabilityTypeSpecifiers(DS.getAttributes());
3578  continue;
3579 
3580  // Objective-C 'kindof' types.
3581  case tok::kw___kindof:
3582  DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3583  nullptr, 0, ParsedAttr::AS_Keyword);
3584  (void)ConsumeToken();
3585  continue;
3586 
3587  // storage-class-specifier
3588  case tok::kw_typedef:
3589  isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3590  PrevSpec, DiagID, Policy);
3591  isStorageClass = true;
3592  break;
3593  case tok::kw_extern:
3595  Diag(Tok, diag::ext_thread_before) << "extern";
3596  isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3597  PrevSpec, DiagID, Policy);
3598  isStorageClass = true;
3599  break;
3600  case tok::kw___private_extern__:
3601  isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3602  Loc, PrevSpec, DiagID, Policy);
3603  isStorageClass = true;
3604  break;
3605  case tok::kw_static:
3607  Diag(Tok, diag::ext_thread_before) << "static";
3608  isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3609  PrevSpec, DiagID, Policy);
3610  isStorageClass = true;
3611  break;
3612  case tok::kw_auto:
3613  if (getLangOpts().CPlusPlus11) {
3614  if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3615  isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3616  PrevSpec, DiagID, Policy);
3617  if (!isInvalid)
3618  Diag(Tok, diag::ext_auto_storage_class)
3620  } else
3621  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3622  DiagID, Policy);
3623  } else
3624  isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3625  PrevSpec, DiagID, Policy);
3626  isStorageClass = true;
3627  break;
3628  case tok::kw___auto_type:
3629  Diag(Tok, diag::ext_auto_type);
3630  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3631  DiagID, Policy);
3632  break;
3633  case tok::kw_register:
3634  isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3635  PrevSpec, DiagID, Policy);
3636  isStorageClass = true;
3637  break;
3638  case tok::kw_mutable:
3639  isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3640  PrevSpec, DiagID, Policy);
3641  isStorageClass = true;
3642  break;
3643  case tok::kw___thread:
3645  PrevSpec, DiagID);
3646  isStorageClass = true;
3647  break;
3648  case tok::kw_thread_local:
3650  PrevSpec, DiagID);
3651  isStorageClass = true;
3652  break;
3653  case tok::kw__Thread_local:
3654  if (!getLangOpts().C11)
3655  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3657  Loc, PrevSpec, DiagID);
3658  isStorageClass = true;
3659  break;
3660 
3661  // function-specifier
3662  case tok::kw_inline:
3663  isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3664  break;
3665  case tok::kw_virtual:
3666  // C++ for OpenCL does not allow virtual function qualifier, to avoid
3667  // function pointers restricted in OpenCL v2.0 s6.9.a.
3668  if (getLangOpts().OpenCLCPlusPlus) {
3669  DiagID = diag::err_openclcxx_virtual_function;
3670  PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3671  isInvalid = true;
3672  }
3673  else {
3674  isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3675  }
3676  break;
3677  case tok::kw_explicit: {
3678  SourceLocation ExplicitLoc = Loc;
3679  SourceLocation CloseParenLoc;
3680  ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
3681  ConsumedEnd = ExplicitLoc;
3682  ConsumeToken(); // kw_explicit
3683  if (Tok.is(tok::l_paren)) {
3684  if (getLangOpts().CPlusPlus2a || isExplicitBool() == TPResult::True) {
3685  Diag(Tok.getLocation(), getLangOpts().CPlusPlus2a
3686  ? diag::warn_cxx17_compat_explicit_bool
3687  : diag::ext_explicit_bool);
3688 
3689  ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
3690  BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3691  Tracker.consumeOpen();
3692  ExplicitExpr = ParseConstantExpression();
3693  ConsumedEnd = Tok.getLocation();
3694  if (ExplicitExpr.isUsable()) {
3695  CloseParenLoc = Tok.getLocation();
3696  Tracker.consumeClose();
3697  ExplicitSpec =
3698  Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
3699  } else
3700  Tracker.skipToEnd();
3701  } else {
3702  Diag(Tok.getLocation(), diag::warn_cxx2a_compat_explicit_bool);
3703  }
3704  }
3705  isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
3706  ExplicitSpec, CloseParenLoc);
3707  break;
3708  }
3709  case tok::kw__Noreturn:
3710  if (!getLangOpts().C11)
3711  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3712  isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3713  break;
3714 
3715  // alignment-specifier
3716  case tok::kw__Alignas:
3717  if (!getLangOpts().C11)
3718  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3719  ParseAlignmentSpecifier(DS.getAttributes());
3720  continue;
3721 
3722  // friend
3723  case tok::kw_friend:
3724  if (DSContext == DeclSpecContext::DSC_class)
3725  isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3726  else {
3727  PrevSpec = ""; // not actually used by the diagnostic
3728  DiagID = diag::err_friend_invalid_in_context;
3729  isInvalid = true;
3730  }
3731  break;
3732 
3733  // Modules
3734  case tok::kw___module_private__:
3735  isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3736  break;
3737 
3738  // constexpr, consteval, constinit specifiers
3739  case tok::kw_constexpr:
3740  isInvalid = DS.SetConstexprSpec(CSK_constexpr, Loc, PrevSpec, DiagID);
3741  break;
3742  case tok::kw_consteval:
3743  isInvalid = DS.SetConstexprSpec(CSK_consteval, Loc, PrevSpec, DiagID);
3744  break;
3745  case tok::kw_constinit:
3746  isInvalid = DS.SetConstexprSpec(CSK_constinit, Loc, PrevSpec, DiagID);
3747  break;
3748 
3749  // type-specifier
3750  case tok::kw_short:
3751  isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3752  DiagID, Policy);
3753  break;
3754  case tok::kw_long:
3756  isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3757  DiagID, Policy);
3758  else
3759  isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3760  DiagID, Policy);
3761  break;
3762  case tok::kw___int64:
3763  isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3764  DiagID, Policy);
3765  break;
3766  case tok::kw_signed:
3767  isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3768  DiagID);
3769  break;
3770  case tok::kw_unsigned:
3771  isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3772  DiagID);
3773  break;
3774  case tok::kw__Complex:
3775  if (!getLangOpts().C99)
3776  Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3777  isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3778  DiagID);
3779  break;
3780  case tok::kw__Imaginary:
3781  if (!getLangOpts().C99)
3782  Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3783  isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3784  DiagID);
3785  break;
3786  case tok::kw_void:
3787  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3788  DiagID, Policy);
3789  break;
3790  case tok::kw_char:
3791  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3792  DiagID, Policy);
3793  break;
3794  case tok::kw_int:
3795  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3796  DiagID, Policy);
3797  break;
3798  case tok::kw___int128:
3799  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3800  DiagID, Policy);
3801  break;
3802  case tok::kw_half:
3803  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3804  DiagID, Policy);
3805  break;
3806  case tok::kw_float:
3807  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3808  DiagID, Policy);
3809  break;
3810  case tok::kw_double:
3811  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3812  DiagID, Policy);
3813  break;
3814  case tok::kw__Float16:
3815  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3816  DiagID, Policy);
3817  break;
3818  case tok::kw__Accum:
3819  if (!getLangOpts().FixedPoint) {
3820  SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3821  } else {
3822  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3823  DiagID, Policy);
3824  }
3825  break;
3826  case tok::kw__Fract:
3827  if (!getLangOpts().FixedPoint) {
3828  SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3829  } else {
3830  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3831  DiagID, Policy);
3832  }
3833  break;
3834  case tok::kw__Sat:
3835  if (!getLangOpts().FixedPoint) {
3836  SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3837  } else {
3838  isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3839  }
3840  break;
3841  case tok::kw___float128:
3842  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3843  DiagID, Policy);
3844  break;
3845  case tok::kw_wchar_t:
3846  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3847  DiagID, Policy);
3848  break;
3849  case tok::kw_char8_t:
3850  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3851  DiagID, Policy);
3852  break;
3853  case tok::kw_char16_t:
3854  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3855  DiagID, Policy);
3856  break;
3857  case tok::kw_char32_t:
3858  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3859  DiagID, Policy);
3860  break;
3861  case tok::kw_bool:
3862  case tok::kw__Bool:
3863  if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
3864  Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3865 
3866  if (Tok.is(tok::kw_bool) &&
3869  PrevSpec = ""; // Not used by the diagnostic.
3870  DiagID = diag::err_bool_redeclaration;
3871  // For better error recovery.
3872  Tok.setKind(tok::identifier);
3873  isInvalid = true;
3874  } else {
3875  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3876  DiagID, Policy);
3877  }
3878  break;
3879  case tok::kw__Decimal32:
3880  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3881  DiagID, Policy);
3882  break;
3883  case tok::kw__Decimal64:
3884  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3885  DiagID, Policy);
3886  break;
3887  case tok::kw__Decimal128:
3888  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3889  DiagID, Policy);
3890  break;
3891  case tok::kw___vector:
3892  isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3893  break;
3894  case tok::kw___pixel:
3895  isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3896  break;
3897  case tok::kw___bool:
3898  isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3899  break;
3900  case tok::kw_pipe:
3901  if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200 &&
3902  !getLangOpts().OpenCLCPlusPlus)) {
3903  // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3904  // support the "pipe" word as identifier.
3905  Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3906  goto DoneWithDeclSpec;
3907  }
3908  isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3909  break;
3910 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
3911  case tok::kw_##ImgType##_t: \
3912  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3913  DiagID, Policy); \
3914  break;
3915 #include "clang/Basic/OpenCLImageTypes.def"
3916  case tok::kw___unknown_anytype:
3917  isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3918  PrevSpec, DiagID, Policy);
3919  break;
3920 
3921  // class-specifier:
3922  case tok::kw_class:
3923  case tok::kw_struct:
3924  case tok::kw___interface:
3925  case tok::kw_union: {
3926  tok::TokenKind Kind = Tok.getKind();
3927  ConsumeToken();
3928 
3929  // These are attributes following class specifiers.
3930  // To produce better diagnostic, we parse them when
3931  // parsing class specifier.
3932  ParsedAttributesWithRange Attributes(AttrFactory);
3933  ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3934  EnteringContext, DSContext, Attributes);
3935 
3936  // If there are attributes following class specifier,
3937  // take them over and handle them here.
3938  if (!Attributes.empty()) {
3939  AttrsLastTime = true;
3940  attrs.takeAllFrom(Attributes);
3941  }
3942  continue;
3943  }
3944 
3945  // enum-specifier:
3946  case tok::kw_enum:
3947  ConsumeToken();
3948  ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3949  continue;
3950 
3951  // cv-qualifier:
3952  case tok::kw_const:
3953  isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3954  getLangOpts());
3955  break;
3956  case tok::kw_volatile:
3957  isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3958  getLangOpts());
3959  break;
3960  case tok::kw_restrict:
3961  isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3962  getLangOpts());
3963  break;
3964 
3965  // C++ typename-specifier:
3966  case tok::kw_typename:
3968  DS.SetTypeSpecError();
3969  goto DoneWithDeclSpec;
3970  }
3971  if (!Tok.is(tok::kw_typename))
3972  continue;
3973  break;
3974 
3975  // GNU typeof support.
3976  case tok::kw_typeof:
3977  ParseTypeofSpecifier(DS);
3978  continue;
3979 
3980  case tok::annot_decltype:
3981  ParseDecltypeSpecifier(DS);
3982  continue;
3983 
3984  case tok::annot_pragma_pack:
3985  HandlePragmaPack();
3986  continue;
3987 
3988  case tok::annot_pragma_ms_pragma:
3989  HandlePragmaMSPragma();
3990  continue;
3991 
3992  case tok::annot_pragma_ms_vtordisp:
3993  HandlePragmaMSVtorDisp();
3994  continue;
3995 
3996  case tok::annot_pragma_ms_pointers_to_members:
3997  HandlePragmaMSPointersToMembers();
3998  continue;
3999 
4000  case tok::kw___underlying_type:
4001  ParseUnderlyingTypeSpecifier(DS);
4002  continue;
4003 
4004  case tok::kw__Atomic:
4005  // C11 6.7.2.4/4:
4006  // If the _Atomic keyword is immediately followed by a left parenthesis,
4007  // it is interpreted as a type specifier (with a type name), not as a
4008  // type qualifier.
4009  if (!getLangOpts().C11)
4010  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4011 
4012  if (NextToken().is(tok::l_paren)) {
4013  ParseAtomicSpecifier(DS);
4014  continue;
4015  }
4016  isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4017  getLangOpts());
4018  break;
4019 
4020  // OpenCL address space qualifiers:
4021  case tok::kw___generic:
4022  // generic address space is introduced only in OpenCL v2.0
4023  // see OpenCL C Spec v2.0 s6.5.5
4024  if (Actions.getLangOpts().OpenCLVersion < 200 &&
4025  !Actions.getLangOpts().OpenCLCPlusPlus) {
4026  DiagID = diag::err_opencl_unknown_type_specifier;
4027  PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4028  isInvalid = true;
4029  break;
4030  }
4031  LLVM_FALLTHROUGH;
4032  case tok::kw_private:
4033  // It's fine (but redundant) to check this for __generic on the
4034  // fallthrough path; we only form the __generic token in OpenCL mode.
4035  if (!getLangOpts().OpenCL)
4036  goto DoneWithDeclSpec;
4037  LLVM_FALLTHROUGH;
4038  case tok::kw___private:
4039  case tok::kw___global:
4040  case tok::kw___local:
4041  case tok::kw___constant:
4042  // OpenCL access qualifiers:
4043  case tok::kw___read_only:
4044  case tok::kw___write_only:
4045  case tok::kw___read_write:
4046  ParseOpenCLQualifiers(DS.getAttributes());
4047  break;
4048 
4049  case tok::less:
4050  // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
4051  // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
4052  // but we support it.
4053  if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
4054  goto DoneWithDeclSpec;
4055 
4056  SourceLocation StartLoc = Tok.getLocation();
4057  SourceLocation EndLoc;
4058  TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
4059  if (Type.isUsable()) {
4060  if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
4061  PrevSpec, DiagID, Type.get(),
4062  Actions.getASTContext().getPrintingPolicy()))
4063  Diag(StartLoc, DiagID) << PrevSpec;
4064 
4065  DS.SetRangeEnd(EndLoc);
4066  } else {
4067  DS.SetTypeSpecError();
4068  }
4069 
4070  // Need to support trailing type qualifiers (e.g. "id<p> const").
4071  // If a type specifier follows, it will be diagnosed elsewhere.
4072  continue;
4073  }
4074 
4075  DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
4076 
4077  // If the specifier wasn't legal, issue a diagnostic.
4078  if (isInvalid) {
4079  assert(PrevSpec && "Method did not return previous specifier!");
4080  assert(DiagID);
4081 
4082  if (DiagID == diag::ext_duplicate_declspec ||
4083  DiagID == diag::ext_warn_duplicate_declspec ||
4084  DiagID == diag::err_duplicate_declspec)
4085  Diag(Loc, DiagID) << PrevSpec
4087  SourceRange(Loc, DS.getEndLoc()));
4088  else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4089  Diag(Loc, DiagID) << getLangOpts().OpenCLCPlusPlus
4090  << getLangOpts().getOpenCLVersionTuple().getAsString()
4091  << PrevSpec << isStorageClass;
4092  } else
4093  Diag(Loc, DiagID) << PrevSpec;
4094  }
4095 
4096  if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
4097  // After an error the next token can be an annotation token.
4098  ConsumeAnyToken();
4099 
4100  AttrsLastTime = false;
4101  }
4102 }
4103 
4104 /// ParseStructDeclaration - Parse a struct declaration without the terminating
4105 /// semicolon.
4106 ///
4107 /// Note that a struct declaration refers to a declaration in a struct,
4108 /// not to the declaration of a struct.
4109 ///
4110 /// struct-declaration:
4111 /// [C2x] attributes-specifier-seq[opt]
4112 /// specifier-qualifier-list struct-declarator-list
4113 /// [GNU] __extension__ struct-declaration
4114 /// [GNU] specifier-qualifier-list
4115 /// struct-declarator-list:
4116 /// struct-declarator
4117 /// struct-declarator-list ',' struct-declarator
4118 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
4119 /// struct-declarator:
4120 /// declarator
4121 /// [GNU] declarator attributes[opt]
4122 /// declarator[opt] ':' constant-expression
4123 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
4124 ///
4125 void Parser::ParseStructDeclaration(
4126  ParsingDeclSpec &DS,
4127  llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4128 
4129  if (Tok.is(tok::kw___extension__)) {
4130  // __extension__ silences extension warnings in the subexpression.
4131  ExtensionRAIIObject O(Diags); // Use RAII to do this.
4132  ConsumeToken();
4133  return ParseStructDeclaration(DS, FieldsCallback);
4134  }
4135 
4136  // Parse leading attributes.
4137  ParsedAttributesWithRange Attrs(AttrFactory);
4138  MaybeParseCXX11Attributes(Attrs);
4139  DS.takeAttributesFrom(Attrs);
4140 
4141  // Parse the common specifier-qualifiers-list piece.
4142  ParseSpecifierQualifierList(DS);
4143 
4144  // If there are no declarators, this is a free-standing declaration
4145  // specifier. Let the actions module cope with it.
4146  if (Tok.is(tok::semi)) {
4147  RecordDecl *AnonRecord = nullptr;
4148  Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
4149  DS, AnonRecord);
4150  assert(!AnonRecord && "Did not expect anonymous struct or union here");
4151  DS.complete(TheDecl);
4152  return;
4153  }
4154 
4155  // Read struct-declarators until we find the semicolon.
4156  bool FirstDeclarator = true;
4157  SourceLocation CommaLoc;
4158  while (1) {
4159  ParsingFieldDeclarator DeclaratorInfo(*this, DS);
4160  DeclaratorInfo.D.setCommaLoc(CommaLoc);
4161 
4162  // Attributes are only allowed here on successive declarators.
4163  if (!FirstDeclarator)
4164  MaybeParseGNUAttributes(DeclaratorInfo.D);
4165 
4166  /// struct-declarator: declarator
4167  /// struct-declarator: declarator[opt] ':' constant-expression
4168  if (Tok.isNot(tok::colon)) {
4169  // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4171  ParseDeclarator(DeclaratorInfo.D);
4172  } else
4173  DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4174 
4175  if (TryConsumeToken(tok::colon)) {
4177  if (Res.isInvalid())
4178  SkipUntil(tok::semi, StopBeforeMatch);
4179  else
4180  DeclaratorInfo.BitfieldSize = Res.get();
4181  }
4182 
4183  // If attributes exist after the declarator, parse them.
4184  MaybeParseGNUAttributes(DeclaratorInfo.D);
4185 
4186  // We're done with this declarator; invoke the callback.
4187  FieldsCallback(DeclaratorInfo);
4188 
4189  // If we don't have a comma, it is either the end of the list (a ';')
4190  // or an error, bail out.
4191  if (!TryConsumeToken(tok::comma, CommaLoc))
4192  return;
4193 
4194  FirstDeclarator = false;
4195  }
4196 }
4197 
4198 /// ParseStructUnionBody
4199 /// struct-contents:
4200 /// struct-declaration-list
4201 /// [EXT] empty
4202 /// [GNU] "struct-declaration-list" without terminatoring ';'
4203 /// struct-declaration-list:
4204 /// struct-declaration
4205 /// struct-declaration-list struct-declaration
4206 /// [OBC] '@' 'defs' '(' class-name ')'
4207 ///
4208 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4210  PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4211  "parsing struct/union body");
4212  assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4213 
4214  BalancedDelimiterTracker T(*this, tok::l_brace);
4215  if (T.consumeOpen())
4216  return;
4217 
4218  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4219  Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
4220 
4221  SmallVector<Decl *, 32> FieldDecls;
4222 
4223  // While we still have something to read, read the declarations in the struct.
4224  while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4225  Tok.isNot(tok::eof)) {
4226  // Each iteration of this loop reads one struct-declaration.
4227 
4228  // Check for extraneous top-level semicolon.
4229  if (Tok.is(tok::semi)) {
4230  ConsumeExtraSemi(InsideStruct, TagType);
4231  continue;
4232  }
4233 
4234  // Parse _Static_assert declaration.
4235  if (Tok.is(tok::kw__Static_assert)) {
4236  SourceLocation DeclEnd;
4237  ParseStaticAssertDeclaration(DeclEnd);
4238  continue;
4239  }
4240 
4241  if (Tok.is(tok::annot_pragma_pack)) {
4242  HandlePragmaPack();
4243  continue;
4244  }
4245 
4246  if (Tok.is(tok::annot_pragma_align)) {
4247  HandlePragmaAlign();
4248  continue;
4249  }
4250 
4251  if (Tok.is(tok::annot_pragma_openmp)) {
4252  // Result can be ignored, because it must be always empty.
4253  AccessSpecifier AS = AS_none;
4254  ParsedAttributesWithRange Attrs(AttrFactory);
4255  (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4256  continue;
4257  }
4258 
4259  if (tok::isPragmaAnnotation(Tok.getKind())) {
4260  Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4262  TagType, Actions.getASTContext().getPrintingPolicy());
4263  ConsumeAnnotationToken();
4264  continue;
4265  }
4266 
4267  if (!Tok.is(tok::at)) {
4268  auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4269  // Install the declarator into the current TagDecl.
4270  Decl *Field =
4271  Actions.ActOnField(getCurScope(), TagDecl,
4272  FD.D.getDeclSpec().getSourceRange().getBegin(),
4273  FD.D, FD.BitfieldSize);
4274  FieldDecls.push_back(Field);
4275  FD.complete(Field);
4276  };
4277 
4278  // Parse all the comma separated declarators.
4279  ParsingDeclSpec DS(*this);
4280  ParseStructDeclaration(DS, CFieldCallback);
4281  } else { // Handle @defs
4282  ConsumeToken();
4283  if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4284  Diag(Tok, diag::err_unexpected_at);
4285  SkipUntil(tok::semi);
4286  continue;
4287  }
4288  ConsumeToken();
4289  ExpectAndConsume(tok::l_paren);
4290  if (!Tok.is(tok::identifier)) {
4291  Diag(Tok, diag::err_expected) << tok::identifier;
4292  SkipUntil(tok::semi);
4293  continue;
4294  }
4295  SmallVector<Decl *, 16> Fields;
4296  Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4297  Tok.getIdentifierInfo(), Fields);
4298  FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4299  ConsumeToken();
4300  ExpectAndConsume(tok::r_paren);
4301  }
4302 
4303  if (TryConsumeToken(tok::semi))
4304  continue;
4305 
4306  if (Tok.is(tok::r_brace)) {
4307  ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4308  break;
4309  }
4310 
4311  ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4312  // Skip to end of block or statement to avoid ext-warning on extra ';'.
4313  SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4314  // If we stopped at a ';', eat it.
4315  TryConsumeToken(tok::semi);
4316  }
4317 
4318  T.consumeClose();
4319 
4320  ParsedAttributes attrs(AttrFactory);
4321  // If attributes exist after struct contents, parse them.
4322  MaybeParseGNUAttributes(attrs);
4323 
4324  Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4325  T.getOpenLocation(), T.getCloseLocation(), attrs);
4326  StructScope.Exit();
4327  Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4328 }
4329 
4330 /// ParseEnumSpecifier
4331 /// enum-specifier: [C99 6.7.2.2]
4332 /// 'enum' identifier[opt] '{' enumerator-list '}'
4333 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4334 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4335 /// '}' attributes[opt]
4336 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4337 /// '}'
4338 /// 'enum' identifier
4339 /// [GNU] 'enum' attributes[opt] identifier
4340 ///
4341 /// [C++11] enum-head '{' enumerator-list[opt] '}'
4342 /// [C++11] enum-head '{' enumerator-list ',' '}'
4343 ///
4344 /// enum-head: [C++11]
4345 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4346 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
4347 /// identifier enum-base[opt]
4348 ///
4349 /// enum-key: [C++11]
4350 /// 'enum'
4351 /// 'enum' 'class'
4352 /// 'enum' 'struct'
4353 ///
4354 /// enum-base: [C++11]
4355 /// ':' type-specifier-seq
4356 ///
4357 /// [C++] elaborated-type-specifier:
4358 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4359 ///
4360 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4361  const ParsedTemplateInfo &TemplateInfo,
4362  AccessSpecifier AS, DeclSpecContext DSC) {
4363  // Parse the tag portion of this.
4364  if (Tok.is(tok::code_completion)) {
4365  // Code completion for an enum name.
4366  Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
4367  return cutOffParsing();
4368  }
4369 
4370  // If attributes exist after tag, parse them.
4371  ParsedAttributesWithRange attrs(AttrFactory);
4372  MaybeParseGNUAttributes(attrs);
4373  MaybeParseCXX11Attributes(attrs);
4374  MaybeParseMicrosoftDeclSpecs(attrs);
4375 
4376  SourceLocation ScopedEnumKWLoc;
4377  bool IsScopedUsingClassTag = false;
4378 
4379  // In C++11, recognize 'enum class' and 'enum struct'.
4380  if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4381  Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4382  : diag::ext_scoped_enum);
4383  IsScopedUsingClassTag = Tok.is(tok::kw_class);
4384  ScopedEnumKWLoc = ConsumeToken();
4385 
4386  // Attributes are not allowed between these keywords. Diagnose,
4387  // but then just treat them like they appeared in the right place.
4388  ProhibitAttributes(attrs);
4389 
4390  // They are allowed afterwards, though.
4391  MaybeParseGNUAttributes(attrs);
4392  MaybeParseCXX11Attributes(attrs);
4393  MaybeParseMicrosoftDeclSpecs(attrs);
4394  }
4395 
4396  // C++11 [temp.explicit]p12:
4397  // The usual access controls do not apply to names used to specify
4398  // explicit instantiations.
4399  // We extend this to also cover explicit specializations. Note that
4400  // we don't suppress if this turns out to be an elaborated type
4401  // specifier.
4402  bool shouldDelayDiagsInTag =
4403  (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4404  TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4405  SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4406 
4407  // Enum definitions should not be parsed in a trailing-return-type.
4408  bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
4409 
4410  CXXScopeSpec &SS = DS.getTypeSpecScope();
4411  if (getLangOpts().CPlusPlus) {
4412  // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4413  // if a fixed underlying type is allowed.
4414  ColonProtectionRAIIObject X(*this, AllowDeclaration);
4415 
4416  CXXScopeSpec Spec;
4417  if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
4418  /*EnteringContext=*/true))
4419  return;
4420 
4421  if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4422  Diag(Tok, diag::err_expected) << tok::identifier;
4423  if (Tok.isNot(tok::l_brace)) {
4424  // Has no name and is not a definition.
4425  // Skip the rest of this declarator, up until the comma or semicolon.
4426  SkipUntil(tok::comma, StopAtSemi);
4427  return;
4428  }
4429  }
4430 
4431  SS = Spec;
4432  }
4433 
4434  // Must have either 'enum name' or 'enum {...}'.
4435  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4436  !(AllowDeclaration && Tok.is(tok::colon))) {
4437  Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4438 
4439  // Skip the rest of this declarator, up until the comma or semicolon.
4440  SkipUntil(tok::comma, StopAtSemi);
4441  return;
4442  }
4443 
4444  // If an identifier is present, consume and remember it.
4445  IdentifierInfo *Name = nullptr;
4446  SourceLocation NameLoc;
4447  if (Tok.is(tok::identifier)) {
4448  Name = Tok.getIdentifierInfo();
4449  NameLoc = ConsumeToken();
4450  }
4451 
4452  if (!Name && ScopedEnumKWLoc.isValid()) {
4453  // C++0x 7.2p2: The optional identifier shall not be omitted in the
4454  // declaration of a scoped enumeration.
4455  Diag(Tok, diag::err_scoped_enum_missing_identifier);
4456  ScopedEnumKWLoc = SourceLocation();
4457  IsScopedUsingClassTag = false;
4458  }
4459 
4460  // Okay, end the suppression area. We'll decide whether to emit the
4461  // diagnostics in a second.
4462  if (shouldDelayDiagsInTag)
4463  diagsFromTag.done();
4464 
4465  TypeResult BaseType;
4466 
4467  // Parse the fixed underlying type.
4468  bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4469  if (AllowDeclaration && Tok.is(tok::colon)) {
4470  bool PossibleBitfield = false;
4471  if (CanBeBitfield) {
4472  // If we're in class scope, this can either be an enum declaration with
4473  // an underlying type, or a declaration of a bitfield member. We try to
4474  // use a simple disambiguation scheme first to catch the common cases
4475  // (integer literal, sizeof); if it's still ambiguous, we then consider
4476  // anything that's a simple-type-specifier followed by '(' as an
4477  // expression. This suffices because function types are not valid
4478  // underlying types anyway.
4481  TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
4482  // If the next token starts an expression, we know we're parsing a
4483  // bit-field. This is the common case.
4484  if (TPR == TPResult::True)
4485  PossibleBitfield = true;
4486  // If the next token starts a type-specifier-seq, it may be either a
4487  // a fixed underlying type or the start of a function-style cast in C++;
4488  // lookahead one more token to see if it's obvious that we have a
4489  // fixed underlying type.
4490  else if (TPR == TPResult::False &&
4491  GetLookAheadToken(2).getKind() == tok::semi) {
4492  // Consume the ':'.
4493  ConsumeToken();
4494  } else {
4495  // We have the start of a type-specifier-seq, so we have to perform
4496  // tentative parsing to determine whether we have an expression or a
4497  // type.
4498  TentativeParsingAction TPA(*this);
4499 
4500  // Consume the ':'.
4501  ConsumeToken();
4502 
4503  // If we see a type specifier followed by an open-brace, we have an
4504  // ambiguity between an underlying type and a C++11 braced
4505  // function-style cast. Resolve this by always treating it as an
4506  // underlying type.
4507  // FIXME: The standard is not entirely clear on how to disambiguate in
4508  // this case.
4509  if ((getLangOpts().CPlusPlus &&
4510  isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
4511  (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
4512  // We'll parse this as a bitfield later.
4513  PossibleBitfield = true;
4514  TPA.Revert();
4515  } else {
4516  // We have a type-specifier-seq.
4517  TPA.Commit();
4518  }
4519  }
4520  } else {
4521  // Consume the ':'.
4522  ConsumeToken();
4523  }
4524 
4525  if (!PossibleBitfield) {
4526  SourceRange Range;
4527  BaseType = ParseTypeName(&Range);
4528 
4529  if (!getLangOpts().ObjC) {
4530  if (getLangOpts().CPlusPlus11)
4531  Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4532  else if (getLangOpts().CPlusPlus)
4533  Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type);
4534  else if (getLangOpts().MicrosoftExt)
4535  Diag(StartLoc, diag::ext_ms_c_enum_fixed_underlying_type);
4536  else
4537  Diag(StartLoc, diag::ext_clang_c_enum_fixed_underlying_type);
4538  }
4539  }
4540  }
4541 
4542  // There are four options here. If we have 'friend enum foo;' then this is a
4543  // friend declaration, and cannot have an accompanying definition. If we have
4544  // 'enum foo;', then this is a forward declaration. If we have
4545  // 'enum foo {...' then this is a definition. Otherwise we have something
4546  // like 'enum foo xyz', a reference.
4547  //
4548  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4549  // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4550  // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4551  //
4552  Sema::TagUseKind TUK;
4553  if (!AllowDeclaration) {
4554  TUK = Sema::TUK_Reference;
4555  } else if (Tok.is(tok::l_brace)) {
4556  if (DS.isFriendSpecified()) {
4557  Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4558  << SourceRange(DS.getFriendSpecLoc());
4559  ConsumeBrace();
4560  SkipUntil(tok::r_brace, StopAtSemi);
4561  TUK = Sema::TUK_Friend;
4562  } else {
4563  TUK = Sema::TUK_Definition;
4564  }
4565  } else if (!isTypeSpecifier(DSC) &&
4566  (Tok.is(tok::semi) ||
4567  (Tok.isAtStartOfLine() &&
4568  !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4570  if (Tok.isNot(tok::semi)) {
4571  // A semicolon was missing after this declaration. Diagnose and recover.
4572  ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4573  PP.EnterToken(Tok, /*IsReinject=*/true);
4574  Tok.setKind(tok::semi);
4575  }
4576  } else {
4577  TUK = Sema::TUK_Reference;
4578  }
4579 
4580  // If this is an elaborated type specifier, and we delayed
4581  // diagnostics before, just merge them into the current pool.
4582  if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4583  diagsFromTag.redelay();
4584  }
4585 
4586  MultiTemplateParamsArg TParams;
4587  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4588  TUK != Sema::TUK_Reference) {
4589  if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4590  // Skip the rest of this declarator, up until the comma or semicolon.
4591  Diag(Tok, diag::err_enum_template);
4592  SkipUntil(tok::comma, StopAtSemi);
4593  return;
4594  }
4595 
4596  if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4597  // Enumerations can't be explicitly instantiated.
4598  DS.SetTypeSpecError();
4599  Diag(StartLoc, diag::err_explicit_instantiation_enum);
4600  return;
4601  }
4602 
4603  assert(TemplateInfo.TemplateParams && "no template parameters");
4604  TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4605  TemplateInfo.TemplateParams->size());
4606  }
4607 
4608  if (TUK == Sema::TUK_Reference)
4609  ProhibitAttributes(attrs);
4610 
4611  if (!Name && TUK != Sema::TUK_Definition) {
4612  Diag(Tok, diag::err_enumerator_unnamed_no_def);
4613 
4614  // Skip the rest of this declarator, up until the comma or semicolon.
4615  SkipUntil(tok::comma, StopAtSemi);
4616  return;
4617  }
4618 
4619  stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4620 
4621  Sema::SkipBodyInfo SkipBody;
4622  if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4623  NextToken().is(tok::identifier))
4624  SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4625  NextToken().getIdentifierInfo(),
4626  NextToken().getLocation());
4627 
4628  bool Owned = false;
4629  bool IsDependent = false;
4630  const char *PrevSpec = nullptr;
4631  unsigned DiagID;
4632  Decl *TagDecl = Actions.ActOnTag(
4633  getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
4634  attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4635  ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
4636  DSC == DeclSpecContext::DSC_type_specifier,
4637  DSC == DeclSpecContext::DSC_template_param ||
4638  DSC == DeclSpecContext::DSC_template_type_arg,
4639  &SkipBody);
4640 
4641  if (SkipBody.ShouldSkip) {
4642  assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4643 
4644  BalancedDelimiterTracker T(*this, tok::l_brace);
4645  T.consumeOpen();
4646  T.skipToEnd();
4647 
4648  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4649  NameLoc.isValid() ? NameLoc : StartLoc,
4650  PrevSpec, DiagID, TagDecl, Owned,
4651  Actions.getASTContext().getPrintingPolicy()))
4652  Diag(StartLoc, DiagID) << PrevSpec;
4653  return;
4654  }
4655 
4656  if (IsDependent) {
4657  // This enum has a dependent nested-name-specifier. Handle it as a
4658  // dependent tag.
4659  if (!Name) {
4660  DS.SetTypeSpecError();
4661  Diag(Tok, diag::err_expected_type_name_after_typename);
4662  return;
4663  }
4664 
4665  TypeResult Type = Actions.ActOnDependentTag(
4666  getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4667  if (Type.isInvalid()) {
4668  DS.SetTypeSpecError();
4669  return;
4670  }
4671 
4672  if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4673  NameLoc.isValid() ? NameLoc : StartLoc,
4674  PrevSpec, DiagID, Type.get(),
4675  Actions.getASTContext().getPrintingPolicy()))
4676  Diag(StartLoc, DiagID) << PrevSpec;
4677 
4678  return;
4679  }
4680 
4681  if (!TagDecl) {
4682  // The action failed to produce an enumeration tag. If this is a
4683  // definition, consume the entire definition.
4684  if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4685  ConsumeBrace();
4686  SkipUntil(tok::r_brace, StopAtSemi);
4687  }
4688 
4689  DS.SetTypeSpecError();
4690  return;
4691  }
4692 
4693  if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4694  Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4695  ParseEnumBody(StartLoc, D);
4696  if (SkipBody.CheckSameAsPrevious &&
4697  !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4698  DS.SetTypeSpecError();
4699  return;
4700  }
4701  }
4702 
4703  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4704  NameLoc.isValid() ? NameLoc : StartLoc,
4705  PrevSpec, DiagID, TagDecl, Owned,
4706  Actions.getASTContext().getPrintingPolicy()))
4707  Diag(StartLoc, DiagID) << PrevSpec;
4708 }
4709 
4710 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4711 /// enumerator-list:
4712 /// enumerator
4713 /// enumerator-list ',' enumerator
4714 /// enumerator:
4715 /// enumeration-constant attributes[opt]
4716 /// enumeration-constant attributes[opt] '=' constant-expression
4717 /// enumeration-constant:
4718 /// identifier
4719 ///
4720 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4721  // Enter the scope of the enum body and start the definition.
4722  ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4723  Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4724 
4725  BalancedDelimiterTracker T(*this, tok::l_brace);
4726  T.consumeOpen();
4727 
4728  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4729  if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4730  Diag(Tok, diag::err_empty_enum);
4731 
4732  SmallVector<Decl *, 32> EnumConstantDecls;
4733  SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4734 
4735  Decl *LastEnumConstDecl = nullptr;
4736 
4737  // Parse the enumerator-list.
4738  while (Tok.isNot(tok::r_brace)) {
4739  // Parse enumerator. If failed, try skipping till the start of the next
4740  // enumerator definition.
4741  if (Tok.isNot(tok::identifier)) {
4742  Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4743  if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4744  TryConsumeToken(tok::comma))
4745  continue;
4746  break;
4747  }
4748  IdentifierInfo *Ident = Tok.getIdentifierInfo();
4749  SourceLocation IdentLoc = ConsumeToken();
4750 
4751  // If attributes exist after the enumerator, parse them.
4752  ParsedAttributesWithRange attrs(AttrFactory);
4753  MaybeParseGNUAttributes(attrs);
4754  ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4755  if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4756  if (getLangOpts().CPlusPlus)
4757  Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4758  ? diag::warn_cxx14_compat_ns_enum_attribute
4759  : diag::ext_ns_enum_attribute)
4760  << 1 /*enumerator*/;
4761  ParseCXX11Attributes(attrs);
4762  }
4763 
4764  SourceLocation EqualLoc;
4765  ExprResult AssignedVal;
4766  EnumAvailabilityDiags.emplace_back(*this);
4767 
4768  EnterExpressionEvaluationContext ConstantEvaluated(
4770  if (TryConsumeToken(tok::equal, EqualLoc)) {
4772  if (AssignedVal.isInvalid())
4773  SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4774  }
4775 
4776  // Install the enumerator constant into EnumDecl.
4777  Decl *EnumConstDecl = Actions.ActOnEnumConstant(
4778  getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4779  EqualLoc, AssignedVal.get());
4780  EnumAvailabilityDiags.back().done();
4781 
4782  EnumConstantDecls.push_back(EnumConstDecl);
4783  LastEnumConstDecl = EnumConstDecl;
4784 
4785  if (Tok.is(tok::identifier)) {
4786  // We're missing a comma between enumerators.
4788  Diag(Loc, diag::err_enumerator_list_missing_comma)
4789  << FixItHint::CreateInsertion(Loc, ", ");
4790  continue;
4791  }
4792 
4793  // Emumerator definition must be finished, only comma or r_brace are
4794  // allowed here.
4795  SourceLocation CommaLoc;
4796  if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4797  if (EqualLoc.isValid())
4798  Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4799  << tok::comma;
4800  else
4801  Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4802  if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4803  if (TryConsumeToken(tok::comma, CommaLoc))
4804  continue;
4805  } else {
4806  break;
4807  }
4808  }
4809 
4810  // If comma is followed by r_brace, emit appropriate warning.
4811  if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4812  if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4813  Diag(CommaLoc, getLangOpts().CPlusPlus ?
4814  diag::ext_enumerator_list_comma_cxx :
4815  diag::ext_enumerator_list_comma_c)
4816  << FixItHint::CreateRemoval(CommaLoc);
4817  else if (getLangOpts().CPlusPlus11)
4818  Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4819  << FixItHint::CreateRemoval(CommaLoc);
4820  break;
4821  }
4822  }
4823 
4824  // Eat the }.
4825  T.consumeClose();
4826 
4827  // If attributes exist after the identifier list, parse them.
4828  ParsedAttributes attrs(AttrFactory);
4829  MaybeParseGNUAttributes(attrs);
4830 
4831  Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4832  getCurScope(), attrs);
4833 
4834  // Now handle enum constant availability diagnostics.
4835  assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4836  for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4838  EnumAvailabilityDiags[i].redelay();
4839  PD.complete(EnumConstantDecls[i]);
4840  }
4841 
4842  EnumScope.Exit();
4843  Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4844 
4845  // The next token must be valid after an enum definition. If not, a ';'
4846  // was probably forgotten.
4847  bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4848  if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4849  ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4850  // Push this token back into the preprocessor and change our current token
4851  // to ';' so that the rest of the code recovers as though there were an
4852  // ';' after the definition.
4853  PP.EnterToken(Tok, /*IsReinject=*/true);
4854  Tok.setKind(tok::semi);
4855  }
4856 }
4857 
4858 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4859 /// is definitely a type-specifier. Return false if it isn't part of a type
4860 /// specifier or if we're not sure.
4861 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4862  switch (Tok.getKind()) {
4863  default: return false;
4864  // type-specifiers
4865  case tok::kw_short:
4866  case tok::kw_long:
4867  case tok::kw___int64:
4868  case tok::kw___int128:
4869  case tok::kw_signed:
4870  case tok::kw_unsigned:
4871  case tok::kw__Complex:
4872  case tok::kw__Imaginary:
4873  case tok::kw_void:
4874  case tok::kw_char:
4875  case tok::kw_wchar_t:
4876  case tok::kw_char8_t:
4877  case tok::kw_char16_t:
4878  case tok::kw_char32_t:
4879  case tok::kw_int:
4880  case tok::kw_half:
4881  case tok::kw_float:
4882  case tok::kw_double:
4883  case tok::kw__Accum:
4884  case tok::kw__Fract:
4885  case tok::kw__Float16:
4886  case tok::kw___float128:
4887  case tok::kw_bool:
4888  case tok::kw__Bool:
4889  case tok::kw__Decimal32:
4890  case tok::kw__Decimal64:
4891  case tok::kw__Decimal128:
4892  case tok::kw___vector:
4893 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4894 #include "clang/Basic/OpenCLImageTypes.def"
4895 
4896  // struct-or-union-specifier (C99) or class-specifier (C++)
4897  case tok::kw_class:
4898  case tok::kw_struct:
4899  case tok::kw___interface:
4900  case tok::kw_union:
4901  // enum-specifier
4902  case tok::kw_enum:
4903 
4904  // typedef-name
4905  case tok::annot_typename:
4906  return true;
4907  }
4908 }
4909 
4910 /// isTypeSpecifierQualifier - Return true if the current token could be the
4911 /// start of a specifier-qualifier-list.
4912 bool Parser::isTypeSpecifierQualifier() {
4913  switch (Tok.getKind()) {
4914  default: return false;
4915 
4916  case tok::identifier: // foo::bar
4917  if (TryAltiVecVectorToken())
4918  return true;
4919  LLVM_FALLTHROUGH;
4920  case tok::kw_typename: // typename T::type
4921  // Annotate typenames and C++ scope specifiers. If we get one, just
4922  // recurse to handle whatever we get.
4924  return true;
4925  if (Tok.is(tok::identifier))
4926  return false;
4927  return isTypeSpecifierQualifier();
4928 
4929  case tok::coloncolon: // ::foo::bar
4930  if (NextToken().is(tok::kw_new) || // ::new
4931  NextToken().is(tok::kw_delete)) // ::delete
4932  return false;
4933 
4935  return true;
4936  return isTypeSpecifierQualifier();
4937 
4938  // GNU attributes support.
4939  case tok::kw___attribute:
4940  // GNU typeof support.
4941  case tok::kw_typeof:
4942 
4943  // type-specifiers
4944  case tok::kw_short:
4945  case tok::kw_long:
4946  case tok::kw___int64:
4947  case tok::kw___int128:
4948  case tok::kw_signed:
4949  case tok::kw_unsigned:
4950  case tok::kw__Complex:
4951  case tok::kw__Imaginary:
4952  case tok::kw_void:
4953  case tok::kw_char:
4954  case tok::kw_wchar_t:
4955  case tok::kw_char8_t:
4956  case tok::kw_char16_t:
4957  case tok::kw_char32_t:
4958  case tok::kw_int:
4959  case tok::kw_half:
4960  case tok::kw_float:
4961  case tok::kw_double:
4962  case tok::kw__Accum:
4963  case tok::kw__Fract:
4964  case tok::kw__Float16:
4965  case tok::kw___float128:
4966  case tok::kw_bool:
4967  case tok::kw__Bool:
4968  case tok::kw__Decimal32:
4969  case tok::kw__Decimal64:
4970  case tok::kw__Decimal128:
4971  case tok::kw___vector:
4972 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4973 #include "clang/Basic/OpenCLImageTypes.def"
4974 
4975  // struct-or-union-specifier (C99) or class-specifier (C++)
4976  case tok::kw_class:
4977  case tok::kw_struct:
4978  case tok::kw___interface:
4979  case tok::kw_union:
4980  // enum-specifier
4981  case tok::kw_enum:
4982 
4983  // type-qualifier
4984  case tok::kw_const:
4985  case tok::kw_volatile:
4986  case tok::kw_restrict:
4987  case tok::kw__Sat:
4988 
4989  // Debugger support.
4990  case tok::kw___unknown_anytype:
4991 
4992  // typedef-name
4993  case tok::annot_typename:
4994  return true;
4995 
4996  // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4997  case tok::less:
4998  return getLangOpts().ObjC;
4999 
5000  case tok::kw___cdecl:
5001  case tok::kw___stdcall:
5002  case tok::kw___fastcall:
5003  case tok::kw___thiscall:
5004  case tok::kw___regcall:
5005  case tok::kw___vectorcall:
5006  case tok::kw___w64:
5007  case tok::kw___ptr64:
5008  case tok::kw___ptr32:
5009  case tok::kw___pascal:
5010  case tok::kw___unaligned:
5011 
5012  case tok::kw__Nonnull:
5013  case tok::kw__Nullable:
5014  case tok::kw__Null_unspecified:
5015 
5016  case tok::kw___kindof:
5017 
5018  case tok::kw___private:
5019  case tok::kw___local:
5020  case tok::kw___global:
5021  case tok::kw___constant:
5022  case tok::kw___generic:
5023  case tok::kw___read_only:
5024  case tok::kw___read_write:
5025  case tok::kw___write_only:
5026  return true;
5027 
5028  case tok::kw_private:
5029  return getLangOpts().OpenCL;
5030 
5031  // C11 _Atomic
5032  case tok::kw__Atomic:
5033  return true;
5034  }
5035 }
5036 
5037 /// isDeclarationSpecifier() - Return true if the current token is part of a
5038 /// declaration specifier.
5039 ///
5040 /// \param DisambiguatingWithExpression True to indicate that the purpose of
5041 /// this check is to disambiguate between an expression and a declaration.
5042 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
5043  switch (Tok.getKind()) {
5044  default: return false;
5045 
5046  case tok::kw_pipe:
5047  return (getLangOpts().OpenCL && getLangOpts().OpenCLVersion >= 200) ||
5048  getLangOpts().OpenCLCPlusPlus;
5049 
5050  case tok::identifier: // foo::bar
5051  // Unfortunate hack to support "Class.factoryMethod" notation.
5052  if (getLangOpts().ObjC && NextToken().is(tok::period))
5053  return false;
5054  if (TryAltiVecVectorToken())
5055  return true;
5056  LLVM_FALLTHROUGH;
5057  case tok::kw_decltype: // decltype(T())::type
5058  case tok::kw_typename: // typename T::type
5059  // Annotate typenames and C++ scope specifiers. If we get one, just
5060  // recurse to handle whatever we get.
5062  return true;
5063  if (TryAnnotateTypeConstraint())
5064  return true;
5065  if (Tok.is(tok::identifier))
5066  return false;
5067 
5068  // If we're in Objective-C and we have an Objective-C class type followed
5069  // by an identifier and then either ':' or ']', in a place where an
5070  // expression is permitted, then this is probably a class message send
5071  // missing the initial '['. In this case, we won't consider this to be
5072  // the start of a declaration.
5073  if (DisambiguatingWithExpression &&
5074  isStartOfObjCClassMessageMissingOpenBracket())
5075  return false;
5076 
5077  return isDeclarationSpecifier();
5078 
5079  case tok::coloncolon: // ::foo::bar
5080  if (NextToken().is(tok::kw_new) || // ::new
5081  NextToken().is(tok::kw_delete)) // ::delete
5082  return false;
5083 
5084  // Annotate typenames and C++ scope specifiers. If we get one, just
5085  // recurse to handle whatever we get.
5087  return true;
5088  return isDeclarationSpecifier();
5089 
5090  // storage-class-specifier
5091  case tok::kw_typedef:
5092  case tok::kw_extern:
5093  case tok::kw___private_extern__:
5094  case tok::kw_static:
5095  case tok::kw_auto:
5096  case tok::kw___auto_type:
5097  case tok::kw_register:
5098  case tok::kw___thread:
5099  case tok::kw_thread_local:
5100  case tok::kw__Thread_local:
5101 
5102  // Modules
5103  case tok::kw___module_private__:
5104 
5105  // Debugger support
5106  case tok::kw___unknown_anytype:
5107 
5108  // type-specifiers
5109  case tok::kw_short:
5110  case tok::kw_long:
5111  case tok::kw___int64:
5112  case tok::kw___int128:
5113  case tok::kw_signed:
5114  case tok::kw_unsigned:
5115  case tok::kw__Complex:
5116  case tok::kw__Imaginary:
5117  case tok::kw_void:
5118  case tok::kw_char:
5119  case tok::kw_wchar_t:
5120  case tok::kw_char8_t:
5121  case tok::kw_char16_t:
5122  case tok::kw_char32_t:
5123 
5124  case tok::kw_int:
5125  case tok::kw_half:
5126  case tok::kw_float:
5127  case tok::kw_double:
5128  case tok::kw__Accum:
5129  case tok::kw__Fract:
5130  case tok::kw__Float16:
5131  case tok::kw___float128:
5132  case tok::kw_bool:
5133  case tok::kw__Bool:
5134  case tok::kw__Decimal32:
5135  case tok::kw__Decimal64:
5136  case tok::kw__Decimal128:
5137  case tok::kw___vector:
5138 
5139  // struct-or-union-specifier (C99) or class-specifier (C++)
5140  case tok::kw_class:
5141  case tok::kw_struct:
5142  case tok::kw_union:
5143  case tok::kw___interface:
5144  // enum-specifier
5145  case tok::kw_enum:
5146 
5147  // type-qualifier
5148  case tok::kw_const:
5149  case tok::kw_volatile:
5150  case tok::kw_restrict:
5151  case tok::kw__Sat:
5152 
5153  // function-specifier
5154  case tok::kw_inline:
5155  case tok::kw_virtual:
5156  case tok::kw_explicit:
5157  case tok::kw__Noreturn:
5158 
5159  // alignment-specifier
5160  case tok::kw__Alignas:
5161 
5162  // friend keyword.
5163  case tok::kw_friend:
5164 
5165  // static_assert-declaration
5166  case tok::kw__Static_assert:
5167 
5168  // GNU typeof support.
5169  case tok::kw_typeof:
5170 
5171  // GNU attributes.
5172  case tok::kw___attribute:
5173 
5174  // C++11 decltype and constexpr.
5175  case tok::annot_decltype:
5176  case tok::kw_constexpr:
5177 
5178  // C++20 consteval and constinit.
5179  case tok::kw_consteval:
5180  case tok::kw_constinit:
5181 
5182  // C11 _Atomic
5183  case tok::kw__Atomic:
5184  return true;
5185 
5186  // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5187  case tok::less:
5188  return getLangOpts().ObjC;
5189 
5190  // typedef-name
5191  case tok::annot_typename:
5192  return !DisambiguatingWithExpression ||
5193  !isStartOfObjCClassMessageMissingOpenBracket();
5194 
5195  // placeholder-type-specifier
5196  case tok::annot_template_id: {
5197  return isTypeConstraintAnnotation() &&
5198  (NextToken().is(tok::kw_auto) || NextToken().is(tok::kw_decltype));
5199  }
5200  case tok::annot_cxxscope:
5201  if (NextToken().is(tok::identifier) && TryAnnotateTypeConstraint())
5202  return true;
5203  return isTypeConstraintAnnotation() &&
5204  GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype);
5205  case tok::kw___declspec:
5206  case tok::kw___cdecl:
5207  case tok::kw___stdcall:
5208  case tok::kw___fastcall:
5209  case tok::kw___thiscall:
5210  case tok::kw___regcall:
5211  case tok::kw___vectorcall:
5212  case tok::kw___w64:
5213  case tok::kw___sptr:
5214  case tok::kw___uptr:
5215  case tok::kw___ptr64:
5216  case tok::kw___ptr32:
5217  case tok::kw___forceinline:
5218  case tok::kw___pascal:
5219  case tok::kw___unaligned:
5220 
5221  case tok::kw__Nonnull:
5222  case tok::kw__Nullable:
5223  case tok::kw__Null_unspecified:
5224 
5225  case tok::kw___kindof:
5226 
5227  case tok::kw___private:
5228  case tok::kw___local:
5229  case tok::kw___global:
5230  case tok::kw___constant:
5231  case tok::kw___generic:
5232  case tok::kw___read_only:
5233  case tok::kw___read_write:
5234  case tok::kw___write_only:
5235 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5236 #include "clang/Basic/OpenCLImageTypes.def"
5237 
5238  return true;
5239 
5240  case tok::kw_private:
5241  return getLangOpts().OpenCL;
5242  }
5243 }
5244 
5245 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
5246  TentativeParsingAction TPA(*this);
5247 
5248  // Parse the C++ scope specifier.
5249  CXXScopeSpec SS;
5250  if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
5251  /*EnteringContext=*/true)) {
5252  TPA.Revert();
5253  return false;
5254  }
5255 
5256  // Parse the constructor name.
5257  if (Tok.is(tok::identifier)) {
5258  // We already know that we have a constructor name; just consume
5259  // the token.
5260  ConsumeToken();
5261  } else if (Tok.is(tok::annot_template_id)) {
5262  ConsumeAnnotationToken();
5263  } else {
5264  TPA.Revert();
5265  return false;
5266  }
5267 
5268  // There may be attributes here, appertaining to the constructor name or type
5269  // we just stepped past.
5270  SkipCXX11Attributes();
5271 
5272  // Current class name must be followed by a left parenthesis.
5273  if (Tok.isNot(tok::l_paren)) {
5274  TPA.Revert();
5275  return false;
5276  }
5277  ConsumeParen();
5278 
5279  // A right parenthesis, or ellipsis followed by a right parenthesis signals
5280  // that we have a constructor.
5281  if (Tok.is(tok::r_paren) ||
5282  (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
5283  TPA.Revert();
5284  return true;
5285  }
5286 
5287  // A C++11 attribute here signals that we have a constructor, and is an
5288  // attribute on the first constructor parameter.
5289  if (getLangOpts().CPlusPlus11 &&
5290  isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5291  /*OuterMightBeMessageSend*/ true)) {
5292  TPA.Revert();
5293  return true;
5294  }
5295 
5296  // If we need to, enter the specified scope.
5297  DeclaratorScopeObj DeclScopeObj(*this, SS);
5298  if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
5299  DeclScopeObj.EnterDeclaratorScope();
5300 
5301  // Optionally skip Microsoft attributes.
5302  ParsedAttributes Attrs(AttrFactory);
5303  MaybeParseMicrosoftAttributes(Attrs);
5304 
5305  // Check whether the next token(s) are part of a declaration
5306  // specifier, in which case we have the start of a parameter and,
5307  // therefore, we know that this is a constructor.
5308  bool IsConstructor = false;
5309  if (isDeclarationSpecifier())
5310  IsConstructor = true;
5311  else if (Tok.is(tok::identifier) ||
5312  (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5313  // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5314  // This might be a parenthesized member name, but is more likely to
5315  // be a constructor declaration with an invalid argument type. Keep
5316  // looking.
5317  if (Tok.is(tok::annot_cxxscope))
5318  ConsumeAnnotationToken();
5319  ConsumeToken();
5320 
5321  // If this is not a constructor, we must be parsing a declarator,
5322  // which must have one of the following syntactic forms (see the
5323  // grammar extract at the start of ParseDirectDeclarator):
5324  switch (Tok.getKind()) {
5325  case tok::l_paren:
5326  // C(X ( int));
5327  case tok::l_square:
5328  // C(X [ 5]);
5329  // C(X [ [attribute]]);
5330  case tok::coloncolon:
5331  // C(X :: Y);
5332  // C(X :: *p);
5333  // Assume this isn't a constructor, rather than assuming it's a
5334  // constructor with an unnamed parameter of an ill-formed type.
5335  break;
5336 
5337  case tok::r_paren:
5338  // C(X )
5339 
5340  // Skip past the right-paren and any following attributes to get to
5341  // the function body or trailing-return-type.
5342  ConsumeParen();
5343  SkipCXX11Attributes();
5344 
5345  if (DeductionGuide) {
5346  // C(X) -> ... is a deduction guide.
5347  IsConstructor = Tok.is(tok::arrow);
5348  break;
5349  }
5350  if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
5351  // Assume these were meant to be constructors:
5352  // C(X) : (the name of a bit-field cannot be parenthesized).
5353  // C(X) try (this is otherwise ill-formed).
5354  IsConstructor = true;
5355  }
5356  if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
5357  // If we have a constructor name within the class definition,
5358  // assume these were meant to be constructors:
5359  // C(X) {
5360  // C(X) ;
5361  // ... because otherwise we would be declaring a non-static data
5362  // member that is ill-formed because it's of the same type as its
5363  // surrounding class.
5364  //
5365  // FIXME: We can actually do this whether or not the name is qualified,
5366  // because if it is qualified in this context it must be being used as
5367  // a constructor name.
5368  // currently, so we're somewhat conservative here.
5369  IsConstructor = IsUnqualified;
5370  }
5371  break;
5372 
5373  default:
5374  IsConstructor = true;
5375  break;
5376  }
5377  }
5378 
5379  TPA.Revert();
5380  return IsConstructor;
5381 }
5382 
5383 /// ParseTypeQualifierListOpt
5384 /// type-qualifier-list: [C99 6.7.5]
5385 /// type-qualifier
5386 /// [vendor] attributes
5387 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5388 /// type-qualifier-list type-qualifier
5389 /// [vendor] type-qualifier-list attributes
5390 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5391 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
5392 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
5393 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5394 /// AttrRequirements bitmask values.
5395 void Parser::ParseTypeQualifierListOpt(
5396  DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5397  bool IdentifierRequired,
5398  Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
5399  if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
5400  isCXX11AttributeSpecifier()) {
5401  ParsedAttributesWithRange attrs(AttrFactory);
5402  ParseCXX11Attributes(attrs);
5403  DS.takeAttributesFrom(attrs);
5404  }
5405 
5406  SourceLocation EndLoc;
5407 
5408  while (1) {
5409  bool isInvalid = false;
5410  const char *PrevSpec = nullptr;
5411  unsigned DiagID = 0;
5412  SourceLocation Loc = Tok.getLocation();
5413 
5414  switch (Tok.getKind()) {
5415  case tok::code_completion:
5417  (*CodeCompletionHandler)();
5418  else
5419  Actions.CodeCompleteTypeQualifiers(DS);
5420  return cutOffParsing();
5421 
5422  case tok::kw_const:
5423  isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
5424  getLangOpts());
5425  break;
5426  case tok::kw_volatile:
5427  isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5428  getLangOpts());
5429  break;
5430  case tok::kw_restrict:
5431  isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5432  getLangOpts());
5433  break;
5434  case tok::kw__Atomic:
5435  if (!AtomicAllowed)
5436  goto DoneWithTypeQuals;
5437  if (!getLangOpts().C11)
5438  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
5439  isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5440  getLangOpts());
5441  break;
5442 
5443  // OpenCL qualifiers:
5444  case tok::kw_private:
5445  if (!getLangOpts().OpenCL)
5446  goto DoneWithTypeQuals;
5447  LLVM_FALLTHROUGH;
5448  case tok::kw___private:
5449  case tok::kw___global:
5450  case tok::kw___local:
5451  case tok::kw___constant:
5452  case tok::kw___generic:
5453  case tok::kw___read_only:
5454  case tok::kw___write_only:
5455  case tok::kw___read_write:
5456  ParseOpenCLQualifiers(DS.getAttributes());
5457  break;
5458 
5459  case tok::kw___unaligned:
5460  isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5461  getLangOpts());
5462  break;
5463  case tok::kw___uptr:
5464  // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
5465  // with the MS modifier keyword.
5466  if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
5467  IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5468  if (TryKeywordIdentFallback(false))
5469  continue;
5470  }
5471  LLVM_FALLTHROUGH;
5472  case tok::kw___sptr:
5473  case tok::kw___w64:
5474  case tok::kw___ptr64:
5475  case tok::kw___ptr32:
5476  case tok::kw___cdecl:
5477  case tok::kw___stdcall:
5478  case tok::kw___fastcall:
5479  case tok::kw___thiscall:
5480  case tok::kw___regcall:
5481  case tok::kw___vectorcall:
5482  if (AttrReqs & AR_DeclspecAttributesParsed) {
5483  ParseMicrosoftTypeAttributes(DS.getAttributes());
5484  continue;
5485  }
5486  goto DoneWithTypeQuals;
5487  case tok::kw___pascal:
5488  if (AttrReqs & AR_VendorAttributesParsed) {
5489  ParseBorlandTypeAttributes(DS.getAttributes());
5490  continue;
5491  }
5492  goto DoneWithTypeQuals;
5493 
5494  // Nullability type specifiers.
5495  case tok::kw__Nonnull:
5496  case tok::kw__Nullable:
5497  case tok::kw__Null_unspecified:
5498  ParseNullabilityTypeSpecifiers(DS.getAttributes());
5499  continue;
5500 
5501  // Objective-C 'kindof' types.
5502  case tok::kw___kindof:
5503  DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
5504  nullptr, 0, ParsedAttr::AS_Keyword);
5505  (void)ConsumeToken();
5506  continue;
5507 
5508  case tok::kw___attribute:
5509  if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5510  // When GNU attributes are expressly forbidden, diagnose their usage.
5511  Diag(Tok, diag::err_attributes_not_allowed);
5512 
5513  // Parse the attributes even if they are rejected to ensure that error
5514  // recovery is graceful.
5515  if (AttrReqs & AR_GNUAttributesParsed ||
5516  AttrReqs & AR_GNUAttributesParsedAndRejected) {
5517  ParseGNUAttributes(DS.getAttributes());
5518  continue; // do *not* consume the next token!
5519  }
5520  // otherwise, FALL THROUGH!
5521  LLVM_FALLTHROUGH;
5522  default:
5523  DoneWithTypeQuals:
5524  // If this is not a type-qualifier token, we're done reading type
5525  // qualifiers. First verify that DeclSpec's are consistent.
5526  DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
5527  if (EndLoc.isValid())
5528  DS.SetRangeEnd(EndLoc);
5529  return;
5530  }
5531 
5532  // If the specifier combination wasn't legal, issue a diagnostic.
5533  if (isInvalid) {
5534  assert(PrevSpec && "Method did not return previous specifier!");
5535  Diag(Tok, DiagID) << PrevSpec;
5536  }
5537  EndLoc = ConsumeToken();
5538  }
5539 }
5540 
5541 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
5542 ///
5543 void Parser::ParseDeclarator(Declarator &D) {
5544  /// This implements the 'declarator' production in the C grammar, then checks
5545  /// for well-formedness and issues diagnostics.
5546  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5547 }
5548 
5550  DeclaratorContext TheContext) {
5551  if (Kind == tok::star || Kind == tok::caret)
5552  return true;
5553 
5554  if (Kind == tok::kw_pipe &&
5555  ((Lang.OpenCL && Lang.OpenCLVersion >= 200) || Lang.OpenCLCPlusPlus))
5556  return true;
5557 
5558  if (!Lang.CPlusPlus)
5559  return false;
5560 
5561  if (Kind == tok::amp)
5562  return true;
5563 
5564  // We parse rvalue refs in C++03, because otherwise the errors are scary.
5565  // But we must not parse them in conversion-type-ids and new-type-ids, since
5566  // those can be legitimately followed by a && operator.
5567  // (The same thing can in theory happen after a trailing-return-type, but
5568  // since those are a C++11 feature, there is no rejects-valid issue there.)
5569  if (Kind == tok::ampamp)
5570  return Lang.CPlusPlus11 ||
5571  (TheContext != DeclaratorContext::ConversionIdContext &&
5572  TheContext != DeclaratorContext::CXXNewContext);
5573 
5574  return false;
5575 }
5576 
5577 // Indicates whether the given declarator is a pipe declarator.
5578 static bool isPipeDeclerator(const Declarator &D) {
5579  const unsigned NumTypes = D.getNumTypeObjects();
5580 
5581  for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5583  return true;
5584 
5585  return false;
5586 }
5587 
5588 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5589 /// is parsed by the function passed to it. Pass null, and the direct-declarator
5590 /// isn't parsed at all, making this function effectively parse the C++
5591 /// ptr-operator production.
5592 ///
5593 /// If the grammar of this construct is extended, matching changes must also be
5594 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5595 /// isConstructorDeclarator.
5596 ///
5597 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5598 /// [C] pointer[opt] direct-declarator
5599 /// [C++] direct-declarator
5600 /// [C++] ptr-operator declarator
5601 ///
5602 /// pointer: [C99 6.7.5]
5603 /// '*' type-qualifier-list[opt]
5604 /// '*' type-qualifier-list[opt] pointer
5605 ///
5606 /// ptr-operator:
5607 /// '*' cv-qualifier-seq[opt]
5608 /// '&'
5609 /// [C++0x] '&&'
5610 /// [GNU] '&' restrict[opt] attributes[opt]
5611 /// [GNU?] '&&' restrict[opt] attributes[opt]
5612 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
5613 void Parser::ParseDeclaratorInternal(Declarator &D,
5614  DirectDeclParseFunction DirectDeclParser) {
5615  if (Diags.hasAllExtensionsSilenced())
5616  D.setExtension();
5617 
5618  // C++ member pointers start with a '::' or a nested-name.
5619  // Member pointers get special handling, since there's no place for the
5620  // scope spec in the generic path below.
5621  if (getLangOpts().CPlusPlus &&
5622  (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
5623  (Tok.is(tok::identifier) &&
5624  (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
5625  Tok.is(tok::annot_cxxscope))) {
5626  bool EnteringContext =
5629  CXXScopeSpec SS;
5630  ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
5631 
5632  if (SS.isNotEmpty()) {
5633  if (Tok.isNot(tok::star)) {
5634  // The scope spec really belongs to the direct-declarator.
5635  if (D.mayHaveIdentifier())
5636  D.getCXXScopeSpec() = SS;
5637  else
5638  AnnotateScopeToken(SS, true);
5639 
5640  if (DirectDeclParser)
5641  (this->*DirectDeclParser)(D);
5642  return;
5643  }
5644 
5645  SourceLocation Loc = ConsumeToken();
5646  D.SetRangeEnd(Loc);
5647  DeclSpec DS(AttrFactory);
5648  ParseTypeQualifierListOpt(DS);
5649  D.ExtendWithDeclSpec(DS);
5650 
5651  // Recurse to parse whatever is left.
5652  ParseDeclaratorInternal(D, DirectDeclParser);
5653 
5654  // Sema will have to catch (syntactically invalid) pointers into global
5655  // scope. It has to catch pointers into namespace scope anyway.
5657  SS, DS.getTypeQualifiers(), DS.getEndLoc()),
5658  std::move(DS.getAttributes()),
5659  /* Don't replace range end. */ SourceLocation());
5660  return;
5661  }
5662  }
5663 
5664  tok::TokenKind Kind = Tok.getKind();
5665 
5666  if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
5667  DeclSpec DS(AttrFactory);
5668  ParseTypeQualifierListOpt(DS);
5669 
5670  D.AddTypeInfo(
5672  std::move(DS.getAttributes()), SourceLocation());
5673  }
5674 
5675  // Not a pointer, C++ reference, or block.
5676  if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
5677  if (DirectDeclParser)
5678  (this->*DirectDeclParser)(D);
5679  return;
5680  }
5681 
5682  // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5683  // '&&' -> rvalue reference
5684  SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
5685  D.SetRangeEnd(Loc);
5686 
5687  if (Kind == tok::star || Kind == tok::caret) {
5688  // Is a pointer.
5689  DeclSpec DS(AttrFactory);
5690 
5691  // GNU attributes are not allowed here in a new-type-id, but Declspec and
5692  // C++11 attributes are allowed.
5693  unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
5695  ? AR_GNUAttributesParsed
5696  : AR_GNUAttributesParsedAndRejected);
5697  ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
5698  D.ExtendWithDeclSpec(DS);
5699 
5700  // Recursively parse the declarator.
5701  ParseDeclaratorInternal(D, DirectDeclParser);
5702  if (Kind == tok::star)
5703  // Remember that we parsed a pointer type, and remember the type-quals.
5705  DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5708  std::move(DS.getAttributes()), SourceLocation());
5709  else
5710  // Remember that we parsed a Block type, and remember the type-quals.
5711  D.AddTypeInfo(
5713  std::move(DS.getAttributes()), SourceLocation());
5714  } else {
5715  // Is a reference
5716  DeclSpec DS(AttrFactory);
5717 
5718  // Complain about rvalue references in C++03, but then go on and build
5719  // the declarator.
5720  if (Kind == tok::ampamp)
5721  Diag(Loc, getLangOpts().CPlusPlus11 ?
5722  diag::warn_cxx98_compat_rvalue_reference :
5723  diag::ext_rvalue_reference);
5724 
5725  // GNU-style and C++11 attributes are allowed here, as is restrict.
5726  ParseTypeQualifierListOpt(DS);
5727  D.ExtendWithDeclSpec(DS);
5728 
5729  // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5730  // cv-qualifiers are introduced through the use of a typedef or of a
5731  // template type argument, in which case the cv-qualifiers are ignored.
5734  Diag(DS.getConstSpecLoc(),
5735  diag::err_invalid_reference_qualifier_application) << "const";
5737  Diag(DS.getVolatileSpecLoc(),
5738  diag::err_invalid_reference_qualifier_application) << "volatile";
5739  // 'restrict' is permitted as an extension.
5741  Diag(DS.getAtomicSpecLoc(),
5742  diag::err_invalid_reference_qualifier_application) << "_Atomic";
5743  }
5744 
5745  // Recursively parse the declarator.
5746  ParseDeclaratorInternal(D, DirectDeclParser);
5747 
5748  if (D.getNumTypeObjects() > 0) {
5749  // C++ [dcl.ref]p4: There shall be no references to references.
5750  DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5751  if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5752  if (const IdentifierInfo *II = D.getIdentifier())
5753  Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5754  << II;
5755  else
5756  Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5757  << "type name";
5758 
5759  // Once we've complained about the reference-to-reference, we
5760  // can go ahead and build the (technically ill-formed)
5761  // declarator: reference collapsing will take care of it.
5762  }
5763  }
5764 
5765  // Remember that we parsed a reference type.
5767  Kind == tok::amp),
5768  std::move(DS.getAttributes()), SourceLocation());
5769  }
5770 }
5771 
5772 // When correcting from misplaced brackets before the identifier, the location
5773 // is saved inside the declarator so that other diagnostic messages can use
5774 // them. This extracts and returns that location, or returns the provided
5775 // location if a stored location does not exist.
5777  SourceLocation Loc) {
5778  if (D.getName().StartLocation.isInvalid() &&
5779  D.getName().EndLocation.isValid())
5780  return D.getName().EndLocation;
5781 
5782  return Loc;
5783 }
5784 
5785 /// ParseDirectDeclarator
5786 /// direct-declarator: [C99 6.7.5]
5787 /// [C99] identifier
5788 /// '(' declarator ')'
5789 /// [GNU] '(' attributes declarator ')'
5790 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5791 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5792 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5793 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5794 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5795 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5796 /// attribute-specifier-seq[opt]
5797 /// direct-declarator '(' parameter-type-list ')'
5798 /// direct-declarator '(' identifier-list[opt] ')'
5799 /// [GNU] direct-declarator '(' parameter-forward-declarations
5800 /// parameter-type-list[opt] ')'
5801 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
5802 /// cv-qualifier-seq[opt] exception-specification[opt]
5803 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5804 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5805 /// ref-qualifier[opt] exception-specification[opt]
5806 /// [C++] declarator-id
5807 /// [C++11] declarator-id attribute-specifier-seq[opt]
5808 ///
5809 /// declarator-id: [C++ 8]
5810 /// '...'[opt] id-expression
5811 /// '::'[opt] nested-name-specifier[opt] type-name
5812 ///
5813 /// id-expression: [C++ 5.1]
5814 /// unqualified-id
5815 /// qualified-id
5816 ///
5817 /// unqualified-id: [C++ 5.1]
5818 /// identifier
5819 /// operator-function-id
5820 /// conversion-function-id
5821 /// '~' class-name
5822 /// template-id
5823 ///
5824 /// C++17 adds the following, which we also handle here:
5825 ///
5826 /// simple-declaration:
5827 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5828 ///
5829 /// Note, any additional constructs added here may need corresponding changes
5830 /// in isConstructorDeclarator.
5831 void Parser::ParseDirectDeclarator(Declarator &D) {
5832  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
5833 
5834  if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
5835  // This might be a C++17 structured binding.
5836  if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5837  D.getCXXScopeSpec().isEmpty())
5838  return ParseDecompositionDeclarator(D);
5839 
5840  // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5841  // this context it is a bitfield. Also in range-based for statement colon
5842  // may delimit for-range-declaration.
5846  getLangOpts().CPlusPlus11));
5847 
5848  // ParseDeclaratorInternal might already have parsed the scope.
5849  if (D.getCXXScopeSpec().isEmpty()) {
5850  bool EnteringContext =
5853  ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
5854  EnteringContext);
5855  }
5856 
5857  if (D.getCXXScopeSpec().isValid()) {
5858  if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5859  D.getCXXScopeSpec()))
5860  // Change the declaration context for name lookup, until this function
5861  // is exited (and the declarator has been parsed).
5862  DeclScopeObj.EnterDeclaratorScope();
5863  else if (getObjCDeclContext()) {
5864  // Ensure that we don't interpret the next token as an identifier when
5865  // dealing with declarations in an Objective-C container.
5866  D.SetIdentifier(nullptr, Tok.getLocation());
5867  D.setInvalidType(true);
5868  ConsumeToken();
5869  goto PastIdentifier;
5870  }
5871  }
5872 
5873  // C++0x [dcl.fct]p14:
5874  // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5875  // parameter-declaration-clause without a preceding comma. In this case,
5876  // the ellipsis is parsed as part of the abstract-declarator if the type
5877  // of the parameter either names a template parameter pack that has not
5878  // been expanded or contains auto; otherwise, it is parsed as part of the
5879  // parameter-declaration-clause.
5880  if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
5884  NextToken().is(tok::r_paren) &&
5885  !D.hasGroupingParens() &&
5886  !Actions.containsUnexpandedParameterPacks(D) &&
5887  D.getDeclSpec().getTypeSpecType() != TST_auto)) {
5888  SourceLocation EllipsisLoc = ConsumeToken();
5889  if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
5890  // The ellipsis was put in the wrong place. Recover, and explain to
5891  // the user what they should have done.
5892  ParseDeclarator(D);
5893  if (EllipsisLoc.isValid())
5894  DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5895  return;
5896  } else
5897  D.setEllipsisLoc(EllipsisLoc);
5898 
5899  // The ellipsis can't be followed by a parenthesized declarator. We
5900  // check for that in ParseParenDeclarator, after we have disambiguated
5901  // the l_paren token.
5902  }
5903 
5904  if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5905  tok::tilde)) {
5906  // We found something that indicates the start of an unqualified-id.
5907  // Parse that unqualified-id.
5908  bool AllowConstructorName;
5909  bool AllowDeductionGuide;
5910  if (D.getDeclSpec().hasTypeSpecifier()) {
5911  AllowConstructorName = false;
5912  AllowDeductionGuide = false;
5913  } else if (D.getCXXScopeSpec().isSet()) {
5914  AllowConstructorName =
5917  AllowDeductionGuide = false;
5918  } else {
5919  AllowConstructorName =
5921  AllowDeductionGuide =
5924  }
5925 
5926  bool HadScope = D.getCXXScopeSpec().isValid();
5928  /*EnteringContext=*/true,
5929  /*AllowDestructorName=*/true, AllowConstructorName,
5930  AllowDeductionGuide, nullptr, nullptr,
5931  D.getName()) ||
5932  // Once we're past the identifier, if the scope was bad, mark the
5933  // whole declarator bad.
5934  D.getCXXScopeSpec().isInvalid()) {
5935  D.SetIdentifier(nullptr, Tok.getLocation());
5936  D.setInvalidType(true);
5937  } else {
5938  // ParseUnqualifiedId might have parsed a scope specifier during error
5939  // recovery. If it did so, enter that scope.
5940  if (!HadScope && D.getCXXScopeSpec().isValid() &&
5941  Actions.ShouldEnterDeclaratorScope(getCurScope(),
5942  D.getCXXScopeSpec()))
5943  DeclScopeObj.EnterDeclaratorScope();
5944 
5945  // Parsed the unqualified-id; update range information and move along.
5946  if (D.getSourceRange().getBegin().isInvalid())
5949  }
5950  goto PastIdentifier;
5951  }
5952 
5953  if (D.getCXXScopeSpec().isNotEmpty()) {
5954  // We have a scope specifier but no following unqualified-id.
5955  Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5956  diag::err_expected_unqualified_id)
5957  << /*C++*/1;
5958  D.SetIdentifier(nullptr, Tok.getLocation());
5959  goto PastIdentifier;
5960  }
5961  } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
5962  assert(!getLangOpts().CPlusPlus &&
5963  "There's a C++-specific check for tok::identifier above");
5964  assert(Tok.getIdentifierInfo() && "Not an identifier?");
5966  D.SetRangeEnd(Tok.getLocation());
5967  ConsumeToken();
5968  goto PastIdentifier;
5969  } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5970  // We're not allowed an identifier here, but we got one. Try to figure out
5971  // if the user was trying to attach a name to the type, or whether the name
5972  // is some unrelated trailing syntax.
5973  bool DiagnoseIdentifier = false;
5974  if (D.hasGroupingParens())
5975  // An identifier within parens is unlikely to be intended to be anything
5976  // other than a name being "declared".
5977  DiagnoseIdentifier = true;
5979  // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5980  DiagnoseIdentifier =
5981  NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
5984  // The most likely error is that the ';' was forgotten.
5985  DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
5988  !isCXX11VirtSpecifier(Tok))
5989  DiagnoseIdentifier = NextToken().isOneOf(
5990  tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5991  if (DiagnoseIdentifier) {
5992  Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5994  D.SetIdentifier(nullptr, Tok.getLocation());
5995  ConsumeToken();
5996  goto PastIdentifier;
5997  }
5998  }
5999 
6000  if (Tok.is(tok::l_paren)) {
6001  // If this might be an abstract-declarator followed by a direct-initializer,
6002  // check whether this is a valid declarator chunk. If it can't be, assume
6003  // that it's an initializer instead.
6005  RevertingTentativeParsingAction PA(*this);
6006  if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
6007  TPResult::False) {
6008  D.SetIdentifier(nullptr, Tok.getLocation());
6009  goto PastIdentifier;
6010  }
6011  }
6012 
6013  // direct-declarator: '(' declarator ')'
6014  // direct-declarator: '(' attributes declarator ')'
6015  // Example: 'char (*X)' or 'int (*XX)(void)'
6016  ParseParenDeclarator(D);
6017 
6018  // If the declarator was parenthesized, we entered the declarator
6019  // scope when parsing the parenthesized declarator, then exited
6020  // the scope already. Re-enter the scope, if we need to.
6021  if (D.getCXXScopeSpec().isSet()) {
6022  // If there was an error parsing parenthesized declarator, declarator
6023  // scope may have been entered before. Don't do it again.
6024  if (!D.isInvalidType() &&
6025  Actions.ShouldEnterDeclaratorScope(getCurScope(),
6026  D.getCXXScopeSpec()))
6027  // Change the declaration context for name lookup, until this function
6028  // is exited (and the declarator has been parsed).
6029  DeclScopeObj.EnterDeclaratorScope();
6030  }
6031  } else if (D.mayOmitIdentifier()) {
6032  // This could be something simple like "int" (in which case the declarator
6033  // portion is empty), if an abstract-declarator is allowed.
6034  D.SetIdentifier(nullptr, Tok.getLocation());
6035 
6036  // The grammar for abstract-pack-declarator does not allow grouping parens.
6037  // FIXME: Revisit this once core issue 1488 is resolved.
6038  if (D.hasEllipsis() && D.hasGroupingParens())
6039  Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
6040  diag::ext_abstract_pack_declarator_parens);
6041  } else {
6042  if (Tok.getKind() == tok::annot_pragma_parser_crash)
6043  LLVM_BUILTIN_TRAP;
6044  if (Tok.is(tok::l_square))
6045  return ParseMisplacedBracketDeclarator(D);
6047  // Objective-C++: Detect C++ keywords and try to prevent further errors by
6048  // treating these keyword as valid member names.
6049  if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
6050  Tok.getIdentifierInfo() &&
6053  diag::err_expected_member_name_or_semi_objcxx_keyword)
6054  << Tok.getIdentifierInfo()
6055  << (D.getDeclSpec().isEmpty() ? SourceRange()
6056  : D.getDeclSpec().getSourceRange());
6058  D.SetRangeEnd(Tok.getLocation());
6059  ConsumeToken();
6060  goto PastIdentifier;
6061  }
6063  diag::err_expected_member_name_or_semi)
6064  << (D.getDeclSpec().isEmpty() ? SourceRange()
6065  : D.getDeclSpec().getSourceRange());
6066  } else if (getLangOpts().CPlusPlus) {
6067  if (Tok.isOneOf(tok::period, tok::arrow))
6068  Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
6069  else {
6071  if (Tok.isAtStartOfLine() && Loc.isValid())
6072  Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
6073  << getLangOpts().CPlusPlus;
6074  else
6076  diag::err_expected_unqualified_id)
6077  << getLangOpts().CPlusPlus;
6078  }
6079  } else {
6081  diag::err_expected_either)
6082  << tok::identifier << tok::l_paren;
6083  }
6084  D.SetIdentifier(nullptr, Tok.getLocation());
6085  D.setInvalidType(true);
6086  }
6087 
6088  PastIdentifier:
6089  assert(D.isPastIdentifier() &&
6090  "Haven't past the location of the identifier yet?");
6091 
6092  // Don't parse attributes unless we have parsed an unparenthesized name.
6093  if (D.hasName() && !D.getNumTypeObjects())
6094  MaybeParseCXX11Attributes(D);
6095 
6096  while (1) {
6097  if (Tok.is(tok::l_paren)) {
6098  bool IsFunctionDeclaration = D.isFunctionDeclaratorAFunctionDeclaration();
6099  // Enter function-declaration scope, limiting any declarators to the
6100  // function prototype scope, including parameter declarators.
6101  ParseScope PrototypeScope(this,
6103  (IsFunctionDeclaration
6105 
6106  // The paren may be part of a C++ direct initializer, eg. "int x(1);".
6107  // In such a case, check if we actually have a function declarator; if it
6108  // is not, the declarator has been fully parsed.
6109  bool IsAmbiguous = false;
6111  // The name of the declarator, if any, is tentatively declared within
6112  // a possible direct initializer.
6113  TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
6114  bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
6115  TentativelyDeclaredIdentifiers.pop_back();
6116  if (!IsFunctionDecl)
6117  break;
6118  }
6119  ParsedAttributes attrs(AttrFactory);
6120  BalancedDelimiterTracker T(*this, tok::l_paren);
6121  T.consumeOpen();
6122  if (IsFunctionDeclaration)
6123  Actions.ActOnStartFunctionDeclarationDeclarator(D,
6124  TemplateParameterDepth);
6125  ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
6126  if (IsFunctionDeclaration)
6127  Actions.ActOnFinishFunctionDeclarationDeclarator(D);
6128  PrototypeScope.Exit();
6129  } else if (Tok.is(tok::l_square)) {
6130  ParseBracketDeclarator(D);
6131  } else if (Tok.is(tok::kw_requires) && D.hasGroupingParens()) {
6132  // This declarator is declaring a function, but the requires clause is
6133  // in the wrong place:
6134  // void (f() requires true);
6135  // instead of
6136  // void f() requires true;
6137  // or
6138  // void (f()) requires true;
6139  Diag(Tok, diag::err_requires_clause_inside_parens);
6140  ConsumeToken();
6141  ExprResult TrailingRequiresClause = Actions.CorrectDelayedTyposInExpr(
6142  ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
6143  if (TrailingRequiresClause.isUsable() && D.isFunctionDeclarator() &&
6145  // We're already ill-formed if we got here but we'll accept it anyway.
6146  D.setTrailingRequiresClause(TrailingRequiresClause.get());
6147  } else {
6148  break;
6149  }
6150  }
6151 }
6152 
6153 void Parser::ParseDecompositionDeclarator(Declarator &D) {
6154  assert(Tok.is(tok::l_square));
6155 
6156  // If this doesn't look like a structured binding, maybe it's a misplaced
6157  // array declarator.
6158  // FIXME: Consume the l_square first so we don't need extra lookahead for
6159  // this.
6160  if (!(NextToken().is(tok::identifier) &&
6161  GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
6162  !(NextToken().is(tok::r_square) &&
6163  GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
6164  return ParseMisplacedBracketDeclarator(D);
6165 
6166  BalancedDelimiterTracker T(*this, tok::l_square);
6167  T.consumeOpen();
6168 
6170  while (Tok.isNot(tok::r_square)) {
6171  if (!Bindings.empty()) {
6172  if (Tok.is(tok::comma))
6173  ConsumeToken();
6174  else {
6175  if (Tok.is(tok::identifier)) {
6177  Diag(EndLoc, diag::err_expected)
6178  << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
6179  } else {
6180  Diag(Tok, diag::err_expected_comma_or_rsquare);
6181  }
6182 
6183  SkipUntil(tok::r_square, tok::comma, tok::identifier,
6185  if (Tok.is(tok::comma))
6186  ConsumeToken();
6187  else if (Tok.isNot(tok::identifier))
6188  break;
6189  }
6190  }
6191 
6192  if (Tok.isNot(tok::identifier)) {
6193  Diag(Tok, diag::err_expected) << tok::identifier;
6194  break;
6195  }
6196 
6197  Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
6198  ConsumeToken();
6199  }
6200 
6201  if (Tok.isNot(tok::r_square))
6202  // We've already diagnosed a problem here.
6203  T.skipToEnd();
6204  else {
6205  // C++17 does not allow the identifier-list in a structured binding
6206  // to be empty.
6207  if (Bindings.empty())
6208  Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
6209 
6210  T.consumeClose();
6211  }
6212 
6213  return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
6214  T.getCloseLocation());
6215 }
6216 
6217 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
6218 /// only called before the identifier, so these are most likely just grouping
6219 /// parens for precedence. If we find that these are actually function
6220 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
6221 ///
6222 /// direct-declarator:
6223 /// '(' declarator ')'
6224 /// [GNU] '(' attributes declarator ')'
6225 /// direct-declarator '(' parameter-type-list ')'
6226 /// direct-declarator '(' identifier-list[opt] ')'
6227 /// [GNU] direct-declarator '(' parameter-forward-declarations
6228 /// parameter-type-list[opt] ')'
6229 ///
6230 void Parser::ParseParenDeclarator(Declarator &D) {
6231  BalancedDelimiterTracker T(*this, tok::l_paren);
6232  T.consumeOpen();
6233 
6234  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
6235 
6236  // Eat any attributes before we look at whether this is a grouping or function
6237  // declarator paren. If this is a grouping paren, the attribute applies to
6238  // the type being built up, for example:
6239  // int (__attribute__(()) *x)(long y)
6240  // If this ends up not being a grouping paren, the attribute applies to the
6241  // first argument, for example:
6242  // int (__attribute__(()) int x)
6243  // In either case, we need to eat any attributes to be able to determine what
6244  // sort of paren this is.
6245  //
6246  ParsedAttributes attrs(AttrFactory);
6247  bool RequiresArg = false;
6248  if (Tok.is(tok::kw___attribute)) {
6249  ParseGNUAttributes(attrs);
6250 
6251  // We require that the argument list (if this is a non-grouping paren) be
6252  // present even if the attribute list was empty.
6253  RequiresArg = true;
6254  }
6255 
6256  // Eat any Microsoft extensions.
6257  ParseMicrosoftTypeAttributes(attrs);
6258 
6259  // Eat any Borland extensions.
6260  if (Tok.is(tok::kw___pascal))
6261  ParseBorlandTypeAttributes(attrs);
6262 
6263  // If we haven't past the identifier yet (or where the identifier would be
6264  // stored, if this is an abstract declarator), then this is probably just
6265  // grouping parens. However, if this could be an abstract-declarator, then
6266  // this could also be the start of function arguments (consider 'void()').
6267  bool isGrouping;
6268 
6269  if (!D.mayOmitIdentifier()) {
6270  // If this can't be an abstract-declarator, this *must* be a grouping
6271  // paren, because we haven't seen the identifier yet.
6272  isGrouping = true;
6273  } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
6274  (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
6275  NextToken().is(tok::r_paren)) || // C++ int(...)
6276  isDeclarationSpecifier() || // 'int(int)' is a function.
6277  isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
6278  // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
6279  // considered to be a type, not a K&R identifier-list.
6280  isGrouping = false;
6281  } else {
6282  // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6283  isGrouping = true;
6284  }
6285 
6286  // If this is a grouping paren, handle:
6287  // direct-declarator: '(' declarator ')'
6288  // direct-declarator: '(' attributes declarator ')'
6289  if (isGrouping) {
6290  SourceLocation EllipsisLoc = D.getEllipsisLoc();
6292 
6293  bool hadGroupingParens = D.hasGroupingParens();
6294  D.setGroupingParens(true);
6295  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6296  // Match the ')'.
6297  T.consumeClose();
6298  D.AddTypeInfo(
6300  std::move(attrs), T.getCloseLocation());
6301 
6302  D.setGroupingParens(hadGroupingParens);
6303 
6304  // An ellipsis cannot be placed outside parentheses.
6305  if (EllipsisLoc.isValid())
6306  DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6307 
6308  return;
6309  }
6310 
6311  // Okay, if this wasn't a grouping paren, it must be the start of a function
6312  // argument list. Recognize that this declarator will never have an
6313  // identifier (and remember where it would have been), then call into
6314  // ParseFunctionDeclarator to handle of argument list.
6315  D.SetIdentifier(nullptr, Tok.getLocation());
6316 
6317  // Enter function-declaration scope, limiting any declarators to the
6318  // function prototype scope, including parameter declarators.
6319  ParseScope PrototypeScope(this,
6323  ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
6324  PrototypeScope.Exit();
6325 }
6326 
6327 void Parser::InitCXXThisScopeForDeclaratorIfRelevant(
6328  const Declarator &D, const DeclSpec &DS,
6330  // C++11 [expr.prim.general]p3:
6331  // If a declaration declares a member function or member function
6332  // template of a class X, the expression this is a prvalue of type
6333  // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6334  // and the end of the function-definition, member-declarator, or
6335  // declarator.
6336  // FIXME: currently, "static" case isn't handled correctly.
6337  bool IsCXX11MemberFunction = getLangOpts().CPlusPlus11 &&
6342  D.getCXXScopeSpec().isValid() &&
6343  Actions.CurContext->isRecord());
6344  if (!IsCXX11MemberFunction)
6345  return;
6346 
6348  if (D.getDeclSpec().hasConstexprSpecifier() && !getLangOpts().CPlusPlus14)
6349  Q.addConst();
6350  // FIXME: Collect C++ address spaces.
6351  // If there are multiple different address spaces, the source is invalid.
6352  // Carry on using the first addr space for the qualifiers of 'this'.
6353  // The diagnostic will be given later while creating the function
6354  // prototype for the method.
6355  if (getLangOpts().OpenCLCPlusPlus) {
6356  for (ParsedAttr &attr : DS.getAttributes()) {
6357  LangAS ASIdx = attr.asOpenCLLangAS();
6358  if (ASIdx != LangAS::Default) {
6359  Q.addAddressSpace(ASIdx);
6360  break;
6361  }
6362  }
6363  }
6364  ThisScope.emplace(Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
6365  IsCXX11MemberFunction);
6366 }
6367 
6368 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
6369 /// declarator D up to a paren, which indicates that we are parsing function
6370 /// arguments.
6371 ///
6372 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
6373 /// immediately after the open paren - they should be considered to be the
6374 /// first argument of a parameter.
6375 ///
6376 /// If RequiresArg is true, then the first argument of the function is required
6377 /// to be present and required to not be an identifier list.
6378 ///
6379 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6380 /// (C++11) ref-qualifier[opt], exception-specification[opt],
6381 /// (C++11) attribute-specifier-seq[opt], (C++11) trailing-return-type[opt] and
6382 /// (C++2a) the trailing requires-clause.
6383 ///
6384 /// [C++11] exception-specification:
6385 /// dynamic-exception-specification
6386 /// noexcept-specification
6387 ///
6388 void Parser::ParseFunctionDeclarator(Declarator &D,
6389  ParsedAttributes &FirstArgAttrs,
6390  BalancedDelimiterTracker &Tracker,
6391  bool IsAmbiguous,
6392  bool RequiresArg) {
6393  assert(getCurScope()->isFunctionPrototypeScope() &&
6394  "Should call from a Function scope");
6395  // lparen is already consumed!
6396  assert(D.isPastIdentifier() && "Should not call before identifier!");
6397 
6398  // This should be true when the function has typed arguments.
6399  // Otherwise, it is treated as a K&R-style function.
6400  bool HasProto = false;
6401  // Build up an array of information about the parsed arguments.
6403  // Remember where we see an ellipsis, if any.
6404  SourceLocation EllipsisLoc;
6405 
6406  DeclSpec DS(AttrFactory);
6407  bool RefQualifierIsLValueRef = true;
6408  SourceLocation RefQualifierLoc;
6410  SourceRange ESpecRange;
6411  SmallVector<ParsedType, 2> DynamicExceptions;
6412  SmallVector<SourceRange, 2> DynamicExceptionRanges;
6413  ExprResult NoexceptExpr;
6414  CachedTokens *ExceptionSpecTokens = nullptr;
6415  ParsedAttributesWithRange FnAttrs(AttrFactory);
6416  TypeResult TrailingReturnType;
6417 
6418  /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6419  EndLoc is the end location for the function declarator.
6420  They differ for trailing return types. */
6421  SourceLocation StartLoc, LocalEndLoc, EndLoc;
6422  SourceLocation LParenLoc, RParenLoc;
6423  LParenLoc = Tracker.getOpenLocation();
6424  StartLoc = LParenLoc;
6425 
6426  if (isFunctionDeclaratorIdentifierList()) {
6427  if (RequiresArg)
6428  Diag(Tok, diag::err_argument_required_after_attribute);
6429 
6430  ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6431 
6432  Tracker.consumeClose();
6433  RParenLoc = Tracker.getCloseLocation();
6434  LocalEndLoc = RParenLoc;
6435  EndLoc = RParenLoc;
6436 
6437  // If there are attributes following the identifier list, parse them and
6438  // prohibit them.
6439  MaybeParseCXX11Attributes(FnAttrs);
6440  ProhibitAttributes(FnAttrs);
6441  } else {
6442  if (Tok.isNot(tok::r_paren))
6443  ParseParameterDeclarationClause(D.getContext(), FirstArgAttrs, ParamInfo,
6444  EllipsisLoc);
6445  else if (RequiresArg)
6446  Diag(Tok, diag::err_argument_required_after_attribute);
6447 
6448  HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6449  || getLangOpts().OpenCL;
6450 
6451  // If we have the closing ')', eat it.
6452  Tracker.consumeClose();
6453  RParenLoc = Tracker.getCloseLocation();
6454  LocalEndLoc = RParenLoc;
6455  EndLoc = RParenLoc;
6456 
6457  if (getLangOpts().CPlusPlus) {
6458  // FIXME: Accept these components in any order, and produce fixits to
6459  // correct the order if the user gets it wrong. Ideally we should deal
6460  // with the pure-specifier in the same way.
6461 
6462  // Parse cv-qualifier-seq[opt].
6463  ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
6464  /*AtomicAllowed*/ false,
6465  /*IdentifierRequired=*/false,
6466  llvm::function_ref<void()>([&]() {
6467  Actions.CodeCompleteFunctionQualifiers(DS, D);
6468  }));
6469  if (!DS.getSourceRange().getEnd().isInvalid()) {
6470  EndLoc = DS.getSourceRange().getEnd();
6471  }
6472 
6473  // Parse ref-qualifier[opt].
6474  if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
6475  EndLoc = RefQualifierLoc;
6476 
6478  InitCXXThisScopeForDeclaratorIfRelevant(D, DS, ThisScope);
6479 
6480  // Parse exception-specification[opt].
6481  bool Delayed = D.isFirstDeclarationOfMember() &&
6483  if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6484  GetLookAheadToken(0).is(tok::kw_noexcept) &&
6485  GetLookAheadToken(1).is(tok::l_paren) &&
6486  GetLookAheadToken(2).is(tok::kw_noexcept) &&
6487  GetLookAheadToken(3).is(tok::l_paren) &&
6488  GetLookAheadToken(4).is(tok::identifier) &&
6489  GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6490  // HACK: We've got an exception-specification
6491  // noexcept(noexcept(swap(...)))
6492  // or
6493  // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6494  // on a 'swap' member function. This is a libstdc++ bug; the lookup
6495  // for 'swap' will only find the function we're currently declaring,
6496  // whereas it expects to find a non-member swap through ADL. Turn off
6497  // delayed parsing to give it a chance to find what it expects.
6498  Delayed = false;
6499  }
6500  ESpecType = tryParseExceptionSpecification(Delayed,
6501  ESpecRange,
6502  DynamicExceptions,
6503  DynamicExceptionRanges,
6504  NoexceptExpr,
6505  ExceptionSpecTokens);
6506  if (ESpecType != EST_None)
6507  EndLoc = ESpecRange.getEnd();
6508 
6509  // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6510  // after the exception-specification.
6511  MaybeParseCXX11Attributes(FnAttrs);
6512 
6513  // Parse trailing-return-type[opt].
6514  LocalEndLoc = EndLoc;
6515  if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
6516  Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
6517  if (D.getDeclSpec().getTypeSpecType() == TST_auto)
6518  StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
6519  LocalEndLoc = Tok.getLocation();
6520  SourceRange Range;
6521  TrailingReturnType =
6522  ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
6523  EndLoc = Range.getEnd();
6524  }
6525  } else if (standardAttributesAllowed()) {
6526  MaybeParseCXX11Attributes(FnAttrs);
6527  }
6528  }
6529 
6530  // Collect non-parameter declarations from the prototype if this is a function
6531  // declaration. They will be moved into the scope of the function. Only do
6532  // this in C and not C++, where the decls will continue to live in the
6533  // surrounding context.
6534  SmallVector<NamedDecl *, 0> DeclsInPrototype;
6535  if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6536  !getLangOpts().CPlusPlus) {
6537  for (Decl *D : getCurScope()->decls()) {
6538  NamedDecl *ND = dyn_cast<NamedDecl>(D);
6539  if (!ND || isa<ParmVarDecl>(ND))
6540  continue;
6541  DeclsInPrototype.push_back(ND);
6542  }
6543  }
6544 
6545  // Remember that we parsed a function type, and remember the attributes.
6547  HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6548  ParamInfo.size(), EllipsisLoc, RParenLoc,
6549  RefQualifierIsLValueRef, RefQualifierLoc,
6550  /*MutableLoc=*/SourceLocation(),
6551  ESpecType, ESpecRange, DynamicExceptions.data(),
6552  DynamicExceptionRanges.data(), DynamicExceptions.size(),
6553  NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6554  ExceptionSpecTokens, DeclsInPrototype, StartLoc,
6555  LocalEndLoc, D, TrailingReturnType, &DS),
6556  std::move(FnAttrs), EndLoc);
6557 }
6558 
6559 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6560 /// true if a ref-qualifier is found.
6561 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6562  SourceLocation &RefQualifierLoc) {
6563  if (Tok.isOneOf(tok::amp, tok::ampamp)) {
6564  Diag(Tok, getLangOpts().CPlusPlus11 ?
6565  diag::warn_cxx98_compat_ref_qualifier :
6566  diag::ext_ref_qualifier);
6567 
6568  RefQualifierIsLValueRef = Tok.is(tok::amp);
6569  RefQualifierLoc = ConsumeToken();
6570  return true;
6571  }
6572  return false;
6573 }
6574 
6575 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
6576 /// identifier list form for a K&R-style function: void foo(a,b,c)
6577 ///
6578 /// Note that identifier-lists are only allowed for normal declarators, not for
6579 /// abstract-declarators.
6580 bool Parser::isFunctionDeclaratorIdentifierList() {
6581  return !getLangOpts().CPlusPlus
6582  && Tok.is(tok::identifier)
6583  && !TryAltiVecVectorToken()
6584  // K&R identifier lists can't have typedefs as identifiers, per C99
6585  // 6.7.5.3p11.
6586  && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6587  // Identifier lists follow a really simple grammar: the identifiers can
6588  // be followed *only* by a ", identifier" or ")". However, K&R
6589  // identifier lists are really rare in the brave new modern world, and
6590  // it is very common for someone to typo a type in a non-K&R style
6591  // list. If we are presented with something like: "void foo(intptr x,
6592  // float y)", we don't want to start parsing the function declarator as
6593  // though it is a K&R style declarator just because intptr is an
6594  // invalid type.
6595  //
6596  // To handle this, we check to see if the token after the first
6597  // identifier is a "," or ")". Only then do we parse it as an
6598  // identifier list.
6599  && (!Tok.is(tok::eof) &&
6600  (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
6601 }
6602 
6603 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6604 /// we found a K&R-style identifier list instead of a typed parameter list.
6605 ///
6606 /// After returning, ParamInfo will hold the parsed parameters.
6607 ///
6608 /// identifier-list: [C99 6.7.5]
6609 /// identifier
6610 /// identifier-list ',' identifier
6611 ///
6612 void Parser::ParseFunctionDeclaratorIdentifierList(
6613  Declarator &D,
6615  // If there was no identifier specified for the declarator, either we are in
6616  // an abstract-declarator, or we are in a parameter declarator which was found
6617  // to be abstract. In abstract-declarators, identifier lists are not valid:
6618  // diagnose this.
6619  if (!D.getIdentifier())
6620  Diag(Tok, diag::ext_ident_list_in_param);
6621 
6622  // Maintain an efficient lookup of params we have seen so far.
6623  llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6624 
6625  do {
6626  // If this isn't an identifier, report the error and skip until ')'.
6627  if (Tok.isNot(tok::identifier)) {
6628  Diag(Tok, diag::err_expected) << tok::identifier;
6629  SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
6630  // Forget we parsed anything.
6631  ParamInfo.clear();
6632  return;
6633  }
6634 
6635  IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6636 
6637  // Reject 'typedef int y; int test(x, y)', but continue parsing.
6638  if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6639  Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6640 
6641  // Verify that the argument identifier has not already been mentioned.
6642  if (!ParamsSoFar.insert(ParmII).second) {
6643  Diag(Tok, diag::err_param_redefinition) << ParmII;
6644  } else {
6645  // Remember this identifier in ParamInfo.
6646  ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6647  Tok.getLocation(),
6648  nullptr));
6649  }
6650 
6651  // Eat the identifier.
6652  ConsumeToken();
6653  // The list continues if we see a comma.
6654  } while (TryConsumeToken(tok::comma));
6655 }
6656 
6657 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6658 /// after the opening parenthesis. This function will not parse a K&R-style
6659 /// identifier list.
6660 ///
6661 /// DeclContext is the context of the declarator being parsed. If FirstArgAttrs
6662 /// is non-null, then the caller parsed those attributes immediately after the
6663 /// open paren - they should be considered to be part of the first parameter.
6664 ///
6665 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6666 /// be the location of the ellipsis, if any was parsed.
6667 ///
6668 /// parameter-type-list: [C99 6.7.5]
6669 /// parameter-list
6670 /// parameter-list ',' '...'
6671 /// [C++] parameter-list '...'
6672 ///
6673 /// parameter-list: [C99 6.7.5]
6674 /// parameter-declaration
6675 /// parameter-list ',' parameter-declaration
6676 ///
6677 /// parameter-declaration: [C99 6.7.5]
6678 /// declaration-specifiers declarator
6679 /// [C++] declaration-specifiers declarator '=' assignment-expression
6680 /// [C++11] initializer-clause
6681 /// [GNU] declaration-specifiers declarator attributes
6682 /// declaration-specifiers abstract-declarator[opt]
6683 /// [C++] declaration-specifiers abstract-declarator[opt]
6684 /// '=' assignment-expression
6685 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
6686 /// [C++11] attribute-specifier-seq parameter-declaration
6687 ///
6688 void Parser::ParseParameterDeclarationClause(
6689  DeclaratorContext DeclaratorCtx,
6690  ParsedAttributes &FirstArgAttrs,
6692  SourceLocation &EllipsisLoc) {
6693 
6694  // Avoid exceeding the maximum function scope depth.
6695  // See https://bugs.llvm.org/show_bug.cgi?id=19607
6696  // Note Sema::ActOnParamDeclarator calls ParmVarDecl::setScopeInfo with
6697  // getFunctionPrototypeDepth() - 1.
6698  if (getCurScope()->getFunctionPrototypeDepth() - 1 >
6700  Diag(Tok.getLocation(), diag::err_function_scope_depth_exceeded)
6702  cutOffParsing();
6703  return;
6704  }
6705 
6706  do {
6707  // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6708  // before deciding this was a parameter-declaration-clause.
6709  if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
6710  break;
6711 
6712  // Parse the declaration-specifiers.
6713  // Just use the ParsingDeclaration "scope" of the declarator.
6714  DeclSpec DS(AttrFactory);
6715 
6716  // Parse any C++11 attributes.
6717  MaybeParseCXX11Attributes(DS.getAttributes());
6718 
6719  // Skip any Microsoft attributes before a param.
6720  MaybeParseMicrosoftAttributes(DS.getAttributes());
6721 
6722  SourceLocation DSStart = Tok.getLocation();
6723 
6724  // If the caller parsed attributes for the first argument, add them now.
6725  // Take them so that we only apply the attributes to the first parameter.
6726  // FIXME: If we can leave the attributes in the token stream somehow, we can
6727  // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6728  // too much hassle.
6729  DS.takeAttributesFrom(FirstArgAttrs);
6730 
6731  ParseDeclarationSpecifiers(DS);
6732 
6733 
6734  // Parse the declarator. This is "PrototypeContext" or
6735  // "LambdaExprParameterContext", because we must accept either
6736  // 'declarator' or 'abstract-declarator' here.
6737  Declarator ParmDeclarator(
6738  DS, DeclaratorCtx == DeclaratorContext::RequiresExprContext
6740  : DeclaratorCtx == DeclaratorContext::LambdaExprContext
6743  ParseDeclarator(ParmDeclarator);
6744 
6745  // Parse GNU attributes, if present.
6746  MaybeParseGNUAttributes(ParmDeclarator);
6747 
6748  if (Tok.is(tok::kw_requires)) {
6749  // User tried to define a requires clause in a parameter declaration,
6750  // which is surely not a function declaration.
6751  // void f(int (*g)(int, int) requires true);
6752  Diag(Tok,
6753  diag::err_requires_clause_on_declarator_not_declaring_a_function);
6754  ConsumeToken();
6755  Actions.CorrectDelayedTyposInExpr(
6756  ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
6757  }
6758 
6759  // Remember this parsed parameter in ParamInfo.
6760  IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
6761 
6762  // DefArgToks is used when the parsing of default arguments needs
6763  // to be delayed.
6764  std::unique_ptr<CachedTokens> DefArgToks;
6765 
6766  // If no parameter was specified, verify that *something* was specified,
6767  // otherwise we have a missing type and identifier.
6768  if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
6769  ParmDeclarator.getNumTypeObjects() == 0) {
6770  // Completely missing, emit error.
6771  Diag(DSStart, diag::err_missing_param);
6772  } else {
6773  // Otherwise, we have something. Add it and let semantic analysis try
6774  // to grok it and add the result to the ParamInfo we are building.
6775 
6776  // Last chance to recover from a misplaced ellipsis in an attempted
6777  // parameter pack declaration.
6778  if (Tok.is(tok::ellipsis) &&
6779  (NextToken().isNot(tok::r_paren) ||
6780  (!ParmDeclarator.getEllipsisLoc().isValid() &&
6781  !Actions.isUnexpandedParameterPackPermitted())) &&
6782  Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6783  DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6784 
6785  // Inform the actions module about the parameter declarator, so it gets
6786  // added to the current scope.
6787  Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
6788  // Parse the default argument, if any. We parse the default
6789  // arguments in all dialects; the semantic analysis in
6790  // ActOnParamDefaultArgument will reject the default argument in
6791  // C.
6792  if (Tok.is(tok::equal)) {
6793  SourceLocation EqualLoc = Tok.getLocation();
6794 
6795  // Parse the default argument
6796  if (DeclaratorCtx == DeclaratorContext::MemberContext) {
6797  // If we're inside a class definition, cache the tokens
6798  // corresponding to the default argument. We'll actually parse
6799  // them when we see the end of the class definition.
6800  DefArgToks.reset(new CachedTokens);
6801 
6802  SourceLocation ArgStartLoc = NextToken().getLocation();
6803  if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
6804  DefArgToks.reset();
6805  Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6806  } else {
6807  Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
6808  ArgStartLoc);
6809  }
6810  } else {
6811  // Consume the '='.
6812  ConsumeToken();
6813 
6814  // The argument isn't actually potentially evaluated unless it is
6815  // used.
6817  Actions,
6819  Param);
6820 
6821  ExprResult DefArgResult;
6822  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
6823  Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
6824  DefArgResult = ParseBraceInitializer();
6825  } else
6826  DefArgResult = ParseAssignmentExpression();
6827  DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
6828  if (DefArgResult.isInvalid()) {
6829  Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6830  SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
6831  } else {
6832  // Inform the actions module about the default argument
6833  Actions.ActOnParamDefaultArgument(Param, EqualLoc,
6834  DefArgResult.get());
6835  }
6836  }
6837  }
6838 
6839  ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6840  ParmDeclarator.getIdentifierLoc(),
6841  Param, std::move(DefArgToks)));
6842  }
6843 
6844  if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6845  if (!getLangOpts().CPlusPlus) {
6846  // We have ellipsis without a preceding ',', which is ill-formed
6847  // in C. Complain and provide the fix.
6848  Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6849  << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6850  } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6851  Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6852  // It looks like this was supposed to be a parameter pack. Warn and
6853  // point out where the ellipsis should have gone.
6854  SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6855  Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6856  << ParmEllipsis.isValid() << ParmEllipsis;
6857  if (ParmEllipsis.isValid()) {
6858  Diag(ParmEllipsis,
6859  diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6860  } else {
6861  Diag(ParmDeclarator.getIdentifierLoc(),
6862  diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6863  << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6864  "...")
6865  << !ParmDeclarator.hasName();
6866  }
6867  Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
6868  << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6869  }
6870 
6871  // We can't have any more parameters after an ellipsis.
6872  break;
6873  }
6874 
6875  // If the next token is a comma, consume it and keep reading arguments.
6876  } while (TryConsumeToken(tok::comma));
6877 }
6878 
6879 /// [C90] direct-declarator '[' constant-expression[opt] ']'
6880 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6881 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6882 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6883 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
6884 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
6885 /// attribute-specifier-seq[opt]
6886 void Parser::ParseBracketDeclarator(Declarator &D) {
6887  if (CheckProhibitedCXX11Attribute())
6888  return;
6889 
6890  BalancedDelimiterTracker T(*this, tok::l_square);
6891  T.consumeOpen();
6892 
6893  // C array syntax has many features, but by-far the most common is [] and [4].
6894  // This code does a fast path to handle some of the most obvious cases.
6895  if (Tok.getKind() == tok::r_square) {
6896  T.consumeClose();
6897  ParsedAttributes attrs(AttrFactory);
6898  MaybeParseCXX11Attributes(attrs);
6899 
6900  // Remember that we parsed the empty array type.
6901  D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
6902  T.getOpenLocation(),
6903  T.getCloseLocation()),
6904  std::move(attrs), T.getCloseLocation());
6905  return;
6906  } else if (Tok.getKind() == tok::numeric_constant &&
6907  GetLookAheadToken(1).is(tok::r_square)) {
6908  // [4] is very common. Parse the numeric constant expression.
6909  ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
6910  ConsumeToken();
6911 
6912  T.consumeClose();
6913  ParsedAttributes attrs(AttrFactory);
6914  MaybeParseCXX11Attributes(attrs);
6915 
6916  // Remember that we parsed a array type, and remember its features.
6917  D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
6918  T.getOpenLocation(),
6919  T.getCloseLocation()),
6920  std::move(attrs), T.getCloseLocation());
6921  return;
6922  } else if (Tok.getKind() == tok::code_completion) {
6923  Actions.CodeCompleteBracketDeclarator(getCurScope());
6924  return cutOffParsing();
6925  }
6926 
6927  // If valid, this location is the position where we read the 'static' keyword.
6928  SourceLocation StaticLoc;
6929  TryConsumeToken(tok::kw_static, StaticLoc);
6930 
6931  // If there is a type-qualifier-list, read it now.
6932  // Type qualifiers in an array subscript are a C99 feature.
6933  DeclSpec DS(AttrFactory);
6934  ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
6935 
6936  // If we haven't already read 'static', check to see if there is one after the
6937  // type-qualifier-list.
6938  if (!StaticLoc.isValid())
6939  TryConsumeToken(tok::kw_static, StaticLoc);
6940 
6941  // Handle "direct-declarator [ type-qual-list[opt] * ]".
6942  bool isStar = false;
6943  ExprResult NumElements;
6944 
6945  // Handle the case where we have '[*]' as the array size. However, a leading
6946  // star could be the start of an expression, for example 'X[*p + 4]'. Verify
6947  // the token after the star is a ']'. Since stars in arrays are
6948  // infrequent, use of lookahead is not costly here.
6949  if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
6950  ConsumeToken(); // Eat the '*'.
6951 
6952  if (StaticLoc.isValid()) {
6953  Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
6954  StaticLoc = SourceLocation(); // Drop the static.
6955  }
6956  isStar = true;
6957  } else if (Tok.isNot(tok::r_square)) {
6958  // Note, in C89, this production uses the constant-expr production instead
6959  // of assignment-expr. The only difference is that assignment-expr allows
6960  // things like '=' and '*='. Sema rejects these in C89 mode because they
6961  // are not i-c-e's, so we don't need to distinguish between the two here.
6962 
6963  // Parse the constant-expression or assignment-expression now (depending
6964  // on dialect).
6965  if (getLangOpts().CPlusPlus) {
6966  NumElements = ParseConstantExpression();
6967  } else {
6970  NumElements =
6971  Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
6972  }
6973  } else {
6974  if (StaticLoc.isValid()) {
6975  Diag(StaticLoc, diag::err_unspecified_size_with_static);
6976  StaticLoc = SourceLocation(); // Drop the static.
6977  }
6978  }
6979 
6980  // If there was an error parsing the assignment-expression, recover.
6981  if (NumElements.isInvalid()) {
6982  D.setInvalidType(true);
6983  // If the expression was invalid, skip it.
6984  SkipUntil(tok::r_square, StopAtSemi);
6985  return;
6986  }
6987 
6988  T.consumeClose();
6989 
6990  MaybeParseCXX11Attributes(DS.getAttributes());
6991 
6992  // Remember that we parsed a array type, and remember its features.
6993  D.AddTypeInfo(
6995  isStar, NumElements.get(), T.getOpenLocation(),
6996  T.getCloseLocation()),
6997  std::move(DS.getAttributes()), T.getCloseLocation());
6998 }
6999 
7000 /// Diagnose brackets before an identifier.
7001 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
7002  assert(Tok.is(tok::l_square) && "Missing opening bracket");
7003  assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
7004 
7005  SourceLocation StartBracketLoc = Tok.getLocation();
7006  Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
7007 
7008  while (Tok.is(tok::l_square)) {
7009  ParseBracketDeclarator(TempDeclarator);
7010  }
7011 
7012  // Stuff the location of the start of the brackets into the Declarator.
7013  // The diagnostics from ParseDirectDeclarator will make more sense if
7014  // they use this location instead.
7015  if (Tok.is(tok::semi))
7016  D.getName().EndLocation = StartBracketLoc;
7017 
7018  SourceLocation SuggestParenLoc = Tok.getLocation();
7019 
7020  // Now that the brackets are removed, try parsing the declarator again.
7021  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
7022 
7023  // Something went wrong parsing the brackets, in which case,
7024  // ParseBracketDeclarator has emitted an error, and we don't need to emit
7025  // one here.
7026  if (TempDeclarator.getNumTypeObjects() == 0)
7027  return;
7028 
7029  // Determine if parens will need to be suggested in the diagnostic.
7030  bool NeedParens = false;
7031  if (D.getNumTypeObjects() != 0) {
7032  switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
7037  case DeclaratorChunk::Pipe:
7038  NeedParens = true;
7039  break;
7043  break;
7044  }
7045  }
7046 
7047  if (NeedParens) {
7048  // Create a DeclaratorChunk for the inserted parens.
7049  SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
7050  D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
7051  SourceLocation());
7052  }
7053 
7054  // Adding back the bracket info to the end of the Declarator.
7055  for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
7056  const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
7057  D.AddTypeInfo(Chunk, SourceLocation());
7058  }
7059 
7060  // The missing identifier would have been diagnosed in ParseDirectDeclarator.
7061  // If parentheses are required, always suggest them.
7062  if (!D.getIdentifier() && !NeedParens)
7063  return;
7064 
7065  SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
7066 
7067  // Generate the move bracket error message.
7068  SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
7069  SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
7070 
7071  if (NeedParens) {
7072  Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
7073  << getLangOpts().CPlusPlus
7074  << FixItHint::CreateInsertion(SuggestParenLoc, "(")
7075  << FixItHint::CreateInsertion(EndLoc, ")")
7077  EndLoc, CharSourceRange(BracketRange, true))
7078  << FixItHint::CreateRemoval(BracketRange);
7079  } else {
7080  Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
7081  << getLangOpts().CPlusPlus
7083  EndLoc, CharSourceRange(BracketRange, true))
7084  << FixItHint::CreateRemoval(BracketRange);
7085  }
7086 }
7087 
7088 /// [GNU] typeof-specifier:
7089 /// typeof ( expressions )
7090 /// typeof ( type-name )
7091 /// [GNU/C++] typeof unary-expression
7092 ///
7093 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
7094  assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
7095  Token OpTok = Tok;
7096  SourceLocation StartLoc = ConsumeToken();
7097 
7098  const bool hasParens = Tok.is(tok::l_paren);
7099 
7103 
7104  bool isCastExpr;
7105  ParsedType CastTy;
7106  SourceRange CastRange;
7107  ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
7108  ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
7109  if (hasParens)
7110  DS.setTypeofParensRange(CastRange);
7111 
7112  if (CastRange.getEnd().isInvalid())
7113  // FIXME: Not accurate, the range gets one token more than it should.
7114  DS.SetRangeEnd(Tok.getLocation());
7115  else
7116  DS.SetRangeEnd(CastRange.getEnd());
7117 
7118  if (isCastExpr) {
7119  if (!CastTy) {
7120  DS.SetTypeSpecError();
7121  return;
7122  }
7123 
7124  const char *PrevSpec = nullptr;
7125  unsigned DiagID;
7126  // Check for duplicate type specifiers (e.g. "int typeof(int)").
7127  if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
7128  DiagID, CastTy,
7129  Actions.getASTContext().getPrintingPolicy()))
7130  Diag(StartLoc, DiagID) << PrevSpec;
7131  return;
7132  }
7133 
7134  // If we get here, the operand to the typeof was an expression.
7135  if (Operand.isInvalid()) {
7136  DS.SetTypeSpecError();
7137  return;
7138  }
7139 
7140  // We might need to transform the operand if it is potentially evaluated.
7141  Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
7142  if (Operand.isInvalid()) {
7143  DS.SetTypeSpecError();
7144  return;
7145  }
7146 
7147  const char *PrevSpec = nullptr;
7148  unsigned DiagID;
7149  // Check for duplicate type specifiers (e.g. "int typeof(int)").
7150  if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
7151  DiagID, Operand.get(),
7152  Actions.getASTContext().getPrintingPolicy()))
7153  Diag(StartLoc, DiagID) << PrevSpec;
7154 }
7155 
7156 /// [C11] atomic-specifier:
7157 /// _Atomic ( type-name )
7158 ///
7159 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
7160  assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
7161  "Not an atomic specifier");
7162 
7163  SourceLocation StartLoc = ConsumeToken();
7164  BalancedDelimiterTracker T(*this, tok::l_paren);
7165  if (T.consumeOpen())
7166  return;
7167 
7169  if (Result.isInvalid()) {
7170  SkipUntil(tok::r_paren, StopAtSemi);
7171  return;
7172  }
7173 
7174  // Match the ')'
7175  T.consumeClose();
7176 
7177  if (T.getCloseLocation().isInvalid())
7178  return;
7179 
7181  DS.SetRangeEnd(T.getCloseLocation());
7182 
7183  const char *PrevSpec = nullptr;
7184  unsigned DiagID;
7185  if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
7186  DiagID, Result.get(),
7187  Actions.getASTContext().getPrintingPolicy()))
7188  Diag(StartLoc, DiagID) << PrevSpec;
7189 }
7190 
7191 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
7192 /// from TryAltiVecVectorToken.
7193 bool Parser::TryAltiVecVectorTokenOutOfLine() {
7194  Token Next = NextToken();
7195  switch (Next.getKind()) {
7196  default: return false;
7197  case tok::kw_short:
7198  case tok::kw_long:
7199  case tok::kw_signed:
7200  case tok::kw_unsigned:
7201  case tok::kw_void:
7202  case tok::kw_char:
7203  case tok::kw_int:
7204  case tok::kw_float:
7205  case tok::kw_double:
7206  case tok::kw_bool:
7207  case tok::kw___bool:
7208  case tok::kw___pixel:
7209  Tok.setKind(tok::kw___vector);
7210  return true;
7211  case tok::identifier:
7212  if (Next.getIdentifierInfo() == Ident_pixel) {
7213  Tok.setKind(tok::kw___vector);
7214  return true;
7215  }
7216  if (Next.getIdentifierInfo() == Ident_bool) {
7217  Tok.setKind(tok::kw___vector);
7218  return true;
7219  }
7220  return false;
7221  }
7222 }
7223 
7224 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
7225  const char *&PrevSpec, unsigned &DiagID,
7226  bool &isInvalid) {
7227  const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
7228  if (Tok.getIdentifierInfo() == Ident_vector) {
7229  Token Next = NextToken();
7230  switch (Next.getKind()) {
7231  case tok::kw_short:
7232  case tok::kw_long:
7233  case tok::kw_signed:
7234  case tok::kw_unsigned:
7235  case tok::kw_void:
7236  case tok::kw_char:
7237  case tok::kw_int:
7238  case tok::kw_float:
7239  case tok::kw_double:
7240  case tok::kw_bool:
7241  case tok::kw___bool:
7242  case tok::kw___pixel:
7243  isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
7244  return true;
7245  case tok::identifier:
7246  if (Next.getIdentifierInfo() == Ident_pixel) {
7247  isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
7248  return true;
7249  }
7250  if (Next.getIdentifierInfo() == Ident_bool) {
7251  isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
7252  return true;
7253  }
7254  break;
7255  default:
7256  break;
7257  }
7258  } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
7259  DS.isTypeAltiVecVector()) {
7260  isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
7261  return true;
7262  } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
7263  DS.isTypeAltiVecVector()) {
7264  isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
7265  return true;
7266  }
7267  return false;
7268 }
void ClearFunctionSpecs()
Definition: DeclSpec.h:597
The name denotes a member of a dependent type that could not be resolved.
Definition: Sema.h:1934
Defines the clang::ASTContext interface.
static bool isAttributeLateParsed(const IdentifierInfo &II)
isAttributeLateParsed - Return true if the attribute has arguments that require late parsing...
Definition: ParseDecl.cpp:80
The name was classified as a variable template name.
Definition: Sema.h:1941
static bool FindLocsWithCommonFileID(Preprocessor &PP, SourceLocation StartLoc, SourceLocation EndLoc)
Check if the a start and end source location expand to the same macro.
Definition: ParseDecl.cpp:89
static Qualifiers fromCVRUMask(unsigned CVRU)
Definition: Type.h:242
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2313
no exception specification
PtrTy get() const
Definition: Ownership.h:80
ExprResult ParseExpression(TypeCastState isTypeCast=NotTypeCast)
Simple precedence-based parser for binary/ternary operators.
Definition: ParseExpr.cpp:123
A (possibly-)qualified type.
Definition: Type.h:654
This is a scope that corresponds to the parameters within a function prototype.
Definition: Scope.h:81
SourceLocation getEndOfPreviousToken()
Definition: Parser.h:498
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1160
static const TSS TSS_unsigned
Definition: DeclSpec.h:268
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:1018
Code completion occurs within a class, struct, or union.
Definition: Sema.h:11458
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2224
SizeType size() const
Definition: ParsedAttr.h:734
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition: DeclSpec.cpp:923
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:3435
IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
static const TST TST_wchar
Definition: DeclSpec.h:275
llvm::PointerUnion< Expr *, IdentifierLoc * > ArgsUnion
A union of the various pointer types that can be passed to an ParsedAttr as an argument.
Definition: ParsedAttr.h:105
The name was classified as an ADL-only function template name.
Definition: Sema.h:1945
static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II)
Determine whether the given attribute has a variadic identifier argument.
Definition: ParseDecl.cpp:256
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:97
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:189
static const TST TST_typeofExpr
Definition: DeclSpec.h:299
static const TST TST_char16
Definition: DeclSpec.h:277
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
Syntax
The style used to specify an attribute.
RAII object used to inform the actions that we&#39;re currently parsing a declaration.
Is the identifier known as a __declspec-style attribute?
A RAII object used to temporarily suppress access-like checking.
Defines the C++ template declaration subclasses.
StringRef P
IdentifierInfo * Ident
Definition: ParsedAttr.h:97
The base class of the type hierarchy.
Definition: Type.h:1450
Classification failed; an error has been produced.
Definition: Sema.h:1918
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
Definition: Parser.cpp:2029
SourceLocation getCloseLocation() const
This indicates that the scope corresponds to a function, which means that labels are set here...
Definition: Scope.h:47
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1931
One instance of this struct is used for each type in a declarator that is parsed. ...
Definition: DeclSpec.h:1174
Declaration of a variable template.
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2282
static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, CharSourceRange FromRange, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code from FromRange at a specific location...
Definition: Diagnostic.h:105
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:520
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:1932
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:425
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:113
TemplateNameKind Kind
The kind of template that Template refers to.
void ActOnExitFunctionContext()
Definition: SemaDecl.cpp:1398
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1787
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:57
bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:882
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:584
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:448
void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2181
static IdentifierLoc * create(ASTContext &Ctx, SourceLocation Loc, IdentifierInfo *Ident)
Definition: ParsedAttr.cpp:28
SourceLocation getEndLoc() const
Definition: DeclSpec.h:73
NameClassificationKind getKind() const
Definition: Sema.h:2024
static bool isAtStartOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroBegin=nullptr)
Returns true if the given MacroID location points at the first token of the macro expansion...
Definition: Lexer.cpp:800
RAII object that enters a new expression evaluation context.
Definition: Sema.h:12029
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1792
void setTypeofParensRange(SourceRange range)
Definition: DeclSpec.h:527
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
Definition: DeclSpec.cpp:436
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:60
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:25
static const TST TST_interface
Definition: DeclSpec.h:295
RAII object used to temporarily allow the C++ &#39;this&#39; expression to be used, with the given qualifiers...
Definition: Sema.h:5616
static const TST TST_char
Definition: DeclSpec.h:274
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:624
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:47
Code completion occurs within an Objective-C implementation or category implementation.
Definition: Sema.h:11464
RAII object that makes sure paren/bracket/brace count is correct after declaration/statement parsing...
friend class ObjCDeclContextSwitch
Definition: Parser.h:62
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:120
Represents a parameter to a function.
Definition: Decl.h:1595
The name was classified as a non-type, and an expression representing that name has been formed...
Definition: Sema.h:1937
ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and restores it when destroyed...
tok::TokenKind getKind() const
Definition: Token.h:92
bool SetConstexprSpec(ConstexprSpecKind ConstexprKind, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1046
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:1118
void setTrailingRequiresClause(Expr *TRC)
Sets a trailing requires clause for this declarator.
Definition: DeclSpec.h:2441
bool mayOmitIdentifier() const
mayOmitIdentifier - Return true if the identifier is either optional or not allowed.
Definition: DeclSpec.h:1979
The collection of all-type qualifiers we support.
Definition: Type.h:143
Information about a template-id annotation token.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:58
SourceLocation getFriendSpecLoc() const
Definition: DeclSpec.h:741
Represents a struct/union/class.
Definition: Decl.h:3748
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:759
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:460
One of these records is kept for each identifier that is lexed.
SourceLocation getBegin() const
static const TST TST_decimal32
Definition: DeclSpec.h:289
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
static bool attributeHasIdentifierArg(const IdentifierInfo &II)
Determine whether the given attribute has an identifier argument.
Definition: ParseDecl.cpp:247
static const TST TST_char8
Definition: DeclSpec.h:276
Lookup for the name failed, but we&#39;re assuming it was a template name anyway.
Definition: TemplateKinds.h:50
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:517
static const TST TST_class
Definition: DeclSpec.h:296
bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, ExplicitSpecifier ExplicitSpec, SourceLocation CloseParenLoc)
Definition: DeclSpec.cpp:979
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:55
static const TST TST_double
Definition: DeclSpec.h:283
Code completion occurs following one or more template headers within a class.
Definition: Sema.h:11473
bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:964
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:32
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:417
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
static const TST TST_enum
Definition: DeclSpec.h:292
void setKind(tok::TokenKind K)
Definition: Token.h:93
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ...
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:14230
bool hasTagDefinition() const
Definition: DeclSpec.cpp:427
void ClearStorageClassSpecs()
Definition: DeclSpec.h:461
static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc, SourceLocation ConstQualLoc, SourceLocation VolatileQualLoc, SourceLocation RestrictQualLoc, SourceLocation AtomicQualLoc, SourceLocation UnalignedQualLoc)
Return a DeclaratorChunk for a pointer.
Definition: DeclSpec.h:1571
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:53
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:907
void * getAsOpaquePtr() const
Definition: Ownership.h:90
static const TST TST_accum
Definition: DeclSpec.h:285
bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:865
bool isInvalidType() const
Definition: DeclSpec.h:2530
The name was classified as a type.
Definition: Sema.h:1922
Code completion occurs at top-level or namespace context.
Definition: Sema.h:11456
The name was classified as a template whose specializations are types.
Definition: Sema.h:1939
The controlling scope in a if/switch/while/for statement.
Definition: Scope.h:62
bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const
Return true if we have an ObjC keyword identifier.
Definition: Lexer.cpp:57
This is a scope that corresponds to a block/closure object.
Definition: Scope.h:71
bool isFunctionDeclaratorAFunctionDeclaration() const
Return true if a function declarator at this position would be a function declaration.
Definition: DeclSpec.h:2419
static ParsedType getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition: Parser.h:764
Represents the results of name lookup.
Definition: Lookup.h:46
PtrTy get() const
Definition: Ownership.h:170
void setExtension(bool Val=true)
Definition: DeclSpec.h:2520
bool isNot(T Kind) const
Definition: FormatToken.h:330
void startOpenMPCXXRangeFor()
If the current region is a range loop-based region, mark the start of the loop construct.
This scope corresponds to an enum.
Definition: Scope.h:118
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the &#39;spelling&#39; of the token at the given location; does not go up to the spelling location or ...
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
static StringRef normalizeAttrName(StringRef Name)
Normalizes an attribute name by dropping prefixed and suffixed __.
Definition: ParseDecl.cpp:72
void SetRangeBegin(SourceLocation Loc)
SetRangeBegin - Set the start of the source range to Loc, unless it&#39;s invalid.
Definition: DeclSpec.h:1937
Code completion occurs following one or more template headers.
Definition: Sema.h:11470
bool isTypeSpecPipe() const
Definition: DeclSpec.h:485
bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:952
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl *> Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:13017
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2220
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:671
The name has been typo-corrected to a keyword.
Definition: Sema.h:1920
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:277
bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1016
bool hasAttributes() const
Definition: DeclSpec.h:785
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
Represents information about a change in availability for an entity, which is part of the encoding of...
Definition: ParsedAttr.h:44
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
int hasAttribute(AttrSyntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const TargetInfo &Target, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
Definition: Attributes.cpp:8
bool SetTypePipe(bool isPipe, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:848
bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1001
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID. ...
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type...
Definition: Parser.h:480
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:551
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:1910
bool isCPlusPlusKeyword(const LangOptions &LangOpts) const
Return true if this token is a C++ keyword in the specified language.
void addAtEnd(ParsedAttr *newAttr)
Definition: ParsedAttr.h:738
static bool VersionNumberSeparator(const char Separator)
Definition: ParseDecl.cpp:843
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:509
const char * getName() const
Definition: Token.h:168
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
VersionTuple getOpenCLVersionTuple() const
Return the OpenCL C or C++ version as a VersionTuple.
Definition: LangOptions.cpp:46
VersionTuple Version
The version number at which the change occurred.
Definition: ParsedAttr.h:49
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2172
static const TST TST_float
Definition: DeclSpec.h:282
Language
The language for the input, used to select and validate the language standard and possible actions...
Definition: LangStandard.h:19
Code completion occurs within a sequence of declaration specifiers within a function, method, or block.
Definition: Sema.h:11496
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:220
Provides definitions for the various language-specific address spaces.
static const TSW TSW_long
Definition: DeclSpec.h:255
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(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:151
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:555
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:751
bool isOneOf(A K1, B K2) const
Definition: FormatToken.h:323
ParsedAttr * addNewTypeTagForDatatype(IdentifierInfo *attrName, SourceRange attrRange, IdentifierInfo *scopeName, SourceLocation scopeLoc, IdentifierLoc *argumentKind, ParsedType matchingCType, bool layoutCompatible, bool mustBeNull, ParsedAttr::Syntax syntax)
Add type_tag_for_datatype attribute.
Definition: ParsedAttr.h:890
void ClearConstexprSpec()
Definition: DeclSpec.h:755
bool mayBeFollowedByCXXDirectInit() const
mayBeFollowedByCXXDirectInit - Return true if the declarator can be followed by a C++ direct initiali...
Definition: DeclSpec.h:2099
A class for parsing a declarator.
bool isPastIdentifier() const
isPastIdentifier - Return true if we have parsed beyond the point where the name would appear...
Definition: DeclSpec.h:2156
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:641
The name was classified as a function template name.
Definition: Sema.h:1943
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1314
Stop at code completion.
Definition: Parser.h:1101
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
TST getTypeSpecType() const
Definition: DeclSpec.h:479
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:939
static bool isAtEndOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroEnd=nullptr)
Returns true if the given MacroID location points at the last token of the macro expansion.
Definition: Lexer.cpp:822
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
ParsedAttr * addNewPropertyAttr(IdentifierInfo *attrName, SourceRange attrRange, IdentifierInfo *scopeName, SourceLocation scopeLoc, IdentifierInfo *getterId, IdentifierInfo *setterId, ParsedAttr::Syntax syntaxUsed)
Add microsoft __delspec(property) attribute.
Definition: ParsedAttr.h:915
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e...
Definition: SemaDecl.cpp:4305
SourceLocation End
void setDecompositionBindings(SourceLocation LSquareLoc, ArrayRef< DecompositionDeclarator::Binding > Bindings, SourceLocation RSquareLoc)
Set the decomposition bindings for this declarator.
Definition: DeclSpec.cpp:280
Represents a character-granular source range.
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
Definition: ParseDecl.cpp:1922
bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, ParsedType ObjectType, SourceLocation *TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
static DeclaratorChunk getPipe(unsigned TypeQuals, SourceLocation Loc)
Return a DeclaratorChunk for a block.
Definition: DeclSpec.h:1652
TypeResult ActOnTypeName(Scope *S, Declarator &D)
Definition: SemaType.cpp:6026
bool isTypeAltiVecVector() const
Definition: DeclSpec.h:480
The name was classified as a specific non-type, non-template declaration.
Definition: Sema.h:1926
void setEofData(const void *D)
Definition: Token.h:196
The name refers to a concept.
Definition: TemplateKinds.h:52
static bool isPipeDeclerator(const Declarator &D)
Definition: ParseDecl.cpp:5578
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:553
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:457
static constexpr bool isOneOf()
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:126
void setAsmLabel(Expr *E)
Definition: DeclSpec.h:2517
DeclContext * getDeclContext()
Definition: DeclBase.h:438
bool hasEllipsis() const
Definition: DeclSpec.h:2541
static const TST TST_decimal64
Definition: DeclSpec.h:290
This is a compound statement scope.
Definition: Scope.h:130
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:456
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1042
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7)...
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:707
SourceLocation KeywordLoc
The location of the keyword indicating the kind of change.
Definition: ParsedAttr.h:46
A class for parsing a field declarator.
bool isValid() const
Determine whether this availability change is valid.
Definition: ParsedAttr.h:55
bool isInvalid() const
SourceLocation Loc
Loc - The place where this type was defined.
Definition: DeclSpec.h:1180
DeclaratorContext
Definition: DeclSpec.h:1749
static SourceLocation getMissingDeclaratorIdLoc(Declarator &D, SourceLocation Loc)
Definition: ParseDecl.cpp:5776
static const TST TST_int
Definition: DeclSpec.h:279
void setEllipsisLoc(SourceLocation EL)
Definition: DeclSpec.h:2543
bool isInvalid() const
Definition: Ownership.h:166
SourceLocation getEnd() const
bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:692
SourceLocation getOpenLocation() const
static const TST TST_half
Definition: DeclSpec.h:281
bool isFriendSpecified() const
Definition: DeclSpec.h:740
Wraps an identifier and optional source location for the identifier.
Definition: ParsedAttr.h:95
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an initializer for the declaration ...
bool isUsable() const
Definition: Ownership.h:167
The result type of a method or function.
SourceRange VersionRange
The source range covering the version number.
Definition: ParsedAttr.h:52
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:719
static const TSW TSW_short
Definition: DeclSpec.h:254
const SourceManager & SM
Definition: Format.cpp:1685
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
bool isFirstDeclarator() const
Definition: DeclSpec.h:2537
const LangOptions & getLangOpts() const
Definition: Parser.h:407
bool SetTypeSpecWidth(TSW W, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec, but return true and ignore the request if ...
Definition: DeclSpec.cpp:665
This is a scope that corresponds to the parameters within a function prototype for a function declara...
Definition: Scope.h:87
bool hasGroupingParens() const
Definition: DeclSpec.h:2535
SourceManager & getSourceManager() const
Definition: Preprocessor.h:911
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:746
static const TST TST_char32
Definition: DeclSpec.h:278
static const TST TST_fract
Definition: DeclSpec.h:286
A class for parsing a DeclSpec.
bool isTemplateDecl() const
returns true if this declaration is a template
Definition: DeclBase.cpp:226
static DeclaratorChunk getParen(SourceLocation LParenLoc, SourceLocation RParenLoc)
Return a DeclaratorChunk for a paren.
Definition: DeclSpec.h:1674
Kind
Stop skipping at semicolon.
Definition: Parser.h:1098
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:153
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition: DeclSpec.h:1590
SCS getStorageClassSpec() const
Definition: DeclSpec.h:447
static const TST TST_float16
Definition: DeclSpec.h:284
bool hasName() const
hasName - Whether this declarator has a name, which might be an identifier (accessible via getIdentif...
Definition: DeclSpec.h:2162
Encodes a location in the source.
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
bool isTypeSpecOwned() const
Definition: DeclSpec.h:483
static const TST TST_auto_type
Definition: DeclSpec.h:304
bool TryAnnotateTypeOrScopeToken()
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
Definition: Parser.cpp:1800
bool is(tok::TokenKind Kind) const
Definition: FormatToken.h:314
enum clang::DeclaratorChunk::@219 Kind
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:1914
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:12758
static void SetupFixedPointError(const LangOptions &LangOpts, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid)
Definition: ParseDecl.cpp:2995
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3219
void ExitScope()
ExitScope - Pop a scope off the scope stack.
Definition: Parser.cpp:381
This is a scope that corresponds to the Objective-C @catch statement.
Definition: Scope.h:91
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:377
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:511
static const TST TST_union
Definition: DeclSpec.h:293
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:179
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:117
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error...
Definition: DeclSpec.cpp:589
bool hasTrailingRequiresClause() const
Determine whether a trailing requires clause was written in this declarator.
Definition: DeclSpec.h:2452
bool isWrittenInBuiltinFile(SourceLocation Loc) const
Returns whether Loc is located in a <built-in> file.
static const TSS TSS_signed
Definition: DeclSpec.h:267
ExtensionRAIIObject - This saves the state of extension warnings when constructed and disables them...
void setGroupingParens(bool flag)
Definition: DeclSpec.h:2534
ParsedAttr * addNew(IdentifierInfo *attrName, SourceRange attrRange, IdentifierInfo *scopeName, SourceLocation scopeLoc, ArgsUnion *args, unsigned numArgs, ParsedAttr::Syntax syntax, SourceLocation ellipsisLoc=SourceLocation())
Add attribute with expression arguments.
Definition: ParsedAttr.h:850
void EnterScope(unsigned ScopeFlags)
EnterScope - Start a new scope.
Definition: Parser.cpp:370
const char * getNameStart() const
Return the beginning of the actual null-terminated string for this identifier.
This name is not a type or template in this context, but might be something else. ...
Definition: Sema.h:1916
const void * getEofData() const
Definition: Token.h:192
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:268
static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang, DeclaratorContext TheContext)
Definition: ParseDecl.cpp:5549
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:24
void remove(ParsedAttr *ToBeRemoved)
Definition: ParsedAttr.h:743
Decl * getRepAsDecl() const
Definition: DeclSpec.h:493
static const TST TST_typeofType
Definition: DeclSpec.h:298
Used for C&#39;s _Alignof and C++&#39;s alignof.
Definition: TypeTraits.h:100
Scope * getCurScope() const
Definition: Parser.h:414
bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:833
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:573
static DeclaratorChunk getArray(unsigned TypeQuals, bool isStatic, bool isStar, Expr *NumElts, SourceLocation LBLoc, SourceLocation RBLoc)
Return a DeclaratorChunk for an array.
Definition: DeclSpec.h:1601
ExprResult ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast=NotTypeCast)
Definition: ParseExpr.cpp:201
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:744
StringRef getName() const
Return the actual identifier string.
The scope of a struct/union/class definition.
Definition: Scope.h:65
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:1930
bool isNot(tok::TokenKind K) const
Definition: Token.h:98
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
Definition: SemaDecl.cpp:1374
TSW getTypeSpecWidth() const
Definition: DeclSpec.h:476
ParserCompletionContext
Describes the context in which code completion occurs.
Definition: Sema.h:11454
bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1034
static bool isInvalid(LocType Loc, bool *Invalid)
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool expectAndConsume(unsigned DiagID=diag::err_expected, const char *Msg="", tok::TokenKind SkipToTok=tok::unknown)
Definition: Parser.cpp:2489
static const TST TST_auto
Definition: DeclSpec.h:303
static const TST TST_void
Definition: DeclSpec.h:273
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition: DeclBase.h:1018
static const TST TST_int128
Definition: DeclSpec.h:280
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:118
SourceLocation getPipeLoc() const
Definition: DeclSpec.h:556
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:77
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:99
Represents an enum.
Definition: Decl.h:3481
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
static const TST TST_unspecified
Definition: DeclSpec.h:272
unsigned getLength() const
Definition: Token.h:129
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:196
void addConst()
Definition: Type.h:263
bool isMacroID() const
LLVM_READONLY bool isDigit(unsigned char c)
Return true if this character is an ASCII digit: [0-9].
Definition: CharInfo.h:93
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
const TargetInfo & getTargetInfo() const
Definition: Parser.h:408
static const TST TST_decimal128
Definition: DeclSpec.h:291
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:550
void takeAttributesFrom(ParsedAttributes &attrs)
Definition: DeclSpec.h:790
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition: Parser.cpp:72
static const TSCS TSCS___thread
Definition: DeclSpec.h:247
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:582
bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:651
static const TST TST_typename
Definition: DeclSpec.h:297
The name was classified as an ADL-only function name.
Definition: Sema.h:1930
void SetRangeEnd(SourceLocation Loc)
SetRangeEnd - Set the end of the source range to Loc, unless it&#39;s invalid.
Definition: DeclSpec.h:1942
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast=NotTypeCast)
Parse an expr that doesn&#39;t include (top-level) commas.
Definition: ParseExpr.cpp:160
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
void ActOnCXXForRangeDecl(Decl *D)
Definition: SemaDecl.cpp:12412
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:92
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition: DeclSpec.h:2195
CharSourceRange getExpansionRange(SourceLocation Loc) const
Given a SourceLocation object, return the range of tokens covered by the expansion in the ultimate fi...
CXXScopeSpec & getTypeSpecScope()
Definition: DeclSpec.h:506
This is a scope that can contain a declaration.
Definition: Scope.h:59
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:796
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2178
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
The name was classified as a concept name.
Definition: Sema.h:1947
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:14781
ParsedAttr * addNewTypeAttr(IdentifierInfo *attrName, SourceRange attrRange, IdentifierInfo *scopeName, SourceLocation scopeLoc, ParsedType typeArg, ParsedAttr::Syntax syntaxUsed)
Add an attribute with a single type argument.
Definition: ParsedAttr.h:903
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2529
ExprResult ParseConstantExpression(TypeCastState isTypeCast=NotTypeCast)
Definition: ParseExpr.cpp:211
static constexpr unsigned getMaxFunctionScopeDepth()
Definition: Decl.h:1647
static DeclaratorChunk getBlockPointer(unsigned TypeQuals, SourceLocation Loc)
Return a DeclaratorChunk for a block.
Definition: DeclSpec.h:1642
static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II)
Determine whether the given attribute requires parsing its arguments in an unevaluated context or not...
Definition: ParseDecl.cpp:284
Captures information about "declaration specifiers".
Definition: DeclSpec.h:228
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:552
static bool isValidAfterIdentifierInDeclarator(const Token &T)
isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the specified token is valid after t...
Definition: ParseDecl.cpp:2552
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl *> Group)
Definition: SemaDecl.cpp:12946
SourceLocation ConsumeToken()
ConsumeToken - Consume the current &#39;peek token&#39; and lex the next one.
Definition: Parser.h:452
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:248
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:2542
bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:820
void ClearTypeSpecType()
Definition: DeclSpec.h:469
bool isPragmaAnnotation(TokenKind K)
Return true if this is an annotation token representing a pragma.
Definition: TokenKinds.cpp:59
bool mayHaveIdentifier() const
mayHaveIdentifier - Return true if the identifier is either optional or required. ...
Definition: DeclSpec.h:2018
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:191
static const TST TST_float128
Definition: DeclSpec.h:287
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1895
static const TST TST_bool
Definition: DeclSpec.h:288
bool isVirtualSpecified() const
Definition: DeclSpec.h:581
Decl * getObjCDeclContext() const
Definition: Parser.h:419
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:129
iterator end() const
Definition: Lookup.h:336
A template-id, e.g., f<int>.
void Finish(Sema &S, const PrintingPolicy &Policy)
Finish - This does final analysis of the declspec, issuing diagnostics for things like "_Imaginary" (...
Definition: DeclSpec.cpp:1069
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1711
Defines the clang::TargetInfo interface.
bool isInlineSpecified() const
Definition: DeclSpec.h:570
void ExtendWithDeclSpec(const DeclSpec &DS)
ExtendWithDeclSpec - Extend the declarator source range to include the given declspec, unless its location is invalid.
Definition: DeclSpec.h:1949
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:554
ExprResult ExprError()
Definition: Ownership.h:279
static const TSW TSW_longlong
Definition: DeclSpec.h:256
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:947
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:587
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:750
static bool attributeIsTypeArgAttr(const IdentifierInfo &II)
Determine whether the given attribute parses a type argument.
Definition: ParseDecl.cpp:274
static const TST TST_atomic
Definition: DeclSpec.h:306
static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II)
Determine whether the given attribute treats kw_this as an identifier.
Definition: ParseDecl.cpp:265
bool isEmpty() const
isEmpty - Return true if this declaration specifier is completely empty: no tokens were parsed in the...
Definition: DeclSpec.h:637
void addAddressSpace(LangAS space)
Definition: Type.h:385
static const TST TST_struct
Definition: DeclSpec.h:294
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:66
ParamInfo - An array of paraminfo objects is allocated whenever a function declarator is parsed...
Definition: DeclSpec.h:1250
DeclaratorContext getContext() const
Definition: DeclSpec.h:1920
void setLocation(SourceLocation L)
Definition: Token.h:134
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:385
bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:682
This represents a decl that may have a name.
Definition: Decl.h:223
bool SetTypeSpecError()
Definition: DeclSpec.cpp:899
SourceLocation EndLocation
The location of the last token that describes this unqualified-id.
Definition: DeclSpec.h:1021
iterator begin() const
Definition: Lookup.h:335
static const TSCS TSCS__Thread_local
Definition: DeclSpec.h:249
bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const
Definition: FormatToken.h:365
Callback handler that receives notifications when performing code completion within the preprocessor...
void * getAnnotationValue() const
Definition: Token.h:226
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition: DeclSpec.h:2558
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:642
void addAttributes(ParsedAttributesView &AL)
Concatenates two attribute lists.
Definition: DeclSpec.h:781
SourceLocation getBegin() const
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:824
void setCommaLoc(SourceLocation CL)
Definition: DeclSpec.h:2539
This class handles loading and caching of source files into memory.
ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-or-expression.
Definition: ParseExpr.cpp:349
ParamInfo * Params
Params - This is a pointer to a new[]&#39;d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1339
TypeResult ParseTypeName(SourceRange *Range=nullptr, DeclaratorContext Context=DeclaratorContext::TypeNameContext, AccessSpecifier AS=AS_none, Decl **OwnedType=nullptr, ParsedAttributes *Attrs=nullptr)
ParseTypeName type-name: [C99 6.7.6] specifier-qualifier-list abstract-declarator[opt].
Definition: ParseDecl.cpp:42
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:787
SourceLocation getLocation() const
Definition: DeclBase.h:429
void startToken()
Reset all flags to cleared.
Definition: Token.h:171
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:5406
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition: Decl.cpp:1790
static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS, unsigned TypeQuals, SourceLocation Loc)
Definition: DeclSpec.h:1661
bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:938
Stop skipping at specified token, but don&#39;t skip the token itself.
Definition: Parser.h:1100
unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template)
SourceLocation getEndLoc() const
Definition: Token.h:153