clang  12.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"
27 #include "llvm/ADT/Optional.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/StringSwitch.h"
31 
32 using namespace clang;
33 
34 //===----------------------------------------------------------------------===//
35 // C99 6.7: Declarations.
36 //===----------------------------------------------------------------------===//
37 
38 /// ParseTypeName
39 /// type-name: [C99 6.7.6]
40 /// specifier-qualifier-list abstract-declarator[opt]
41 ///
42 /// Called type-id in C++.
44  DeclaratorContext Context,
45  AccessSpecifier AS,
46  Decl **OwnedType,
47  ParsedAttributes *Attrs) {
48  DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
49  if (DSC == DeclSpecContext::DSC_normal)
50  DSC = DeclSpecContext::DSC_type_specifier;
51 
52  // Parse the common declaration-specifiers piece.
53  DeclSpec DS(AttrFactory);
54  if (Attrs)
55  DS.addAttributes(*Attrs);
56  ParseSpecifierQualifierList(DS, AS, DSC);
57  if (OwnedType)
58  *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
59 
60  // Parse the abstract-declarator, if present.
61  Declarator DeclaratorInfo(DS, Context);
62  ParseDeclarator(DeclaratorInfo);
63  if (Range)
64  *Range = DeclaratorInfo.getSourceRange();
65 
66  if (DeclaratorInfo.isInvalidType())
67  return true;
68 
69  return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
70 }
71 
72 /// Normalizes an attribute name by dropping prefixed and suffixed __.
73 static StringRef normalizeAttrName(StringRef Name) {
74  if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
75  return Name.drop_front(2).drop_back(2);
76  return Name;
77 }
78 
79 /// isAttributeLateParsed - Return true if the attribute has arguments that
80 /// require late parsing.
81 static bool isAttributeLateParsed(const IdentifierInfo &II) {
82 #define CLANG_ATTR_LATE_PARSED_LIST
83  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
84 #include "clang/Parse/AttrParserStringSwitches.inc"
85  .Default(false);
86 #undef CLANG_ATTR_LATE_PARSED_LIST
87 }
88 
89 /// Check if the a start and end source location expand to the same macro.
91  SourceLocation EndLoc) {
92  if (!StartLoc.isMacroID() || !EndLoc.isMacroID())
93  return false;
94 
96  if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
97  return false;
98 
99  bool AttrStartIsInMacro =
101  bool AttrEndIsInMacro =
103  return AttrStartIsInMacro && AttrEndIsInMacro;
104 }
105 
106 /// ParseGNUAttributes - Parse a non-empty attributes list.
107 ///
108 /// [GNU] attributes:
109 /// attribute
110 /// attributes attribute
111 ///
112 /// [GNU] attribute:
113 /// '__attribute__' '(' '(' attribute-list ')' ')'
114 ///
115 /// [GNU] attribute-list:
116 /// attrib
117 /// attribute_list ',' attrib
118 ///
119 /// [GNU] attrib:
120 /// empty
121 /// attrib-name
122 /// attrib-name '(' identifier ')'
123 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
124 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
125 ///
126 /// [GNU] attrib-name:
127 /// identifier
128 /// typespec
129 /// typequal
130 /// storageclass
131 ///
132 /// Whether an attribute takes an 'identifier' is determined by the
133 /// attrib-name. GCC's behavior here is not worth imitating:
134 ///
135 /// * In C mode, if the attribute argument list starts with an identifier
136 /// followed by a ',' or an ')', and the identifier doesn't resolve to
137 /// a type, it is parsed as an identifier. If the attribute actually
138 /// wanted an expression, it's out of luck (but it turns out that no
139 /// attributes work that way, because C constant expressions are very
140 /// limited).
141 /// * In C++ mode, if the attribute argument list starts with an identifier,
142 /// and the attribute *wants* an identifier, it is parsed as an identifier.
143 /// At block scope, any additional tokens between the identifier and the
144 /// ',' or ')' are ignored, otherwise they produce a parse error.
145 ///
146 /// We follow the C++ model, but don't allow junk after the identifier.
147 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
148  SourceLocation *endLoc,
149  LateParsedAttrList *LateAttrs,
150  Declarator *D) {
151  assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
152 
153  while (Tok.is(tok::kw___attribute)) {
154  SourceLocation AttrTokLoc = ConsumeToken();
155  unsigned OldNumAttrs = attrs.size();
156  unsigned OldNumLateAttrs = LateAttrs ? LateAttrs->size() : 0;
157 
158  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
159  "attribute")) {
160  SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
161  return;
162  }
163  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
164  SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
165  return;
166  }
167  // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
168  do {
169  // Eat preceeding commas to allow __attribute__((,,,foo))
170  while (TryConsumeToken(tok::comma))
171  ;
172 
173  // Expect an identifier or declaration specifier (const, int, etc.)
174  if (Tok.isAnnotation())
175  break;
176  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
177  if (!AttrName)
178  break;
179 
180  SourceLocation AttrNameLoc = ConsumeToken();
181 
182  if (Tok.isNot(tok::l_paren)) {
183  attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
185  continue;
186  }
187 
188  // Handle "parameterized" attributes
189  if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
190  ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
192  continue;
193  }
194 
195  // Handle attributes with arguments that require late parsing.
196  LateParsedAttribute *LA =
197  new LateParsedAttribute(this, *AttrName, AttrNameLoc);
198  LateAttrs->push_back(LA);
199 
200  // Attributes in a class are parsed at the end of the class, along
201  // with other late-parsed declarations.
202  if (!ClassStack.empty() && !LateAttrs->parseSoon())
203  getCurrentClass().LateParsedDeclarations.push_back(LA);
204 
205  // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
206  // recursively consumes balanced parens.
207  LA->Toks.push_back(Tok);
208  ConsumeParen();
209  // Consume everything up to and including the matching right parens.
210  ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
211 
212  Token Eof;
213  Eof.startToken();
214  Eof.setLocation(Tok.getLocation());
215  LA->Toks.push_back(Eof);
216  } while (Tok.is(tok::comma));
217 
218  if (ExpectAndConsume(tok::r_paren))
219  SkipUntil(tok::r_paren, StopAtSemi);
220  SourceLocation Loc = Tok.getLocation();
221  if (ExpectAndConsume(tok::r_paren))
222  SkipUntil(tok::r_paren, StopAtSemi);
223  if (endLoc)
224  *endLoc = Loc;
225 
226  // If this was declared in a macro, attach the macro IdentifierInfo to the
227  // parsed attribute.
228  auto &SM = PP.getSourceManager();
229  if (!SM.isWrittenInBuiltinFile(SM.getSpellingLoc(AttrTokLoc)) &&
230  FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)) {
231  CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
232  StringRef FoundName =
233  Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
234  IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
235 
236  for (unsigned i = OldNumAttrs; i < attrs.size(); ++i)
237  attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
238 
239  if (LateAttrs) {
240  for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); ++i)
241  (*LateAttrs)[i]->MacroII = MacroII;
242  }
243  }
244  }
245 }
246 
247 /// Determine whether the given attribute has an identifier argument.
249 #define CLANG_ATTR_IDENTIFIER_ARG_LIST
250  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
251 #include "clang/Parse/AttrParserStringSwitches.inc"
252  .Default(false);
253 #undef CLANG_ATTR_IDENTIFIER_ARG_LIST
254 }
255 
256 /// Determine whether the given attribute has a variadic identifier argument.
258 #define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
259  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
260 #include "clang/Parse/AttrParserStringSwitches.inc"
261  .Default(false);
262 #undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
263 }
264 
265 /// Determine whether the given attribute treats kw_this as an identifier.
267 #define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
268  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
269 #include "clang/Parse/AttrParserStringSwitches.inc"
270  .Default(false);
271 #undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
272 }
273 
274 /// Determine whether the given attribute parses a type argument.
275 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
276 #define CLANG_ATTR_TYPE_ARG_LIST
277  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
278 #include "clang/Parse/AttrParserStringSwitches.inc"
279  .Default(false);
280 #undef CLANG_ATTR_TYPE_ARG_LIST
281 }
282 
283 /// Determine whether the given attribute requires parsing its arguments
284 /// in an unevaluated context or not.
286 #define CLANG_ATTR_ARG_CONTEXT_LIST
287  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
288 #include "clang/Parse/AttrParserStringSwitches.inc"
289  .Default(false);
290 #undef CLANG_ATTR_ARG_CONTEXT_LIST
291 }
292 
293 IdentifierLoc *Parser::ParseIdentifierLoc() {
294  assert(Tok.is(tok::identifier) && "expected an identifier");
296  Tok.getLocation(),
297  Tok.getIdentifierInfo());
298  ConsumeToken();
299  return IL;
300 }
301 
302 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
303  SourceLocation AttrNameLoc,
304  ParsedAttributes &Attrs,
305  SourceLocation *EndLoc,
306  IdentifierInfo *ScopeName,
307  SourceLocation ScopeLoc,
308  ParsedAttr::Syntax Syntax) {
309  BalancedDelimiterTracker Parens(*this, tok::l_paren);
310  Parens.consumeOpen();
311 
312  TypeResult T;
313  if (Tok.isNot(tok::r_paren))
314  T = ParseTypeName();
315 
316  if (Parens.consumeClose())
317  return;
318 
319  if (T.isInvalid())
320  return;
321 
322  if (T.isUsable())
323  Attrs.addNewTypeAttr(&AttrName,
324  SourceRange(AttrNameLoc, Parens.getCloseLocation()),
325  ScopeName, ScopeLoc, T.get(), Syntax);
326  else
327  Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
328  ScopeName, ScopeLoc, nullptr, 0, Syntax);
329 }
330 
331 unsigned Parser::ParseAttributeArgsCommon(
332  IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
333  ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
334  SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
335  // Ignore the left paren location for now.
336  ConsumeParen();
337 
338  bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
339  bool AttributeIsTypeArgAttr = attributeIsTypeArgAttr(*AttrName);
340 
341  // Interpret "kw_this" as an identifier if the attributed requests it.
342  if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
343  Tok.setKind(tok::identifier);
344 
345  ArgsVector ArgExprs;
346  if (Tok.is(tok::identifier)) {
347  // If this attribute wants an 'identifier' argument, make it so.
348  bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName) ||
350  ParsedAttr::Kind AttrKind =
351  ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
352 
353  // If we don't know how to parse this attribute, but this is the only
354  // token in this argument, assume it's meant to be an identifier.
355  if (AttrKind == ParsedAttr::UnknownAttribute ||
356  AttrKind == ParsedAttr::IgnoredAttribute) {
357  const Token &Next = NextToken();
358  IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
359  }
360 
361  if (IsIdentifierArg)
362  ArgExprs.push_back(ParseIdentifierLoc());
363  }
364 
365  ParsedType TheParsedType;
366  if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
367  // Eat the comma.
368  if (!ArgExprs.empty())
369  ConsumeToken();
370 
371  // Parse the non-empty comma-separated list of expressions.
372  do {
373  // Interpret "kw_this" as an identifier if the attributed requests it.
374  if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
375  Tok.setKind(tok::identifier);
376 
377  ExprResult ArgExpr;
378  if (AttributeIsTypeArgAttr) {
380  if (T.isInvalid()) {
381  SkipUntil(tok::r_paren, StopAtSemi);
382  return 0;
383  }
384  if (T.isUsable())
385  TheParsedType = T.get();
386  break; // FIXME: Multiple type arguments are not implemented.
387  } else if (Tok.is(tok::identifier) &&
389  ArgExprs.push_back(ParseIdentifierLoc());
390  } else {
391  bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
393  Actions,
396 
397  ExprResult ArgExpr(
399  if (ArgExpr.isInvalid()) {
400  SkipUntil(tok::r_paren, StopAtSemi);
401  return 0;
402  }
403  ArgExprs.push_back(ArgExpr.get());
404  }
405  // Eat the comma, move to the next argument
406  } while (TryConsumeToken(tok::comma));
407  }
408 
409  SourceLocation RParen = Tok.getLocation();
410  if (!ExpectAndConsume(tok::r_paren)) {
411  SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
412 
413  if (AttributeIsTypeArgAttr && !TheParsedType.get().isNull()) {
414  Attrs.addNewTypeAttr(AttrName, SourceRange(AttrNameLoc, RParen),
415  ScopeName, ScopeLoc, TheParsedType, Syntax);
416  } else {
417  Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
418  ArgExprs.data(), ArgExprs.size(), Syntax);
419  }
420  }
421 
422  if (EndLoc)
423  *EndLoc = RParen;
424 
425  return static_cast<unsigned>(ArgExprs.size() + !TheParsedType.get().isNull());
426 }
427 
428 /// Parse the arguments to a parameterized GNU attribute or
429 /// a C++11 attribute in "gnu" namespace.
430 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
431  SourceLocation AttrNameLoc,
432  ParsedAttributes &Attrs,
433  SourceLocation *EndLoc,
434  IdentifierInfo *ScopeName,
435  SourceLocation ScopeLoc,
436  ParsedAttr::Syntax Syntax,
437  Declarator *D) {
438 
439  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
440 
441  ParsedAttr::Kind AttrKind =
442  ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
443 
444  if (AttrKind == ParsedAttr::AT_Availability) {
445  ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
446  ScopeLoc, Syntax);
447  return;
448  } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
449  ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
450  ScopeName, ScopeLoc, Syntax);
451  return;
452  } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
453  ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
454  ScopeName, ScopeLoc, Syntax);
455  return;
456  } else if (AttrKind == ParsedAttr::AT_SwiftNewType) {
457  ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
458  ScopeLoc, Syntax);
459  return;
460  } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
461  ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
462  ScopeName, ScopeLoc, Syntax);
463  return;
464  } else if (attributeIsTypeArgAttr(*AttrName)) {
465  ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
466  ScopeLoc, Syntax);
467  return;
468  }
469 
470  // These may refer to the function arguments, but need to be parsed early to
471  // participate in determining whether it's a redeclaration.
472  llvm::Optional<ParseScope> PrototypeScope;
473  if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
474  D && D->isFunctionDeclarator()) {
476  PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
479  for (unsigned i = 0; i != FTI.NumParams; ++i) {
480  ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
482  }
483  }
484 
485  ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
486  ScopeLoc, Syntax);
487 }
488 
489 unsigned Parser::ParseClangAttributeArgs(
490  IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
491  ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
492  SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
493  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
494 
495  ParsedAttr::Kind AttrKind =
496  ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
497 
498  switch (AttrKind) {
499  default:
500  return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
501  ScopeName, ScopeLoc, Syntax);
502  case ParsedAttr::AT_ExternalSourceSymbol:
503  ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
504  ScopeName, ScopeLoc, Syntax);
505  break;
506  case ParsedAttr::AT_Availability:
507  ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
508  ScopeLoc, Syntax);
509  break;
510  case ParsedAttr::AT_ObjCBridgeRelated:
511  ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
512  ScopeName, ScopeLoc, Syntax);
513  break;
514  case ParsedAttr::AT_SwiftNewType:
515  ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
516  ScopeLoc, Syntax);
517  break;
518  case ParsedAttr::AT_TypeTagForDatatype:
519  ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
520  ScopeName, ScopeLoc, Syntax);
521  break;
522  }
523  return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
524 }
525 
526 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
527  SourceLocation AttrNameLoc,
528  ParsedAttributes &Attrs) {
529  // If the attribute isn't known, we will not attempt to parse any
530  // arguments.
531  if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
532  getTargetInfo(), getLangOpts())) {
533  // Eat the left paren, then skip to the ending right paren.
534  ConsumeParen();
535  SkipUntil(tok::r_paren);
536  return false;
537  }
538 
539  SourceLocation OpenParenLoc = Tok.getLocation();
540 
541  if (AttrName->getName() == "property") {
542  // The property declspec is more complex in that it can take one or two
543  // assignment expressions as a parameter, but the lhs of the assignment
544  // must be named get or put.
545 
546  BalancedDelimiterTracker T(*this, tok::l_paren);
547  T.expectAndConsume(diag::err_expected_lparen_after,
548  AttrName->getNameStart(), tok::r_paren);
549 
550  enum AccessorKind {
551  AK_Invalid = -1,
552  AK_Put = 0,
553  AK_Get = 1 // indices into AccessorNames
554  };
555  IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
556  bool HasInvalidAccessor = false;
557 
558  // Parse the accessor specifications.
559  while (true) {
560  // Stop if this doesn't look like an accessor spec.
561  if (!Tok.is(tok::identifier)) {
562  // If the user wrote a completely empty list, use a special diagnostic.
563  if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
564  AccessorNames[AK_Put] == nullptr &&
565  AccessorNames[AK_Get] == nullptr) {
566  Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
567  break;
568  }
569 
570  Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
571  break;
572  }
573 
574  AccessorKind Kind;
575  SourceLocation KindLoc = Tok.getLocation();
576  StringRef KindStr = Tok.getIdentifierInfo()->getName();
577  if (KindStr == "get") {
578  Kind = AK_Get;
579  } else if (KindStr == "put") {
580  Kind = AK_Put;
581 
582  // Recover from the common mistake of using 'set' instead of 'put'.
583  } else if (KindStr == "set") {
584  Diag(KindLoc, diag::err_ms_property_has_set_accessor)
585  << FixItHint::CreateReplacement(KindLoc, "put");
586  Kind = AK_Put;
587 
588  // Handle the mistake of forgetting the accessor kind by skipping
589  // this accessor.
590  } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
591  Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
592  ConsumeToken();
593  HasInvalidAccessor = true;
594  goto next_property_accessor;
595 
596  // Otherwise, complain about the unknown accessor kind.
597  } else {
598  Diag(KindLoc, diag::err_ms_property_unknown_accessor);
599  HasInvalidAccessor = true;
600  Kind = AK_Invalid;
601 
602  // Try to keep parsing unless it doesn't look like an accessor spec.
603  if (!NextToken().is(tok::equal))
604  break;
605  }
606 
607  // Consume the identifier.
608  ConsumeToken();
609 
610  // Consume the '='.
611  if (!TryConsumeToken(tok::equal)) {
612  Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
613  << KindStr;
614  break;
615  }
616 
617  // Expect the method name.
618  if (!Tok.is(tok::identifier)) {
619  Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
620  break;
621  }
622 
623  if (Kind == AK_Invalid) {
624  // Just drop invalid accessors.
625  } else if (AccessorNames[Kind] != nullptr) {
626  // Complain about the repeated accessor, ignore it, and keep parsing.
627  Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
628  } else {
629  AccessorNames[Kind] = Tok.getIdentifierInfo();
630  }
631  ConsumeToken();
632 
633  next_property_accessor:
634  // Keep processing accessors until we run out.
635  if (TryConsumeToken(tok::comma))
636  continue;
637 
638  // If we run into the ')', stop without consuming it.
639  if (Tok.is(tok::r_paren))
640  break;
641 
642  Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
643  break;
644  }
645 
646  // Only add the property attribute if it was well-formed.
647  if (!HasInvalidAccessor)
648  Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
649  AccessorNames[AK_Get], AccessorNames[AK_Put],
651  T.skipToEnd();
652  return !HasInvalidAccessor;
653  }
654 
655  unsigned NumArgs =
656  ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
658 
659  // If this attribute's args were parsed, and it was expected to have
660  // arguments but none were provided, emit a diagnostic.
661  if (!Attrs.empty() && Attrs.begin()->getMaxArgs() && !NumArgs) {
662  Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
663  return false;
664  }
665  return true;
666 }
667 
668 /// [MS] decl-specifier:
669 /// __declspec ( extended-decl-modifier-seq )
670 ///
671 /// [MS] extended-decl-modifier-seq:
672 /// extended-decl-modifier[opt]
673 /// extended-decl-modifier extended-decl-modifier-seq
674 void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
675  SourceLocation *End) {
676  assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
677  assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
678 
679  while (Tok.is(tok::kw___declspec)) {
680  ConsumeToken();
681  BalancedDelimiterTracker T(*this, tok::l_paren);
682  if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
683  tok::r_paren))
684  return;
685 
686  // An empty declspec is perfectly legal and should not warn. Additionally,
687  // you can specify multiple attributes per declspec.
688  while (Tok.isNot(tok::r_paren)) {
689  // Attribute not present.
690  if (TryConsumeToken(tok::comma))
691  continue;
692 
693  // We expect either a well-known identifier or a generic string. Anything
694  // else is a malformed declspec.
695  bool IsString = Tok.getKind() == tok::string_literal;
696  if (!IsString && Tok.getKind() != tok::identifier &&
697  Tok.getKind() != tok::kw_restrict) {
698  Diag(Tok, diag::err_ms_declspec_type);
699  T.skipToEnd();
700  return;
701  }
702 
703  IdentifierInfo *AttrName;
704  SourceLocation AttrNameLoc;
705  if (IsString) {
706  SmallString<8> StrBuffer;
707  bool Invalid = false;
708  StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
709  if (Invalid) {
710  T.skipToEnd();
711  return;
712  }
713  AttrName = PP.getIdentifierInfo(Str);
714  AttrNameLoc = ConsumeStringToken();
715  } else {
716  AttrName = Tok.getIdentifierInfo();
717  AttrNameLoc = ConsumeToken();
718  }
719 
720  bool AttrHandled = false;
721 
722  // Parse attribute arguments.
723  if (Tok.is(tok::l_paren))
724  AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
725  else if (AttrName->getName() == "property")
726  // The property attribute must have an argument list.
727  Diag(Tok.getLocation(), diag::err_expected_lparen_after)
728  << AttrName->getName();
729 
730  if (!AttrHandled)
731  Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
733  }
734  T.consumeClose();
735  if (End)
736  *End = T.getCloseLocation();
737  }
738 }
739 
740 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
741  // Treat these like attributes
742  while (true) {
743  switch (Tok.getKind()) {
744  case tok::kw___fastcall:
745  case tok::kw___stdcall:
746  case tok::kw___thiscall:
747  case tok::kw___regcall:
748  case tok::kw___cdecl:
749  case tok::kw___vectorcall:
750  case tok::kw___ptr64:
751  case tok::kw___w64:
752  case tok::kw___ptr32:
753  case tok::kw___sptr:
754  case tok::kw___uptr: {
755  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
756  SourceLocation AttrNameLoc = ConsumeToken();
757  attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
759  break;
760  }
761  default:
762  return;
763  }
764  }
765 }
766 
767 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
768  SourceLocation StartLoc = Tok.getLocation();
769  SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
770 
771  if (EndLoc.isValid()) {
772  SourceRange Range(StartLoc, EndLoc);
773  Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
774  }
775 }
776 
777 SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
778  SourceLocation EndLoc;
779 
780  while (true) {
781  switch (Tok.getKind()) {
782  case tok::kw_const:
783  case tok::kw_volatile:
784  case tok::kw___fastcall:
785  case tok::kw___stdcall:
786  case tok::kw___thiscall:
787  case tok::kw___cdecl:
788  case tok::kw___vectorcall:
789  case tok::kw___ptr32:
790  case tok::kw___ptr64:
791  case tok::kw___w64:
792  case tok::kw___unaligned:
793  case tok::kw___sptr:
794  case tok::kw___uptr:
795  EndLoc = ConsumeToken();
796  break;
797  default:
798  return EndLoc;
799  }
800  }
801 }
802 
803 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
804  // Treat these like attributes
805  while (Tok.is(tok::kw___pascal)) {
806  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
807  SourceLocation AttrNameLoc = ConsumeToken();
808  attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
810  }
811 }
812 
813 void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
814  // Treat these like attributes
815  while (Tok.is(tok::kw___kernel)) {
816  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
817  SourceLocation AttrNameLoc = ConsumeToken();
818  attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
820  }
821 }
822 
823 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
824  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
825  SourceLocation AttrNameLoc = Tok.getLocation();
826  Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
828 }
829 
830 void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
831  // Treat these like attributes, even though they're type specifiers.
832  while (true) {
833  switch (Tok.getKind()) {
834  case tok::kw__Nonnull:
835  case tok::kw__Nullable:
836  case tok::kw__Null_unspecified: {
837  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
838  SourceLocation AttrNameLoc = ConsumeToken();
839  if (!getLangOpts().ObjC)
840  Diag(AttrNameLoc, diag::ext_nullability)
841  << AttrName;
842  attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
844  break;
845  }
846  default:
847  return;
848  }
849  }
850 }
851 
852 static bool VersionNumberSeparator(const char Separator) {
853  return (Separator == '.' || Separator == '_');
854 }
855 
856 /// Parse a version number.
857 ///
858 /// version:
859 /// simple-integer
860 /// simple-integer '.' simple-integer
861 /// simple-integer '_' simple-integer
862 /// simple-integer '.' simple-integer '.' simple-integer
863 /// simple-integer '_' simple-integer '_' simple-integer
864 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
865  Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
866 
867  if (!Tok.is(tok::numeric_constant)) {
868  Diag(Tok, diag::err_expected_version);
869  SkipUntil(tok::comma, tok::r_paren,
871  return VersionTuple();
872  }
873 
874  // Parse the major (and possibly minor and subminor) versions, which
875  // are stored in the numeric constant. We utilize a quirk of the
876  // lexer, which is that it handles something like 1.2.3 as a single
877  // numeric constant, rather than two separate tokens.
878  SmallString<512> Buffer;
879  Buffer.resize(Tok.getLength()+1);
880  const char *ThisTokBegin = &Buffer[0];
881 
882  // Get the spelling of the token, which eliminates trigraphs, etc.
883  bool Invalid = false;
884  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
885  if (Invalid)
886  return VersionTuple();
887 
888  // Parse the major version.
889  unsigned AfterMajor = 0;
890  unsigned Major = 0;
891  while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
892  Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
893  ++AfterMajor;
894  }
895 
896  if (AfterMajor == 0) {
897  Diag(Tok, diag::err_expected_version);
898  SkipUntil(tok::comma, tok::r_paren,
900  return VersionTuple();
901  }
902 
903  if (AfterMajor == ActualLength) {
904  ConsumeToken();
905 
906  // We only had a single version component.
907  if (Major == 0) {
908  Diag(Tok, diag::err_zero_version);
909  return VersionTuple();
910  }
911 
912  return VersionTuple(Major);
913  }
914 
915  const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
916  if (!VersionNumberSeparator(AfterMajorSeparator)
917  || (AfterMajor + 1 == ActualLength)) {
918  Diag(Tok, diag::err_expected_version);
919  SkipUntil(tok::comma, tok::r_paren,
921  return VersionTuple();
922  }
923 
924  // Parse the minor version.
925  unsigned AfterMinor = AfterMajor + 1;
926  unsigned Minor = 0;
927  while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
928  Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
929  ++AfterMinor;
930  }
931 
932  if (AfterMinor == ActualLength) {
933  ConsumeToken();
934 
935  // We had major.minor.
936  if (Major == 0 && Minor == 0) {
937  Diag(Tok, diag::err_zero_version);
938  return VersionTuple();
939  }
940 
941  return VersionTuple(Major, Minor);
942  }
943 
944  const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
945  // If what follows is not a '.' or '_', we have a problem.
946  if (!VersionNumberSeparator(AfterMinorSeparator)) {
947  Diag(Tok, diag::err_expected_version);
948  SkipUntil(tok::comma, tok::r_paren,
950  return VersionTuple();
951  }
952 
953  // Warn if separators, be it '.' or '_', do not match.
954  if (AfterMajorSeparator != AfterMinorSeparator)
955  Diag(Tok, diag::warn_expected_consistent_version_separator);
956 
957  // Parse the subminor version.
958  unsigned AfterSubminor = AfterMinor + 1;
959  unsigned Subminor = 0;
960  while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
961  Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
962  ++AfterSubminor;
963  }
964 
965  if (AfterSubminor != ActualLength) {
966  Diag(Tok, diag::err_expected_version);
967  SkipUntil(tok::comma, tok::r_paren,
969  return VersionTuple();
970  }
971  ConsumeToken();
972  return VersionTuple(Major, Minor, Subminor);
973 }
974 
975 /// Parse the contents of the "availability" attribute.
976 ///
977 /// availability-attribute:
978 /// 'availability' '(' platform ',' opt-strict version-arg-list,
979 /// opt-replacement, opt-message')'
980 ///
981 /// platform:
982 /// identifier
983 ///
984 /// opt-strict:
985 /// 'strict' ','
986 ///
987 /// version-arg-list:
988 /// version-arg
989 /// version-arg ',' version-arg-list
990 ///
991 /// version-arg:
992 /// 'introduced' '=' version
993 /// 'deprecated' '=' version
994 /// 'obsoleted' = version
995 /// 'unavailable'
996 /// opt-replacement:
997 /// 'replacement' '=' <string>
998 /// opt-message:
999 /// 'message' '=' <string>
1000 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
1001  SourceLocation AvailabilityLoc,
1002  ParsedAttributes &attrs,
1003  SourceLocation *endLoc,
1004  IdentifierInfo *ScopeName,
1005  SourceLocation ScopeLoc,
1006  ParsedAttr::Syntax Syntax) {
1007  enum { Introduced, Deprecated, Obsoleted, Unknown };
1008  AvailabilityChange Changes[Unknown];
1009  ExprResult MessageExpr, ReplacementExpr;
1010 
1011  // Opening '('.
1012  BalancedDelimiterTracker T(*this, tok::l_paren);
1013  if (T.consumeOpen()) {
1014  Diag(Tok, diag::err_expected) << tok::l_paren;
1015  return;
1016  }
1017 
1018  // Parse the platform name.
1019  if (Tok.isNot(tok::identifier)) {
1020  Diag(Tok, diag::err_availability_expected_platform);
1021  SkipUntil(tok::r_paren, StopAtSemi);
1022  return;
1023  }
1024  IdentifierLoc *Platform = ParseIdentifierLoc();
1025  if (const IdentifierInfo *const Ident = Platform->Ident) {
1026  // Canonicalize platform name from "macosx" to "macos".
1027  if (Ident->getName() == "macosx")
1028  Platform->Ident = PP.getIdentifierInfo("macos");
1029  // Canonicalize platform name from "macosx_app_extension" to
1030  // "macos_app_extension".
1031  else if (Ident->getName() == "macosx_app_extension")
1032  Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1033  else
1034  Platform->Ident = PP.getIdentifierInfo(
1035  AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1036  }
1037 
1038  // Parse the ',' following the platform name.
1039  if (ExpectAndConsume(tok::comma)) {
1040  SkipUntil(tok::r_paren, StopAtSemi);
1041  return;
1042  }
1043 
1044  // If we haven't grabbed the pointers for the identifiers
1045  // "introduced", "deprecated", and "obsoleted", do so now.
1046  if (!Ident_introduced) {
1047  Ident_introduced = PP.getIdentifierInfo("introduced");
1048  Ident_deprecated = PP.getIdentifierInfo("deprecated");
1049  Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
1050  Ident_unavailable = PP.getIdentifierInfo("unavailable");
1051  Ident_message = PP.getIdentifierInfo("message");
1052  Ident_strict = PP.getIdentifierInfo("strict");
1053  Ident_replacement = PP.getIdentifierInfo("replacement");
1054  }
1055 
1056  // Parse the optional "strict", the optional "replacement" and the set of
1057  // introductions/deprecations/removals.
1058  SourceLocation UnavailableLoc, StrictLoc;
1059  do {
1060  if (Tok.isNot(tok::identifier)) {
1061  Diag(Tok, diag::err_availability_expected_change);
1062  SkipUntil(tok::r_paren, StopAtSemi);
1063  return;
1064  }
1065  IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1066  SourceLocation KeywordLoc = ConsumeToken();
1067 
1068  if (Keyword == Ident_strict) {
1069  if (StrictLoc.isValid()) {
1070  Diag(KeywordLoc, diag::err_availability_redundant)
1071  << Keyword << SourceRange(StrictLoc);
1072  }
1073  StrictLoc = KeywordLoc;
1074  continue;
1075  }
1076 
1077  if (Keyword == Ident_unavailable) {
1078  if (UnavailableLoc.isValid()) {
1079  Diag(KeywordLoc, diag::err_availability_redundant)
1080  << Keyword << SourceRange(UnavailableLoc);
1081  }
1082  UnavailableLoc = KeywordLoc;
1083  continue;
1084  }
1085 
1086  if (Keyword == Ident_deprecated && Platform->Ident &&
1087  Platform->Ident->isStr("swift")) {
1088  // For swift, we deprecate for all versions.
1089  if (Changes[Deprecated].KeywordLoc.isValid()) {
1090  Diag(KeywordLoc, diag::err_availability_redundant)
1091  << Keyword
1092  << SourceRange(Changes[Deprecated].KeywordLoc);
1093  }
1094 
1095  Changes[Deprecated].KeywordLoc = KeywordLoc;
1096  // Use a fake version here.
1097  Changes[Deprecated].Version = VersionTuple(1);
1098  continue;
1099  }
1100 
1101  if (Tok.isNot(tok::equal)) {
1102  Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1103  SkipUntil(tok::r_paren, StopAtSemi);
1104  return;
1105  }
1106  ConsumeToken();
1107  if (Keyword == Ident_message || Keyword == Ident_replacement) {
1108  if (Tok.isNot(tok::string_literal)) {
1109  Diag(Tok, diag::err_expected_string_literal)
1110  << /*Source='availability attribute'*/2;
1111  SkipUntil(tok::r_paren, StopAtSemi);
1112  return;
1113  }
1114  if (Keyword == Ident_message)
1115  MessageExpr = ParseStringLiteralExpression();
1116  else
1117  ReplacementExpr = ParseStringLiteralExpression();
1118  // Also reject wide string literals.
1119  if (StringLiteral *MessageStringLiteral =
1120  cast_or_null<StringLiteral>(MessageExpr.get())) {
1121  if (MessageStringLiteral->getCharByteWidth() != 1) {
1122  Diag(MessageStringLiteral->getSourceRange().getBegin(),
1123  diag::err_expected_string_literal)
1124  << /*Source='availability attribute'*/ 2;
1125  SkipUntil(tok::r_paren, StopAtSemi);
1126  return;
1127  }
1128  }
1129  if (Keyword == Ident_message)
1130  break;
1131  else
1132  continue;
1133  }
1134 
1135  // Special handling of 'NA' only when applied to introduced or
1136  // deprecated.
1137  if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1138  Tok.is(tok::identifier)) {
1139  IdentifierInfo *NA = Tok.getIdentifierInfo();
1140  if (NA->getName() == "NA") {
1141  ConsumeToken();
1142  if (Keyword == Ident_introduced)
1143  UnavailableLoc = KeywordLoc;
1144  continue;
1145  }
1146  }
1147 
1148  SourceRange VersionRange;
1149  VersionTuple Version = ParseVersionTuple(VersionRange);
1150 
1151  if (Version.empty()) {
1152  SkipUntil(tok::r_paren, StopAtSemi);
1153  return;
1154  }
1155 
1156  unsigned Index;
1157  if (Keyword == Ident_introduced)
1158  Index = Introduced;
1159  else if (Keyword == Ident_deprecated)
1160  Index = Deprecated;
1161  else if (Keyword == Ident_obsoleted)
1162  Index = Obsoleted;
1163  else
1164  Index = Unknown;
1165 
1166  if (Index < Unknown) {
1167  if (!Changes[Index].KeywordLoc.isInvalid()) {
1168  Diag(KeywordLoc, diag::err_availability_redundant)
1169  << Keyword
1170  << SourceRange(Changes[Index].KeywordLoc,
1171  Changes[Index].VersionRange.getEnd());
1172  }
1173 
1174  Changes[Index].KeywordLoc = KeywordLoc;
1175  Changes[Index].Version = Version;
1176  Changes[Index].VersionRange = VersionRange;
1177  } else {
1178  Diag(KeywordLoc, diag::err_availability_unknown_change)
1179  << Keyword << VersionRange;
1180  }
1181 
1182  } while (TryConsumeToken(tok::comma));
1183 
1184  // Closing ')'.
1185  if (T.consumeClose())
1186  return;
1187 
1188  if (endLoc)
1189  *endLoc = T.getCloseLocation();
1190 
1191  // The 'unavailable' availability cannot be combined with any other
1192  // availability changes. Make sure that hasn't happened.
1193  if (UnavailableLoc.isValid()) {
1194  bool Complained = false;
1195  for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1196  if (Changes[Index].KeywordLoc.isValid()) {
1197  if (!Complained) {
1198  Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1199  << SourceRange(Changes[Index].KeywordLoc,
1200  Changes[Index].VersionRange.getEnd());
1201  Complained = true;
1202  }
1203 
1204  // Clear out the availability.
1205  Changes[Index] = AvailabilityChange();
1206  }
1207  }
1208  }
1209 
1210  // Record this attribute
1211  attrs.addNew(&Availability,
1212  SourceRange(AvailabilityLoc, T.getCloseLocation()),
1213  ScopeName, ScopeLoc,
1214  Platform,
1215  Changes[Introduced],
1216  Changes[Deprecated],
1217  Changes[Obsoleted],
1218  UnavailableLoc, MessageExpr.get(),
1219  Syntax, StrictLoc, ReplacementExpr.get());
1220 }
1221 
1222 /// Parse the contents of the "external_source_symbol" attribute.
1223 ///
1224 /// external-source-symbol-attribute:
1225 /// 'external_source_symbol' '(' keyword-arg-list ')'
1226 ///
1227 /// keyword-arg-list:
1228 /// keyword-arg
1229 /// keyword-arg ',' keyword-arg-list
1230 ///
1231 /// keyword-arg:
1232 /// 'language' '=' <string>
1233 /// 'defined_in' '=' <string>
1234 /// 'generated_declaration'
1235 void Parser::ParseExternalSourceSymbolAttribute(
1236  IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1237  ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1238  SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1239  // Opening '('.
1240  BalancedDelimiterTracker T(*this, tok::l_paren);
1241  if (T.expectAndConsume())
1242  return;
1243 
1244  // Initialize the pointers for the keyword identifiers when required.
1245  if (!Ident_language) {
1246  Ident_language = PP.getIdentifierInfo("language");
1247  Ident_defined_in = PP.getIdentifierInfo("defined_in");
1248  Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1249  }
1250 
1252  bool HasLanguage = false;
1253  ExprResult DefinedInExpr;
1254  bool HasDefinedIn = false;
1255  IdentifierLoc *GeneratedDeclaration = nullptr;
1256 
1257  // Parse the language/defined_in/generated_declaration keywords
1258  do {
1259  if (Tok.isNot(tok::identifier)) {
1260  Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1261  SkipUntil(tok::r_paren, StopAtSemi);
1262  return;
1263  }
1264 
1265  SourceLocation KeywordLoc = Tok.getLocation();
1266  IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1267  if (Keyword == Ident_generated_declaration) {
1268  if (GeneratedDeclaration) {
1269  Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1270  SkipUntil(tok::r_paren, StopAtSemi);
1271  return;
1272  }
1273  GeneratedDeclaration = ParseIdentifierLoc();
1274  continue;
1275  }
1276 
1277  if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1278  Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1279  SkipUntil(tok::r_paren, StopAtSemi);
1280  return;
1281  }
1282 
1283  ConsumeToken();
1284  if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1285  Keyword->getName())) {
1286  SkipUntil(tok::r_paren, StopAtSemi);
1287  return;
1288  }
1289 
1290  bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1291  if (Keyword == Ident_language)
1292  HasLanguage = true;
1293  else
1294  HasDefinedIn = true;
1295 
1296  if (Tok.isNot(tok::string_literal)) {
1297  Diag(Tok, diag::err_expected_string_literal)
1298  << /*Source='external_source_symbol attribute'*/ 3
1299  << /*language | source container*/ (Keyword != Ident_language);
1300  SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1301  continue;
1302  }
1303  if (Keyword == Ident_language) {
1304  if (HadLanguage) {
1305  Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1306  << Keyword;
1308  continue;
1309  }
1311  } else {
1312  assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1313  if (HadDefinedIn) {
1314  Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1315  << Keyword;
1317  continue;
1318  }
1319  DefinedInExpr = ParseStringLiteralExpression();
1320  }
1321  } while (TryConsumeToken(tok::comma));
1322 
1323  // Closing ')'.
1324  if (T.consumeClose())
1325  return;
1326  if (EndLoc)
1327  *EndLoc = T.getCloseLocation();
1328 
1329  ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1330  GeneratedDeclaration};
1331  Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1332  ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1333 }
1334 
1335 /// Parse the contents of the "objc_bridge_related" attribute.
1336 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1337 /// related_class:
1338 /// Identifier
1339 ///
1340 /// opt-class_method:
1341 /// Identifier: | <empty>
1342 ///
1343 /// opt-instance_method:
1344 /// Identifier | <empty>
1345 ///
1346 void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1347  SourceLocation ObjCBridgeRelatedLoc,
1348  ParsedAttributes &attrs,
1349  SourceLocation *endLoc,
1350  IdentifierInfo *ScopeName,
1351  SourceLocation ScopeLoc,
1352  ParsedAttr::Syntax Syntax) {
1353  // Opening '('.
1354  BalancedDelimiterTracker T(*this, tok::l_paren);
1355  if (T.consumeOpen()) {
1356  Diag(Tok, diag::err_expected) << tok::l_paren;
1357  return;
1358  }
1359 
1360  // Parse the related class name.
1361  if (Tok.isNot(tok::identifier)) {
1362  Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1363  SkipUntil(tok::r_paren, StopAtSemi);
1364  return;
1365  }
1366  IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1367  if (ExpectAndConsume(tok::comma)) {
1368  SkipUntil(tok::r_paren, StopAtSemi);
1369  return;
1370  }
1371 
1372  // Parse class method name. It's non-optional in the sense that a trailing
1373  // comma is required, but it can be the empty string, and then we record a
1374  // nullptr.
1375  IdentifierLoc *ClassMethod = nullptr;
1376  if (Tok.is(tok::identifier)) {
1377  ClassMethod = ParseIdentifierLoc();
1378  if (!TryConsumeToken(tok::colon)) {
1379  Diag(Tok, diag::err_objcbridge_related_selector_name);
1380  SkipUntil(tok::r_paren, StopAtSemi);
1381  return;
1382  }
1383  }
1384  if (!TryConsumeToken(tok::comma)) {
1385  if (Tok.is(tok::colon))
1386  Diag(Tok, diag::err_objcbridge_related_selector_name);
1387  else
1388  Diag(Tok, diag::err_expected) << tok::comma;
1389  SkipUntil(tok::r_paren, StopAtSemi);
1390  return;
1391  }
1392 
1393  // Parse instance method name. Also non-optional but empty string is
1394  // permitted.
1395  IdentifierLoc *InstanceMethod = nullptr;
1396  if (Tok.is(tok::identifier))
1397  InstanceMethod = ParseIdentifierLoc();
1398  else if (Tok.isNot(tok::r_paren)) {
1399  Diag(Tok, diag::err_expected) << tok::r_paren;
1400  SkipUntil(tok::r_paren, StopAtSemi);
1401  return;
1402  }
1403 
1404  // Closing ')'.
1405  if (T.consumeClose())
1406  return;
1407 
1408  if (endLoc)
1409  *endLoc = T.getCloseLocation();
1410 
1411  // Record this attribute
1412  attrs.addNew(&ObjCBridgeRelated,
1413  SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1414  ScopeName, ScopeLoc,
1415  RelatedClass,
1416  ClassMethod,
1417  InstanceMethod,
1418  Syntax);
1419 }
1420 
1421 
1422 void Parser::ParseSwiftNewTypeAttribute(
1423  IdentifierInfo &AttrName, SourceLocation AttrNameLoc,
1424  ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1425  SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1426  BalancedDelimiterTracker T(*this, tok::l_paren);
1427 
1428  // Opening '('
1429  if (T.consumeOpen()) {
1430  Diag(Tok, diag::err_expected) << tok::l_paren;
1431  return;
1432  }
1433 
1434  if (Tok.is(tok::r_paren)) {
1435  Diag(Tok.getLocation(), diag::err_argument_required_after_attribute);
1436  T.consumeClose();
1437  return;
1438  }
1439  if (Tok.isNot(tok::kw_struct) && Tok.isNot(tok::kw_enum)) {
1440  Diag(Tok, diag::warn_attribute_type_not_supported)
1441  << &AttrName << Tok.getIdentifierInfo();
1442  if (!isTokenSpecial())
1443  ConsumeToken();
1444  T.consumeClose();
1445  return;
1446  }
1447 
1448  auto *SwiftType = IdentifierLoc::create(Actions.Context, Tok.getLocation(),
1449  Tok.getIdentifierInfo());
1450  ConsumeToken();
1451 
1452  // Closing ')'
1453  if (T.consumeClose())
1454  return;
1455  if (EndLoc)
1456  *EndLoc = T.getCloseLocation();
1457 
1458  ArgsUnion Args[] = {SwiftType};
1459  Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, T.getCloseLocation()),
1460  ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1461 }
1462 
1463 
1464 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1465  SourceLocation AttrNameLoc,
1466  ParsedAttributes &Attrs,
1467  SourceLocation *EndLoc,
1468  IdentifierInfo *ScopeName,
1469  SourceLocation ScopeLoc,
1470  ParsedAttr::Syntax Syntax) {
1471  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1472 
1473  BalancedDelimiterTracker T(*this, tok::l_paren);
1474  T.consumeOpen();
1475 
1476  if (Tok.isNot(tok::identifier)) {
1477  Diag(Tok, diag::err_expected) << tok::identifier;
1478  T.skipToEnd();
1479  return;
1480  }
1481  IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1482 
1483  if (ExpectAndConsume(tok::comma)) {
1484  T.skipToEnd();
1485  return;
1486  }
1487 
1488  SourceRange MatchingCTypeRange;
1489  TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1490  if (MatchingCType.isInvalid()) {
1491  T.skipToEnd();
1492  return;
1493  }
1494 
1495  bool LayoutCompatible = false;
1496  bool MustBeNull = false;
1497  while (TryConsumeToken(tok::comma)) {
1498  if (Tok.isNot(tok::identifier)) {
1499  Diag(Tok, diag::err_expected) << tok::identifier;
1500  T.skipToEnd();
1501  return;
1502  }
1503  IdentifierInfo *Flag = Tok.getIdentifierInfo();
1504  if (Flag->isStr("layout_compatible"))
1505  LayoutCompatible = true;
1506  else if (Flag->isStr("must_be_null"))
1507  MustBeNull = true;
1508  else {
1509  Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1510  T.skipToEnd();
1511  return;
1512  }
1513  ConsumeToken(); // consume flag
1514  }
1515 
1516  if (!T.consumeClose()) {
1517  Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1518  ArgumentKind, MatchingCType.get(),
1519  LayoutCompatible, MustBeNull, Syntax);
1520  }
1521 
1522  if (EndLoc)
1523  *EndLoc = T.getCloseLocation();
1524 }
1525 
1526 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1527 /// of a C++11 attribute-specifier in a location where an attribute is not
1528 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1529 /// situation.
1530 ///
1531 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1532 /// this doesn't appear to actually be an attribute-specifier, and the caller
1533 /// should try to parse it.
1534 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1535  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1536 
1537  switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1538  case CAK_NotAttributeSpecifier:
1539  // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1540  return false;
1541 
1542  case CAK_InvalidAttributeSpecifier:
1543  Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1544  return false;
1545 
1546  case CAK_AttributeSpecifier:
1547  // Parse and discard the attributes.
1548  SourceLocation BeginLoc = ConsumeBracket();
1549  ConsumeBracket();
1550  SkipUntil(tok::r_square);
1551  assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1552  SourceLocation EndLoc = ConsumeBracket();
1553  Diag(BeginLoc, diag::err_attributes_not_allowed)
1554  << SourceRange(BeginLoc, EndLoc);
1555  return true;
1556  }
1557  llvm_unreachable("All cases handled above.");
1558 }
1559 
1560 /// We have found the opening square brackets of a C++11
1561 /// attribute-specifier in a location where an attribute is not permitted, but
1562 /// we know where the attributes ought to be written. Parse them anyway, and
1563 /// provide a fixit moving them to the right place.
1564 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1565  SourceLocation CorrectLocation) {
1566  assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1567  Tok.is(tok::kw_alignas));
1568 
1569  // Consume the attributes.
1570  SourceLocation Loc = Tok.getLocation();
1571  ParseCXX11Attributes(Attrs);
1572  CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1573  // FIXME: use err_attributes_misplaced
1574  Diag(Loc, diag::err_attributes_not_allowed)
1575  << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1576  << FixItHint::CreateRemoval(AttrRange);
1577 }
1578 
1579 void Parser::DiagnoseProhibitedAttributes(
1580  const SourceRange &Range, const SourceLocation CorrectLocation) {
1581  if (CorrectLocation.isValid()) {
1582  CharSourceRange AttrRange(Range, true);
1583  Diag(CorrectLocation, diag::err_attributes_misplaced)
1584  << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1585  << FixItHint::CreateRemoval(AttrRange);
1586  } else
1587  Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
1588 }
1589 
1590 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1591  unsigned DiagID) {
1592  for (const ParsedAttr &AL : Attrs) {
1593  if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
1594  continue;
1595  if (AL.getKind() == ParsedAttr::UnknownAttribute)
1596  Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
1597  << AL << AL.getRange();
1598  else {
1599  Diag(AL.getLoc(), DiagID) << AL;
1600  AL.setInvalid();
1601  }
1602  }
1603 }
1604 
1605 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1606 // applies to var, not the type Foo.
1607 // As an exception to the rule, __declspec(align(...)) before the
1608 // class-key affects the type instead of the variable.
1609 // Also, Microsoft-style [attributes] seem to affect the type instead of the
1610 // variable.
1611 // This function moves attributes that should apply to the type off DS to Attrs.
1612 void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1613  DeclSpec &DS,
1614  Sema::TagUseKind TUK) {
1615  if (TUK == Sema::TUK_Reference)
1616  return;
1617 
1619 
1620  for (ParsedAttr &AL : DS.getAttributes()) {
1621  if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1622  AL.isDeclspecAttribute()) ||
1623  AL.isMicrosoftAttribute())
1624  ToBeMoved.push_back(&AL);
1625  }
1626 
1627  for (ParsedAttr *AL : ToBeMoved) {
1628  DS.getAttributes().remove(AL);
1629  Attrs.addAtEnd(AL);
1630  }
1631 }
1632 
1633 /// ParseDeclaration - Parse a full 'declaration', which consists of
1634 /// declaration-specifiers, some number of declarators, and a semicolon.
1635 /// 'Context' should be a DeclaratorContext value. This returns the
1636 /// location of the semicolon in DeclEnd.
1637 ///
1638 /// declaration: [C99 6.7]
1639 /// block-declaration ->
1640 /// simple-declaration
1641 /// others [FIXME]
1642 /// [C++] template-declaration
1643 /// [C++] namespace-definition
1644 /// [C++] using-directive
1645 /// [C++] using-declaration
1646 /// [C++11/C11] static_assert-declaration
1647 /// others... [FIXME]
1648 ///
1650 Parser::ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
1651  ParsedAttributesWithRange &attrs,
1652  SourceLocation *DeclSpecStart) {
1653  ParenBraceBracketBalancer BalancerRAIIObj(*this);
1654  // Must temporarily exit the objective-c container scope for
1655  // parsing c none objective-c decls.
1656  ObjCDeclContextSwitch ObjCDC(*this);
1657 
1658  Decl *SingleDecl = nullptr;
1659  switch (Tok.getKind()) {
1660  case tok::kw_template:
1661  case tok::kw_export:
1662  ProhibitAttributes(attrs);
1663  SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
1664  break;
1665  case tok::kw_inline:
1666  // Could be the start of an inline namespace. Allowed as an ext in C++03.
1667  if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1668  ProhibitAttributes(attrs);
1669  SourceLocation InlineLoc = ConsumeToken();
1670  return ParseNamespace(Context, DeclEnd, InlineLoc);
1671  }
1672  return ParseSimpleDeclaration(Context, DeclEnd, attrs, true, nullptr,
1673  DeclSpecStart);
1674  case tok::kw_namespace:
1675  ProhibitAttributes(attrs);
1676  return ParseNamespace(Context, DeclEnd);
1677  case tok::kw_using:
1678  return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1679  DeclEnd, attrs);
1680  case tok::kw_static_assert:
1681  case tok::kw__Static_assert:
1682  ProhibitAttributes(attrs);
1683  SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1684  break;
1685  default:
1686  return ParseSimpleDeclaration(Context, DeclEnd, attrs, true, nullptr,
1687  DeclSpecStart);
1688  }
1689 
1690  // This routine returns a DeclGroup, if the thing we parsed only contains a
1691  // single decl, convert it now.
1692  return Actions.ConvertDeclToDeclGroup(SingleDecl);
1693 }
1694 
1695 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1696 /// declaration-specifiers init-declarator-list[opt] ';'
1697 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1698 /// init-declarator-list ';'
1699 ///[C90/C++]init-declarator-list ';' [TODO]
1700 /// [OMP] threadprivate-directive
1701 /// [OMP] allocate-directive [TODO]
1702 ///
1703 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1704 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1705 ///
1706 /// If RequireSemi is false, this does not check for a ';' at the end of the
1707 /// declaration. If it is true, it checks for and eats it.
1708 ///
1709 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1710 /// of a simple-declaration. If we find that we are, we also parse the
1711 /// for-range-initializer, and place it here.
1712 ///
1713 /// DeclSpecStart is used when decl-specifiers are parsed before parsing
1714 /// the Declaration. The SourceLocation for this Decl is set to
1715 /// DeclSpecStart if DeclSpecStart is non-null.
1716 Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(
1717  DeclaratorContext Context, SourceLocation &DeclEnd,
1718  ParsedAttributesWithRange &Attrs, bool RequireSemi, ForRangeInit *FRI,
1719  SourceLocation *DeclSpecStart) {
1720  // Parse the common declaration-specifiers piece.
1721  ParsingDeclSpec DS(*this);
1722 
1723  DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1724  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1725 
1726  // If we had a free-standing type definition with a missing semicolon, we
1727  // may get this far before the problem becomes obvious.
1728  if (DS.hasTagDefinition() &&
1729  DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1730  return nullptr;
1731 
1732  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1733  // declaration-specifiers init-declarator-list[opt] ';'
1734  if (Tok.is(tok::semi)) {
1735  ProhibitAttributes(Attrs);
1736  DeclEnd = Tok.getLocation();
1737  if (RequireSemi) ConsumeToken();
1738  RecordDecl *AnonRecord = nullptr;
1739  Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1740  DS, AnonRecord);
1741  DS.complete(TheDecl);
1742  if (AnonRecord) {
1743  Decl* decls[] = {AnonRecord, TheDecl};
1744  return Actions.BuildDeclaratorGroup(decls);
1745  }
1746  return Actions.ConvertDeclToDeclGroup(TheDecl);
1747  }
1748 
1749  if (DeclSpecStart)
1750  DS.SetRangeStart(*DeclSpecStart);
1751 
1752  DS.takeAttributesFrom(Attrs);
1753  return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1754 }
1755 
1756 /// Returns true if this might be the start of a declarator, or a common typo
1757 /// for a declarator.
1758 bool Parser::MightBeDeclarator(DeclaratorContext Context) {
1759  switch (Tok.getKind()) {
1760  case tok::annot_cxxscope:
1761  case tok::annot_template_id:
1762  case tok::caret:
1763  case tok::code_completion:
1764  case tok::coloncolon:
1765  case tok::ellipsis:
1766  case tok::kw___attribute:
1767  case tok::kw_operator:
1768  case tok::l_paren:
1769  case tok::star:
1770  return true;
1771 
1772  case tok::amp:
1773  case tok::ampamp:
1774  return getLangOpts().CPlusPlus;
1775 
1776  case tok::l_square: // Might be an attribute on an unnamed bit-field.
1777  return Context == DeclaratorContext::Member && getLangOpts().CPlusPlus11 &&
1778  NextToken().is(tok::l_square);
1779 
1780  case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1781  return Context == DeclaratorContext::Member || getLangOpts().CPlusPlus;
1782 
1783  case tok::identifier:
1784  switch (NextToken().getKind()) {
1785  case tok::code_completion:
1786  case tok::coloncolon:
1787  case tok::comma:
1788  case tok::equal:
1789  case tok::equalequal: // Might be a typo for '='.
1790  case tok::kw_alignas:
1791  case tok::kw_asm:
1792  case tok::kw___attribute:
1793  case tok::l_brace:
1794  case tok::l_paren:
1795  case tok::l_square:
1796  case tok::less:
1797  case tok::r_brace:
1798  case tok::r_paren:
1799  case tok::r_square:
1800  case tok::semi:
1801  return true;
1802 
1803  case tok::colon:
1804  // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1805  // and in block scope it's probably a label. Inside a class definition,
1806  // this is a bit-field.
1807  return Context == DeclaratorContext::Member ||
1808  (getLangOpts().CPlusPlus && Context == DeclaratorContext::File);
1809 
1810  case tok::identifier: // Possible virt-specifier.
1811  return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1812 
1813  default:
1814  return false;
1815  }
1816 
1817  default:
1818  return false;
1819  }
1820 }
1821 
1822 /// Skip until we reach something which seems like a sensible place to pick
1823 /// up parsing after a malformed declaration. This will sometimes stop sooner
1824 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1826  while (true) {
1827  switch (Tok.getKind()) {
1828  case tok::l_brace:
1829  // Skip until matching }, then stop. We've probably skipped over
1830  // a malformed class or function definition or similar.
1831  ConsumeBrace();
1832  SkipUntil(tok::r_brace);
1833  if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1834  // This declaration isn't over yet. Keep skipping.
1835  continue;
1836  }
1837  TryConsumeToken(tok::semi);
1838  return;
1839 
1840  case tok::l_square:
1841  ConsumeBracket();
1842  SkipUntil(tok::r_square);
1843  continue;
1844 
1845  case tok::l_paren:
1846  ConsumeParen();
1847  SkipUntil(tok::r_paren);
1848  continue;
1849 
1850  case tok::r_brace:
1851  return;
1852 
1853  case tok::semi:
1854  ConsumeToken();
1855  return;
1856 
1857  case tok::kw_inline:
1858  // 'inline namespace' at the start of a line is almost certainly
1859  // a good place to pick back up parsing, except in an Objective-C
1860  // @interface context.
1861  if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1862  (!ParsingInObjCContainer || CurParsedObjCImpl))
1863  return;
1864  break;
1865 
1866  case tok::kw_namespace:
1867  // 'namespace' at the start of a line is almost certainly a good
1868  // place to pick back up parsing, except in an Objective-C
1869  // @interface context.
1870  if (Tok.isAtStartOfLine() &&
1871  (!ParsingInObjCContainer || CurParsedObjCImpl))
1872  return;
1873  break;
1874 
1875  case tok::at:
1876  // @end is very much like } in Objective-C contexts.
1877  if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1878  ParsingInObjCContainer)
1879  return;
1880  break;
1881 
1882  case tok::minus:
1883  case tok::plus:
1884  // - and + probably start new method declarations in Objective-C contexts.
1885  if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1886  return;
1887  break;
1888 
1889  case tok::eof:
1890  case tok::annot_module_begin:
1891  case tok::annot_module_end:
1892  case tok::annot_module_include:
1893  return;
1894 
1895  default:
1896  break;
1897  }
1898 
1899  ConsumeAnyToken();
1900  }
1901 }
1902 
1903 /// ParseDeclGroup - Having concluded that this is either a function
1904 /// definition or a group of object declarations, actually parse the
1905 /// result.
1906 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1907  DeclaratorContext Context,
1908  SourceLocation *DeclEnd,
1909  ForRangeInit *FRI) {
1910  // Parse the first declarator.
1911  ParsingDeclarator D(*this, DS, Context);
1912  ParseDeclarator(D);
1913 
1914  // Bail out if the first declarator didn't seem well-formed.
1915  if (!D.hasName() && !D.mayOmitIdentifier()) {
1917  return nullptr;
1918  }
1919 
1920  if (Tok.is(tok::kw_requires))
1921  ParseTrailingRequiresClause(D);
1922 
1923  // Save late-parsed attributes for now; they need to be parsed in the
1924  // appropriate function scope after the function Decl has been constructed.
1925  // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1926  LateParsedAttrList LateParsedAttrs(true);
1927  if (D.isFunctionDeclarator()) {
1928  MaybeParseGNUAttributes(D, &LateParsedAttrs);
1929 
1930  // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1931  // attribute. If we find the keyword here, tell the user to put it
1932  // at the start instead.
1933  if (Tok.is(tok::kw__Noreturn)) {
1934  SourceLocation Loc = ConsumeToken();
1935  const char *PrevSpec;
1936  unsigned DiagID;
1937 
1938  // We can offer a fixit if it's valid to mark this function as _Noreturn
1939  // and we don't have any other declarators in this declaration.
1940  bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1941  MaybeParseGNUAttributes(D, &LateParsedAttrs);
1942  Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
1943 
1944  Diag(Loc, diag::err_c11_noreturn_misplaced)
1945  << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
1946  << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
1947  : FixItHint());
1948  }
1949  }
1950 
1951  // Check to see if we have a function *definition* which must have a body.
1952  if (D.isFunctionDeclarator()) {
1953  if (Tok.is(tok::equal) && NextToken().is(tok::code_completion)) {
1955  cutOffParsing();
1956  return nullptr;
1957  }
1958  // Look at the next token to make sure that this isn't a function
1959  // declaration. We have to check this because __attribute__ might be the
1960  // start of a function definition in GCC-extended K&R C.
1961  if (!isDeclarationAfterDeclarator()) {
1962 
1963  // Function definitions are only allowed at file scope and in C++ classes.
1964  // The C++ inline method definition case is handled elsewhere, so we only
1965  // need to handle the file scope definition case.
1966  if (Context == DeclaratorContext::File) {
1967  if (isStartOfFunctionDefinition(D)) {
1969  Diag(Tok, diag::err_function_declared_typedef);
1970 
1971  // Recover by treating the 'typedef' as spurious.
1973  }
1974 
1975  Decl *TheDecl = ParseFunctionDefinition(D, ParsedTemplateInfo(),
1976  &LateParsedAttrs);
1977  return Actions.ConvertDeclToDeclGroup(TheDecl);
1978  }
1979 
1980  if (isDeclarationSpecifier()) {
1981  // If there is an invalid declaration specifier right after the
1982  // function prototype, then we must be in a missing semicolon case
1983  // where this isn't actually a body. Just fall through into the code
1984  // that handles it as a prototype, and let the top-level code handle
1985  // the erroneous declspec where it would otherwise expect a comma or
1986  // semicolon.
1987  } else {
1988  Diag(Tok, diag::err_expected_fn_body);
1989  SkipUntil(tok::semi);
1990  return nullptr;
1991  }
1992  } else {
1993  if (Tok.is(tok::l_brace)) {
1994  Diag(Tok, diag::err_function_definition_not_allowed);
1996  return nullptr;
1997  }
1998  }
1999  }
2000  }
2001 
2002  if (ParseAsmAttributesAfterDeclarator(D))
2003  return nullptr;
2004 
2005  // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2006  // must parse and analyze the for-range-initializer before the declaration is
2007  // analyzed.
2008  //
2009  // Handle the Objective-C for-in loop variable similarly, although we
2010  // don't need to parse the container in advance.
2011  if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2012  bool IsForRangeLoop = false;
2013  if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2014  IsForRangeLoop = true;
2015  if (getLangOpts().OpenMP)
2016  Actions.startOpenMPCXXRangeFor();
2017  if (Tok.is(tok::l_brace))
2018  FRI->RangeExpr = ParseBraceInitializer();
2019  else
2020  FRI->RangeExpr = ParseExpression();
2021  }
2022 
2023  Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2024  if (IsForRangeLoop) {
2025  Actions.ActOnCXXForRangeDecl(ThisDecl);
2026  } else {
2027  // Obj-C for loop
2028  if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2029  VD->setObjCForDecl(true);
2030  }
2031  Actions.FinalizeDeclaration(ThisDecl);
2032  D.complete(ThisDecl);
2033  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2034  }
2035 
2036  SmallVector<Decl *, 8> DeclsInGroup;
2037  Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2038  D, ParsedTemplateInfo(), FRI);
2039  if (LateParsedAttrs.size() > 0)
2040  ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2041  D.complete(FirstDecl);
2042  if (FirstDecl)
2043  DeclsInGroup.push_back(FirstDecl);
2044 
2045  bool ExpectSemi = Context != DeclaratorContext::ForInit;
2046 
2047  // If we don't have a comma, it is either the end of the list (a ';') or an
2048  // error, bail out.
2049  SourceLocation CommaLoc;
2050  while (TryConsumeToken(tok::comma, CommaLoc)) {
2051  if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2052  // This comma was followed by a line-break and something which can't be
2053  // the start of a declarator. The comma was probably a typo for a
2054  // semicolon.
2055  Diag(CommaLoc, diag::err_expected_semi_declaration)
2056  << FixItHint::CreateReplacement(CommaLoc, ";");
2057  ExpectSemi = false;
2058  break;
2059  }
2060 
2061  // Parse the next declarator.
2062  D.clear();
2063  D.setCommaLoc(CommaLoc);
2064 
2065  // Accept attributes in an init-declarator. In the first declarator in a
2066  // declaration, these would be part of the declspec. In subsequent
2067  // declarators, they become part of the declarator itself, so that they
2068  // don't apply to declarators after *this* one. Examples:
2069  // short __attribute__((common)) var; -> declspec
2070  // short var __attribute__((common)); -> declarator
2071  // short x, __attribute__((common)) var; -> declarator
2072  MaybeParseGNUAttributes(D);
2073 
2074  // MSVC parses but ignores qualifiers after the comma as an extension.
2075  if (getLangOpts().MicrosoftExt)
2076  DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2077 
2078  ParseDeclarator(D);
2079  if (!D.isInvalidType()) {
2080  // C++2a [dcl.decl]p1
2081  // init-declarator:
2082  // declarator initializer[opt]
2083  // declarator requires-clause
2084  if (Tok.is(tok::kw_requires))
2085  ParseTrailingRequiresClause(D);
2086  Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2087  D.complete(ThisDecl);
2088  if (ThisDecl)
2089  DeclsInGroup.push_back(ThisDecl);
2090  }
2091  }
2092 
2093  if (DeclEnd)
2094  *DeclEnd = Tok.getLocation();
2095 
2096  if (ExpectSemi && ExpectAndConsumeSemi(
2097  Context == DeclaratorContext::File
2098  ? diag::err_invalid_token_after_toplevel_declarator
2099  : diag::err_expected_semi_declaration)) {
2100  // Okay, there was no semicolon and one was expected. If we see a
2101  // declaration specifier, just assume it was missing and continue parsing.
2102  // Otherwise things are very confused and we skip to recover.
2103  if (!isDeclarationSpecifier()) {
2104  SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2105  TryConsumeToken(tok::semi);
2106  }
2107  }
2108 
2109  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2110 }
2111 
2112 /// Parse an optional simple-asm-expr and attributes, and attach them to a
2113 /// declarator. Returns true on an error.
2114 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2115  // If a simple-asm-expr is present, parse it.
2116  if (Tok.is(tok::kw_asm)) {
2117  SourceLocation Loc;
2118  ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2119  if (AsmLabel.isInvalid()) {
2120  SkipUntil(tok::semi, StopBeforeMatch);
2121  return true;
2122  }
2123 
2124  D.setAsmLabel(AsmLabel.get());
2125  D.SetRangeEnd(Loc);
2126  }
2127 
2128  MaybeParseGNUAttributes(D);
2129  return false;
2130 }
2131 
2132 /// Parse 'declaration' after parsing 'declaration-specifiers
2133 /// declarator'. This method parses the remainder of the declaration
2134 /// (including any attributes or initializer, among other things) and
2135 /// finalizes the declaration.
2136 ///
2137 /// init-declarator: [C99 6.7]
2138 /// declarator
2139 /// declarator '=' initializer
2140 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2141 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2142 /// [C++] declarator initializer[opt]
2143 ///
2144 /// [C++] initializer:
2145 /// [C++] '=' initializer-clause
2146 /// [C++] '(' expression-list ')'
2147 /// [C++0x] '=' 'default' [TODO]
2148 /// [C++0x] '=' 'delete'
2149 /// [C++0x] braced-init-list
2150 ///
2151 /// According to the standard grammar, =default and =delete are function
2152 /// definitions, but that definitely doesn't fit with the parser here.
2153 ///
2154 Decl *Parser::ParseDeclarationAfterDeclarator(
2155  Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2156  if (ParseAsmAttributesAfterDeclarator(D))
2157  return nullptr;
2158 
2159  return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2160 }
2161 
2162 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2163  Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2164  // RAII type used to track whether we're inside an initializer.
2165  struct InitializerScopeRAII {
2166  Parser &P;
2167  Declarator &D;
2168  Decl *ThisDecl;
2169 
2170  InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2171  : P(P), D(D), ThisDecl(ThisDecl) {
2172  if (ThisDecl && P.getLangOpts().CPlusPlus) {
2173  Scope *S = nullptr;
2174  if (D.getCXXScopeSpec().isSet()) {
2175  P.EnterScope(0);
2176  S = P.getCurScope();
2177  }
2178  P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2179  }
2180  }
2181  ~InitializerScopeRAII() { pop(); }
2182  void pop() {
2183  if (ThisDecl && P.getLangOpts().CPlusPlus) {
2184  Scope *S = nullptr;
2185  if (D.getCXXScopeSpec().isSet())
2186  S = P.getCurScope();
2187  P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2188  if (S)
2189  P.ExitScope();
2190  }
2191  ThisDecl = nullptr;
2192  }
2193  };
2194 
2195  enum class InitKind { Uninitialized, Equal, CXXDirect, CXXBraced };
2196  InitKind TheInitKind;
2197  // If a '==' or '+=' is found, suggest a fixit to '='.
2198  if (isTokenEqualOrEqualTypo())
2199  TheInitKind = InitKind::Equal;
2200  else if (Tok.is(tok::l_paren))
2201  TheInitKind = InitKind::CXXDirect;
2202  else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2203  (!CurParsedObjCImpl || !D.isFunctionDeclarator()))
2204  TheInitKind = InitKind::CXXBraced;
2205  else
2206  TheInitKind = InitKind::Uninitialized;
2207  if (TheInitKind != InitKind::Uninitialized)
2208  D.setHasInitializer();
2209 
2210  // Inform Sema that we just parsed this declarator.
2211  Decl *ThisDecl = nullptr;
2212  Decl *OuterDecl = nullptr;
2213  switch (TemplateInfo.Kind) {
2214  case ParsedTemplateInfo::NonTemplate:
2215  ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2216  break;
2217 
2218  case ParsedTemplateInfo::Template:
2219  case ParsedTemplateInfo::ExplicitSpecialization: {
2220  ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2221  *TemplateInfo.TemplateParams,
2222  D);
2223  if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl)) {
2224  // Re-direct this decl to refer to the templated decl so that we can
2225  // initialize it.
2226  ThisDecl = VT->getTemplatedDecl();
2227  OuterDecl = VT;
2228  }
2229  break;
2230  }
2231  case ParsedTemplateInfo::ExplicitInstantiation: {
2232  if (Tok.is(tok::semi)) {
2233  DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2234  getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2235  if (ThisRes.isInvalid()) {
2236  SkipUntil(tok::semi, StopBeforeMatch);
2237  return nullptr;
2238  }
2239  ThisDecl = ThisRes.get();
2240  } else {
2241  // FIXME: This check should be for a variable template instantiation only.
2242 
2243  // Check that this is a valid instantiation
2245  // If the declarator-id is not a template-id, issue a diagnostic and
2246  // recover by ignoring the 'template' keyword.
2247  Diag(Tok, diag::err_template_defn_explicit_instantiation)
2248  << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2249  ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2250  } else {
2251  SourceLocation LAngleLoc =
2252  PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2253  Diag(D.getIdentifierLoc(),
2254  diag::err_explicit_instantiation_with_definition)
2255  << SourceRange(TemplateInfo.TemplateLoc)
2256  << FixItHint::CreateInsertion(LAngleLoc, "<>");
2257 
2258  // Recover as if it were an explicit specialization.
2259  TemplateParameterLists FakedParamLists;
2260  FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2261  0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
2262  LAngleLoc, nullptr));
2263 
2264  ThisDecl =
2265  Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2266  }
2267  }
2268  break;
2269  }
2270  }
2271 
2272  switch (TheInitKind) {
2273  // Parse declarator '=' initializer.
2274  case InitKind::Equal: {
2275  SourceLocation EqualLoc = ConsumeToken();
2276 
2277  if (Tok.is(tok::kw_delete)) {
2278  if (D.isFunctionDeclarator())
2279  Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2280  << 1 /* delete */;
2281  else
2282  Diag(ConsumeToken(), diag::err_deleted_non_function);
2283  } else if (Tok.is(tok::kw_default)) {
2284  if (D.isFunctionDeclarator())
2285  Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2286  << 0 /* default */;
2287  else
2288  Diag(ConsumeToken(), diag::err_default_special_members)
2289  << getLangOpts().CPlusPlus20;
2290  } else {
2291  InitializerScopeRAII InitScope(*this, D, ThisDecl);
2292 
2293  if (Tok.is(tok::code_completion)) {
2294  Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2295  Actions.FinalizeDeclaration(ThisDecl);
2296  cutOffParsing();
2297  return nullptr;
2298  }
2299 
2300  PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2301  ExprResult Init = ParseInitializer();
2302 
2303  // If this is the only decl in (possibly) range based for statement,
2304  // our best guess is that the user meant ':' instead of '='.
2305  if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2306  Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2307  << FixItHint::CreateReplacement(EqualLoc, ":");
2308  // We are trying to stop parser from looking for ';' in this for
2309  // statement, therefore preventing spurious errors to be issued.
2310  FRI->ColonLoc = EqualLoc;
2311  Init = ExprError();
2312  FRI->RangeExpr = Init;
2313  }
2314 
2315  InitScope.pop();
2316 
2317  if (Init.isInvalid()) {
2318  SmallVector<tok::TokenKind, 2> StopTokens;
2319  StopTokens.push_back(tok::comma);
2322  StopTokens.push_back(tok::r_paren);
2323  SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2324  Actions.ActOnInitializerError(ThisDecl);
2325  } else
2326  Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2327  /*DirectInit=*/false);
2328  }
2329  break;
2330  }
2331  case InitKind::CXXDirect: {
2332  // Parse C++ direct initializer: '(' expression-list ')'
2333  BalancedDelimiterTracker T(*this, tok::l_paren);
2334  T.consumeOpen();
2335 
2336  ExprVector Exprs;
2337  CommaLocsTy CommaLocs;
2338 
2339  InitializerScopeRAII InitScope(*this, D, ThisDecl);
2340 
2341  auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2342  auto RunSignatureHelp = [&]() {
2343  QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2344  getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2345  ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2346  CalledSignatureHelp = true;
2347  return PreferredType;
2348  };
2349  auto SetPreferredType = [&] {
2350  PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2351  };
2352 
2353  llvm::function_ref<void()> ExpressionStarts;
2354  if (ThisVarDecl) {
2355  // ParseExpressionList can sometimes succeed even when ThisDecl is not
2356  // VarDecl. This is an error and it is reported in a call to
2357  // Actions.ActOnInitializerError(). However, we call
2358  // ProduceConstructorSignatureHelp only on VarDecls.
2359  ExpressionStarts = SetPreferredType;
2360  }
2361  if (ParseExpressionList(Exprs, CommaLocs, ExpressionStarts)) {
2362  if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2364  getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2365  ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2366  CalledSignatureHelp = true;
2367  }
2368  Actions.ActOnInitializerError(ThisDecl);
2369  SkipUntil(tok::r_paren, StopAtSemi);
2370  } else {
2371  // Match the ')'.
2372  T.consumeClose();
2373 
2374  assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2375  "Unexpected number of commas!");
2376 
2377  InitScope.pop();
2378 
2379  ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2380  T.getCloseLocation(),
2381  Exprs);
2382  Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2383  /*DirectInit=*/true);
2384  }
2385  break;
2386  }
2387  case InitKind::CXXBraced: {
2388  // Parse C++0x braced-init-list.
2389  Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2390 
2391  InitializerScopeRAII InitScope(*this, D, ThisDecl);
2392 
2393  PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2394  ExprResult Init(ParseBraceInitializer());
2395 
2396  InitScope.pop();
2397 
2398  if (Init.isInvalid()) {
2399  Actions.ActOnInitializerError(ThisDecl);
2400  } else
2401  Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2402  break;
2403  }
2404  case InitKind::Uninitialized: {
2405  Actions.ActOnUninitializedDecl(ThisDecl);
2406  break;
2407  }
2408  }
2409 
2410  Actions.FinalizeDeclaration(ThisDecl);
2411  return OuterDecl ? OuterDecl : ThisDecl;
2412 }
2413 
2414 /// ParseSpecifierQualifierList
2415 /// specifier-qualifier-list:
2416 /// type-specifier specifier-qualifier-list[opt]
2417 /// type-qualifier specifier-qualifier-list[opt]
2418 /// [GNU] attributes specifier-qualifier-list[opt]
2419 ///
2420 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2421  DeclSpecContext DSC) {
2422  /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2423  /// parse declaration-specifiers and complain about extra stuff.
2424  /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2425  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2426 
2427  // Validate declspec for type-name.
2428  unsigned Specs = DS.getParsedSpecifiers();
2429  if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2430  Diag(Tok, diag::err_expected_type);
2431  DS.SetTypeSpecError();
2432  } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2433  Diag(Tok, diag::err_typename_requires_specqual);
2434  if (!DS.hasTypeSpecifier())
2435  DS.SetTypeSpecError();
2436  }
2437 
2438  // Issue diagnostic and remove storage class if present.
2439  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2440  if (DS.getStorageClassSpecLoc().isValid())
2441  Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2442  else
2444  diag::err_typename_invalid_storageclass);
2446  }
2447 
2448  // Issue diagnostic and remove function specifier if present.
2449  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2450  if (DS.isInlineSpecified())
2451  Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2452  if (DS.isVirtualSpecified())
2453  Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2454  if (DS.hasExplicitSpecifier())
2455  Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2456  DS.ClearFunctionSpecs();
2457  }
2458 
2459  // Issue diagnostic and remove constexpr specifier if present.
2460  if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2461  Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2462  << static_cast<int>(DS.getConstexprSpecifier());
2463  DS.ClearConstexprSpec();
2464  }
2465 }
2466 
2467 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2468 /// specified token is valid after the identifier in a declarator which
2469 /// immediately follows the declspec. For example, these things are valid:
2470 ///
2471 /// int x [ 4]; // direct-declarator
2472 /// int x ( int y); // direct-declarator
2473 /// int(int x ) // direct-declarator
2474 /// int x ; // simple-declaration
2475 /// int x = 17; // init-declarator-list
2476 /// int x , y; // init-declarator-list
2477 /// int x __asm__ ("foo"); // init-declarator-list
2478 /// int x : 4; // struct-declarator
2479 /// int x { 5}; // C++'0x unified initializers
2480 ///
2481 /// This is not, because 'x' does not immediately follow the declspec (though
2482 /// ')' happens to be valid anyway).
2483 /// int (x)
2484 ///
2486  return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2487  tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2488  tok::colon);
2489 }
2490 
2491 /// ParseImplicitInt - This method is called when we have an non-typename
2492 /// identifier in a declspec (which normally terminates the decl spec) when
2493 /// the declspec has no type specifier. In this case, the declspec is either
2494 /// malformed or is "implicit int" (in K&R and C89).
2495 ///
2496 /// This method handles diagnosing this prettily and returns false if the
2497 /// declspec is done being processed. If it recovers and thinks there may be
2498 /// other pieces of declspec after it, it returns true.
2499 ///
2500 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2501  const ParsedTemplateInfo &TemplateInfo,
2502  AccessSpecifier AS, DeclSpecContext DSC,
2503  ParsedAttributesWithRange &Attrs) {
2504  assert(Tok.is(tok::identifier) && "should have identifier");
2505 
2506  SourceLocation Loc = Tok.getLocation();
2507  // If we see an identifier that is not a type name, we normally would
2508  // parse it as the identifier being declared. However, when a typename
2509  // is typo'd or the definition is not included, this will incorrectly
2510  // parse the typename as the identifier name and fall over misparsing
2511  // later parts of the diagnostic.
2512  //
2513  // As such, we try to do some look-ahead in cases where this would
2514  // otherwise be an "implicit-int" case to see if this is invalid. For
2515  // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2516  // an identifier with implicit int, we'd get a parse error because the
2517  // next token is obviously invalid for a type. Parse these as a case
2518  // with an invalid type specifier.
2519  assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2520 
2521  // Since we know that this either implicit int (which is rare) or an
2522  // error, do lookahead to try to do better recovery. This never applies
2523  // within a type specifier. Outside of C++, we allow this even if the
2524  // language doesn't "officially" support implicit int -- we support
2525  // implicit int as an extension in C99 and C11.
2526  if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2528  // If this token is valid for implicit int, e.g. "static x = 4", then
2529  // we just avoid eating the identifier, so it will be parsed as the
2530  // identifier in the declarator.
2531  return false;
2532  }
2533 
2534  // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2535  // for incomplete declarations such as `pipe p`.
2536  if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
2537  return false;
2538 
2539  if (getLangOpts().CPlusPlus &&
2541  // Don't require a type specifier if we have the 'auto' storage class
2542  // specifier in C++98 -- we'll promote it to a type specifier.
2543  if (SS)
2544  AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2545  return false;
2546  }
2547 
2548  if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2549  getLangOpts().MSVCCompat) {
2550  // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2551  // Give Sema a chance to recover if we are in a template with dependent base
2552  // classes.
2553  if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2554  *Tok.getIdentifierInfo(), Tok.getLocation(),
2555  DSC == DeclSpecContext::DSC_template_type_arg)) {
2556  const char *PrevSpec;
2557  unsigned DiagID;
2558  DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2559  Actions.getASTContext().getPrintingPolicy());
2560  DS.SetRangeEnd(Tok.getLocation());
2561  ConsumeToken();
2562  return false;
2563  }
2564  }
2565 
2566  // Otherwise, if we don't consume this token, we are going to emit an
2567  // error anyway. Try to recover from various common problems. Check
2568  // to see if this was a reference to a tag name without a tag specified.
2569  // This is a common problem in C (saying 'foo' instead of 'struct foo').
2570  //
2571  // C++ doesn't need this, and isTagName doesn't take SS.
2572  if (SS == nullptr) {
2573  const char *TagName = nullptr, *FixitTagName = nullptr;
2574  tok::TokenKind TagKind = tok::unknown;
2575 
2576  switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2577  default: break;
2578  case DeclSpec::TST_enum:
2579  TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2580  case DeclSpec::TST_union:
2581  TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2582  case DeclSpec::TST_struct:
2583  TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2585  TagName="__interface"; FixitTagName = "__interface ";
2586  TagKind=tok::kw___interface;break;
2587  case DeclSpec::TST_class:
2588  TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2589  }
2590 
2591  if (TagName) {
2592  IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2593  LookupResult R(Actions, TokenName, SourceLocation(),
2595 
2596  Diag(Loc, diag::err_use_of_tag_name_without_tag)
2597  << TokenName << TagName << getLangOpts().CPlusPlus
2598  << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2599 
2600  if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2601  for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2602  I != IEnd; ++I)
2603  Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2604  << TokenName << TagName;
2605  }
2606 
2607  // Parse this as a tag as if the missing tag were present.
2608  if (TagKind == tok::kw_enum)
2609  ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2610  DeclSpecContext::DSC_normal);
2611  else
2612  ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2613  /*EnteringContext*/ false,
2614  DeclSpecContext::DSC_normal, Attrs);
2615  return true;
2616  }
2617  }
2618 
2619  // Determine whether this identifier could plausibly be the name of something
2620  // being declared (with a missing type).
2621  if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2622  DSC == DeclSpecContext::DSC_class)) {
2623  // Look ahead to the next token to try to figure out what this declaration
2624  // was supposed to be.
2625  switch (NextToken().getKind()) {
2626  case tok::l_paren: {
2627  // static x(4); // 'x' is not a type
2628  // x(int n); // 'x' is not a type
2629  // x (*p)[]; // 'x' is a type
2630  //
2631  // Since we're in an error case, we can afford to perform a tentative
2632  // parse to determine which case we're in.
2633  TentativeParsingAction PA(*this);
2634  ConsumeToken();
2635  TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2636  PA.Revert();
2637 
2638  if (TPR != TPResult::False) {
2639  // The identifier is followed by a parenthesized declarator.
2640  // It's supposed to be a type.
2641  break;
2642  }
2643 
2644  // If we're in a context where we could be declaring a constructor,
2645  // check whether this is a constructor declaration with a bogus name.
2646  if (DSC == DeclSpecContext::DSC_class ||
2647  (DSC == DeclSpecContext::DSC_top_level && SS)) {
2648  IdentifierInfo *II = Tok.getIdentifierInfo();
2649  if (Actions.isCurrentClassNameTypo(II, SS)) {
2650  Diag(Loc, diag::err_constructor_bad_name)
2651  << Tok.getIdentifierInfo() << II
2653  Tok.setIdentifierInfo(II);
2654  }
2655  }
2656  // Fall through.
2657  LLVM_FALLTHROUGH;
2658  }
2659  case tok::comma:
2660  case tok::equal:
2661  case tok::kw_asm:
2662  case tok::l_brace:
2663  case tok::l_square:
2664  case tok::semi:
2665  // This looks like a variable or function declaration. The type is
2666  // probably missing. We're done parsing decl-specifiers.
2667  // But only if we are not in a function prototype scope.
2668  if (getCurScope()->isFunctionPrototypeScope())
2669  break;
2670  if (SS)
2671  AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2672  return false;
2673 
2674  default:
2675  // This is probably supposed to be a type. This includes cases like:
2676  // int f(itn);
2677  // struct S { unsigned : 4; };
2678  break;
2679  }
2680  }
2681 
2682  // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2683  // and attempt to recover.
2684  ParsedType T;
2685  IdentifierInfo *II = Tok.getIdentifierInfo();
2686  bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2687  Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2688  IsTemplateName);
2689  if (T) {
2690  // The action has suggested that the type T could be used. Set that as
2691  // the type in the declaration specifiers, consume the would-be type
2692  // name token, and we're done.
2693  const char *PrevSpec;
2694  unsigned DiagID;
2695  DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2696  Actions.getASTContext().getPrintingPolicy());
2697  DS.SetRangeEnd(Tok.getLocation());
2698  ConsumeToken();
2699  // There may be other declaration specifiers after this.
2700  return true;
2701  } else if (II != Tok.getIdentifierInfo()) {
2702  // If no type was suggested, the correction is to a keyword
2703  Tok.setKind(II->getTokenID());
2704  // There may be other declaration specifiers after this.
2705  return true;
2706  }
2707 
2708  // Otherwise, the action had no suggestion for us. Mark this as an error.
2709  DS.SetTypeSpecError();
2710  DS.SetRangeEnd(Tok.getLocation());
2711  ConsumeToken();
2712 
2713  // Eat any following template arguments.
2714  if (IsTemplateName) {
2715  SourceLocation LAngle, RAngle;
2716  TemplateArgList Args;
2717  ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2718  }
2719 
2720  // TODO: Could inject an invalid typedef decl in an enclosing scope to
2721  // avoid rippling error messages on subsequent uses of the same type,
2722  // could be useful if #include was forgotten.
2723  return true;
2724 }
2725 
2726 /// Determine the declaration specifier context from the declarator
2727 /// context.
2728 ///
2729 /// \param Context the declarator context, which is one of the
2730 /// DeclaratorContext enumerator values.
2731 Parser::DeclSpecContext
2732 Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2733  if (Context == DeclaratorContext::Member)
2734  return DeclSpecContext::DSC_class;
2735  if (Context == DeclaratorContext::File)
2736  return DeclSpecContext::DSC_top_level;
2737  if (Context == DeclaratorContext::TemplateParam)
2738  return DeclSpecContext::DSC_template_param;
2739  if (Context == DeclaratorContext::TemplateArg ||
2741  return DeclSpecContext::DSC_template_type_arg;
2742  if (Context == DeclaratorContext::TrailingReturn ||
2744  return DeclSpecContext::DSC_trailing;
2745  if (Context == DeclaratorContext::AliasDecl ||
2747  return DeclSpecContext::DSC_alias_declaration;
2748  return DeclSpecContext::DSC_normal;
2749 }
2750 
2751 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2752 ///
2753 /// FIXME: Simply returns an alignof() expression if the argument is a
2754 /// type. Ideally, the type should be propagated directly into Sema.
2755 ///
2756 /// [C11] type-id
2757 /// [C11] constant-expression
2758 /// [C++0x] type-id ...[opt]
2759 /// [C++0x] assignment-expression ...[opt]
2760 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2761  SourceLocation &EllipsisLoc) {
2762  ExprResult ER;
2763  if (isTypeIdInParens()) {
2765  ParsedType Ty = ParseTypeName().get();
2766  SourceRange TypeRange(Start, Tok.getLocation());
2767  ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2768  Ty.getAsOpaquePtr(), TypeRange);
2769  } else
2770  ER = ParseConstantExpression();
2771 
2772  if (getLangOpts().CPlusPlus11)
2773  TryConsumeToken(tok::ellipsis, EllipsisLoc);
2774 
2775  return ER;
2776 }
2777 
2778 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2779 /// attribute to Attrs.
2780 ///
2781 /// alignment-specifier:
2782 /// [C11] '_Alignas' '(' type-id ')'
2783 /// [C11] '_Alignas' '(' constant-expression ')'
2784 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2785 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2786 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2787  SourceLocation *EndLoc) {
2788  assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2789  "Not an alignment-specifier!");
2790 
2791  IdentifierInfo *KWName = Tok.getIdentifierInfo();
2792  SourceLocation KWLoc = ConsumeToken();
2793 
2794  BalancedDelimiterTracker T(*this, tok::l_paren);
2795  if (T.expectAndConsume())
2796  return;
2797 
2798  SourceLocation EllipsisLoc;
2799  ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2800  if (ArgExpr.isInvalid()) {
2801  T.skipToEnd();
2802  return;
2803  }
2804 
2805  T.consumeClose();
2806  if (EndLoc)
2807  *EndLoc = T.getCloseLocation();
2808 
2809  ArgsVector ArgExprs;
2810  ArgExprs.push_back(ArgExpr.get());
2811  Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2812  ParsedAttr::AS_Keyword, EllipsisLoc);
2813 }
2814 
2815 ExprResult Parser::ParseExtIntegerArgument() {
2816  assert(Tok.is(tok::kw__ExtInt) && "Not an extended int type");
2817  ConsumeToken();
2818 
2819  BalancedDelimiterTracker T(*this, tok::l_paren);
2820  if (T.expectAndConsume())
2821  return ExprError();
2822 
2824  if (ER.isInvalid()) {
2825  T.skipToEnd();
2826  return ExprError();
2827  }
2828 
2829  if(T.consumeClose())
2830  return ExprError();
2831  return ER;
2832 }
2833 
2834 /// Determine whether we're looking at something that might be a declarator
2835 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2836 /// diagnose a missing semicolon after a prior tag definition in the decl
2837 /// specifier.
2838 ///
2839 /// \return \c true if an error occurred and this can't be any kind of
2840 /// declaration.
2841 bool
2842 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2843  DeclSpecContext DSContext,
2844  LateParsedAttrList *LateAttrs) {
2845  assert(DS.hasTagDefinition() && "shouldn't call this");
2846 
2847  bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2848  DSContext == DeclSpecContext::DSC_top_level);
2849 
2850  if (getLangOpts().CPlusPlus &&
2851  Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2852  tok::annot_template_id) &&
2853  TryAnnotateCXXScopeToken(EnteringContext)) {
2855  return true;
2856  }
2857 
2858  bool HasScope = Tok.is(tok::annot_cxxscope);
2859  // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2860  Token AfterScope = HasScope ? NextToken() : Tok;
2861 
2862  // Determine whether the following tokens could possibly be a
2863  // declarator.
2864  bool MightBeDeclarator = true;
2865  if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2866  // A declarator-id can't start with 'typename'.
2867  MightBeDeclarator = false;
2868  } else if (AfterScope.is(tok::annot_template_id)) {
2869  // If we have a type expressed as a template-id, this cannot be a
2870  // declarator-id (such a type cannot be redeclared in a simple-declaration).
2871  TemplateIdAnnotation *Annot =
2872  static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2873  if (Annot->Kind == TNK_Type_template)
2874  MightBeDeclarator = false;
2875  } else if (AfterScope.is(tok::identifier)) {
2876  const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2877 
2878  // These tokens cannot come after the declarator-id in a
2879  // simple-declaration, and are likely to come after a type-specifier.
2880  if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2881  tok::annot_cxxscope, tok::coloncolon)) {
2882  // Missing a semicolon.
2883  MightBeDeclarator = false;
2884  } else if (HasScope) {
2885  // If the declarator-id has a scope specifier, it must redeclare a
2886  // previously-declared entity. If that's a type (and this is not a
2887  // typedef), that's an error.
2888  CXXScopeSpec SS;
2890  Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2891  IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2892  Sema::NameClassification Classification = Actions.ClassifyName(
2893  getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2894  /*CCC=*/nullptr);
2895  switch (Classification.getKind()) {
2896  case Sema::NC_Error:
2898  return true;
2899 
2900  case Sema::NC_Keyword:
2901  llvm_unreachable("typo correction is not possible here");
2902 
2903  case Sema::NC_Type:
2904  case Sema::NC_TypeTemplate:
2907  // Not a previously-declared non-type entity.
2908  MightBeDeclarator = false;
2909  break;
2910 
2911  case Sema::NC_Unknown:
2912  case Sema::NC_NonType:
2914  case Sema::NC_OverloadSet:
2915  case Sema::NC_VarTemplate:
2917  case Sema::NC_Concept:
2918  // Might be a redeclaration of a prior entity.
2919  break;
2920  }
2921  }
2922  }
2923 
2924  if (MightBeDeclarator)
2925  return false;
2926 
2927  const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2929  diag::err_expected_after)
2930  << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2931 
2932  // Try to recover from the typo, by dropping the tag definition and parsing
2933  // the problematic tokens as a type.
2934  //
2935  // FIXME: Split the DeclSpec into pieces for the standalone
2936  // declaration and pieces for the following declaration, instead
2937  // of assuming that all the other pieces attach to new declaration,
2938  // and call ParsedFreeStandingDeclSpec as appropriate.
2939  DS.ClearTypeSpecType();
2940  ParsedTemplateInfo NotATemplate;
2941  ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2942  return false;
2943 }
2944 
2945 // Choose the apprpriate diagnostic error for why fixed point types are
2946 // disabled, set the previous specifier, and mark as invalid.
2947 static void SetupFixedPointError(const LangOptions &LangOpts,
2948  const char *&PrevSpec, unsigned &DiagID,
2949  bool &isInvalid) {
2950  assert(!LangOpts.FixedPoint);
2951  DiagID = diag::err_fixed_point_not_enabled;
2952  PrevSpec = ""; // Not used by diagnostic
2953  isInvalid = true;
2954 }
2955 
2956 /// ParseDeclarationSpecifiers
2957 /// declaration-specifiers: [C99 6.7]
2958 /// storage-class-specifier declaration-specifiers[opt]
2959 /// type-specifier declaration-specifiers[opt]
2960 /// [C99] function-specifier declaration-specifiers[opt]
2961 /// [C11] alignment-specifier declaration-specifiers[opt]
2962 /// [GNU] attributes declaration-specifiers[opt]
2963 /// [Clang] '__module_private__' declaration-specifiers[opt]
2964 /// [ObjC1] '__kindof' declaration-specifiers[opt]
2965 ///
2966 /// storage-class-specifier: [C99 6.7.1]
2967 /// 'typedef'
2968 /// 'extern'
2969 /// 'static'
2970 /// 'auto'
2971 /// 'register'
2972 /// [C++] 'mutable'
2973 /// [C++11] 'thread_local'
2974 /// [C11] '_Thread_local'
2975 /// [GNU] '__thread'
2976 /// function-specifier: [C99 6.7.4]
2977 /// [C99] 'inline'
2978 /// [C++] 'virtual'
2979 /// [C++] 'explicit'
2980 /// [OpenCL] '__kernel'
2981 /// 'friend': [C++ dcl.friend]
2982 /// 'constexpr': [C++0x dcl.constexpr]
2983 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2984  const ParsedTemplateInfo &TemplateInfo,
2985  AccessSpecifier AS,
2986  DeclSpecContext DSContext,
2987  LateParsedAttrList *LateAttrs) {
2988  if (DS.getSourceRange().isInvalid()) {
2989  // Start the range at the current token but make the end of the range
2990  // invalid. This will make the entire range invalid unless we successfully
2991  // consume a token.
2992  DS.SetRangeStart(Tok.getLocation());
2994  }
2995 
2996  bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2997  DSContext == DeclSpecContext::DSC_top_level);
2998  bool AttrsLastTime = false;
2999  ParsedAttributesWithRange attrs(AttrFactory);
3000  // We use Sema's policy to get bool macros right.
3001  PrintingPolicy Policy = Actions.getPrintingPolicy();
3002  while (1) {
3003  bool isInvalid = false;
3004  bool isStorageClass = false;
3005  const char *PrevSpec = nullptr;
3006  unsigned DiagID = 0;
3007 
3008  // This value needs to be set to the location of the last token if the last
3009  // token of the specifier is already consumed.
3010  SourceLocation ConsumedEnd;
3011 
3012  // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3013  // implementation for VS2013 uses _Atomic as an identifier for one of the
3014  // classes in <atomic>.
3015  //
3016  // A typedef declaration containing _Atomic<...> is among the places where
3017  // the class is used. If we are currently parsing such a declaration, treat
3018  // the token as an identifier.
3019  if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3021  !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3022  Tok.setKind(tok::identifier);
3023 
3024  SourceLocation Loc = Tok.getLocation();
3025 
3026  switch (Tok.getKind()) {
3027  default:
3028  DoneWithDeclSpec:
3029  if (!AttrsLastTime)
3030  ProhibitAttributes(attrs);
3031  else {
3032  // Reject C++11 attributes that appertain to decl specifiers as
3033  // we don't support any C++11 attributes that appertain to decl
3034  // specifiers. This also conforms to what g++ 4.8 is doing.
3035  ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
3036 
3037  DS.takeAttributesFrom(attrs);
3038  }
3039 
3040  // If this is not a declaration specifier token, we're done reading decl
3041  // specifiers. First verify that DeclSpec's are consistent.
3042  DS.Finish(Actions, Policy);
3043  return;
3044 
3045  case tok::l_square:
3046  case tok::kw_alignas:
3047  if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
3048  goto DoneWithDeclSpec;
3049 
3050  ProhibitAttributes(attrs);
3051  // FIXME: It would be good to recover by accepting the attributes,
3052  // but attempting to do that now would cause serious
3053  // madness in terms of diagnostics.
3054  attrs.clear();
3055  attrs.Range = SourceRange();
3056 
3057  ParseCXX11Attributes(attrs);
3058  AttrsLastTime = true;
3059  continue;
3060 
3061  case tok::code_completion: {
3063  if (DS.hasTypeSpecifier()) {
3064  bool AllowNonIdentifiers
3069  Scope::AtCatchScope)) == 0;
3070  bool AllowNestedNameSpecifiers
3071  = DSContext == DeclSpecContext::DSC_top_level ||
3072  (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3073 
3074  Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3075  AllowNonIdentifiers,
3076  AllowNestedNameSpecifiers);
3077  return cutOffParsing();
3078  }
3079 
3080  if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3082  else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3083  CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3085  else if (DSContext == DeclSpecContext::DSC_class)
3086  CCC = Sema::PCC_Class;
3087  else if (CurParsedObjCImpl)
3089 
3090  Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3091  return cutOffParsing();
3092  }
3093 
3094  case tok::coloncolon: // ::foo::bar
3095  // C++ scope specifier. Annotate and loop, or bail out on error.
3096  if (TryAnnotateCXXScopeToken(EnteringContext)) {
3097  if (!DS.hasTypeSpecifier())
3098  DS.SetTypeSpecError();
3099  goto DoneWithDeclSpec;
3100  }
3101  if (Tok.is(tok::coloncolon)) // ::new or ::delete
3102  goto DoneWithDeclSpec;
3103  continue;
3104 
3105  case tok::annot_cxxscope: {
3106  if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3107  goto DoneWithDeclSpec;
3108 
3109  CXXScopeSpec SS;
3111  Tok.getAnnotationRange(),
3112  SS);
3113 
3114  // We are looking for a qualified typename.
3115  Token Next = NextToken();
3116 
3117  TemplateIdAnnotation *TemplateId = Next.is(tok::annot_template_id)
3118  ? takeTemplateIdAnnotation(Next)
3119  : nullptr;
3120  if (TemplateId && TemplateId->hasInvalidName()) {
3121  // We found something like 'T::U<Args> x', but U is not a template.
3122  // Assume it was supposed to be a type.
3123  DS.SetTypeSpecError();
3124  ConsumeAnnotationToken();
3125  break;
3126  }
3127 
3128  if (TemplateId && TemplateId->Kind == TNK_Type_template) {
3129  // We have a qualified template-id, e.g., N::A<int>
3130 
3131  // If this would be a valid constructor declaration with template
3132  // arguments, we will reject the attempt to form an invalid type-id
3133  // referring to the injected-class-name when we annotate the token,
3134  // per C++ [class.qual]p2.
3135  //
3136  // To improve diagnostics for this case, parse the declaration as a
3137  // constructor (and reject the extra template arguments later).
3138  if ((DSContext == DeclSpecContext::DSC_top_level ||
3139  DSContext == DeclSpecContext::DSC_class) &&
3140  TemplateId->Name &&
3141  Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3142  isConstructorDeclarator(/*Unqualified=*/false)) {
3143  // The user meant this to be an out-of-line constructor
3144  // definition, but template arguments are not allowed
3145  // there. Just allow this as a constructor; we'll
3146  // complain about it later.
3147  goto DoneWithDeclSpec;
3148  }
3149 
3150  DS.getTypeSpecScope() = SS;
3151  ConsumeAnnotationToken(); // The C++ scope.
3152  assert(Tok.is(tok::annot_template_id) &&
3153  "ParseOptionalCXXScopeSpecifier not working");
3154  AnnotateTemplateIdTokenAsType(SS);
3155  continue;
3156  }
3157 
3158  if (TemplateId && TemplateId->Kind == TNK_Concept_template &&
3159  GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype)) {
3160  DS.getTypeSpecScope() = SS;
3161  // This is a qualified placeholder-specifier, e.g., ::C<int> auto ...
3162  // Consume the scope annotation and continue to consume the template-id
3163  // as a placeholder-specifier.
3164  ConsumeAnnotationToken();
3165  continue;
3166  }
3167 
3168  if (Next.is(tok::annot_typename)) {
3169  DS.getTypeSpecScope() = SS;
3170  ConsumeAnnotationToken(); // The C++ scope.
3171  TypeResult T = getTypeAnnotation(Tok);
3173  Tok.getAnnotationEndLoc(),
3174  PrevSpec, DiagID, T, Policy);
3175  if (isInvalid)
3176  break;
3177  DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3178  ConsumeAnnotationToken(); // The typename
3179  }
3180 
3181  if (Next.isNot(tok::identifier))
3182  goto DoneWithDeclSpec;
3183 
3184  // Check whether this is a constructor declaration. If we're in a
3185  // context where the identifier could be a class name, and it has the
3186  // shape of a constructor declaration, process it as one.
3187  if ((DSContext == DeclSpecContext::DSC_top_level ||
3188  DSContext == DeclSpecContext::DSC_class) &&
3189  Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3190  &SS) &&
3191  isConstructorDeclarator(/*Unqualified*/ false))
3192  goto DoneWithDeclSpec;
3193 
3194  ParsedType TypeRep =
3195  Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3196  getCurScope(), &SS, false, false, nullptr,
3197  /*IsCtorOrDtorName=*/false,
3198  /*WantNontrivialTypeSourceInfo=*/true,
3199  isClassTemplateDeductionContext(DSContext));
3200 
3201  // If the referenced identifier is not a type, then this declspec is
3202  // erroneous: We already checked about that it has no type specifier, and
3203  // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3204  // typename.
3205  if (!TypeRep) {
3206  if (TryAnnotateTypeConstraint())
3207  goto DoneWithDeclSpec;
3208  if (Tok.isNot(tok::annot_cxxscope) ||
3209  NextToken().isNot(tok::identifier))
3210  continue;
3211  // Eat the scope spec so the identifier is current.
3212  ConsumeAnnotationToken();
3213  ParsedAttributesWithRange Attrs(AttrFactory);
3214  if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3215  if (!Attrs.empty()) {
3216  AttrsLastTime = true;
3217  attrs.takeAllFrom(Attrs);
3218  }
3219  continue;
3220  }
3221  goto DoneWithDeclSpec;
3222  }
3223 
3224  DS.getTypeSpecScope() = SS;
3225  ConsumeAnnotationToken(); // The C++ scope.
3226 
3227  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3228  DiagID, TypeRep, Policy);
3229  if (isInvalid)
3230  break;
3231 
3232  DS.SetRangeEnd(Tok.getLocation());
3233  ConsumeToken(); // The typename.
3234 
3235  continue;
3236  }
3237 
3238  case tok::annot_typename: {
3239  // If we've previously seen a tag definition, we were almost surely
3240  // missing a semicolon after it.
3241  if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3242  goto DoneWithDeclSpec;
3243 
3244  TypeResult T = getTypeAnnotation(Tok);
3245  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3246  DiagID, T, Policy);
3247  if (isInvalid)
3248  break;
3249 
3250  DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3251  ConsumeAnnotationToken(); // The typename
3252 
3253  continue;
3254  }
3255 
3256  case tok::kw___is_signed:
3257  // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3258  // typically treats it as a trait. If we see __is_signed as it appears
3259  // in libstdc++, e.g.,
3260  //
3261  // static const bool __is_signed;
3262  //
3263  // then treat __is_signed as an identifier rather than as a keyword.
3264  if (DS.getTypeSpecType() == TST_bool &&
3267  TryKeywordIdentFallback(true);
3268 
3269  // We're done with the declaration-specifiers.
3270  goto DoneWithDeclSpec;
3271 
3272  // typedef-name
3273  case tok::kw___super:
3274  case tok::kw_decltype:
3275  case tok::identifier: {
3276  // This identifier can only be a typedef name if we haven't already seen
3277  // a type-specifier. Without this check we misparse:
3278  // typedef int X; struct Y { short X; }; as 'short int'.
3279  if (DS.hasTypeSpecifier())
3280  goto DoneWithDeclSpec;
3281 
3282  // If the token is an identifier named "__declspec" and Microsoft
3283  // extensions are not enabled, it is likely that there will be cascading
3284  // parse errors if this really is a __declspec attribute. Attempt to
3285  // recognize that scenario and recover gracefully.
3286  if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3287  Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3288  Diag(Loc, diag::err_ms_attributes_not_enabled);
3289 
3290  // The next token should be an open paren. If it is, eat the entire
3291  // attribute declaration and continue.
3292  if (NextToken().is(tok::l_paren)) {
3293  // Consume the __declspec identifier.
3294  ConsumeToken();
3295 
3296  // Eat the parens and everything between them.
3297  BalancedDelimiterTracker T(*this, tok::l_paren);
3298  if (T.consumeOpen()) {
3299  assert(false && "Not a left paren?");
3300  return;
3301  }
3302  T.skipToEnd();
3303  continue;
3304  }
3305  }
3306 
3307  // In C++, check to see if this is a scope specifier like foo::bar::, if
3308  // so handle it as such. This is important for ctor parsing.
3309  if (getLangOpts().CPlusPlus) {
3310  if (TryAnnotateCXXScopeToken(EnteringContext)) {
3311  DS.SetTypeSpecError();
3312  goto DoneWithDeclSpec;
3313  }
3314  if (!Tok.is(tok::identifier))
3315  continue;
3316  }
3317 
3318  // Check for need to substitute AltiVec keyword tokens.
3319  if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3320  break;
3321 
3322  // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3323  // allow the use of a typedef name as a type specifier.
3324  if (DS.isTypeAltiVecVector())
3325  goto DoneWithDeclSpec;
3326 
3327  if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3328  isObjCInstancetype()) {
3329  ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3330  assert(TypeRep);
3331  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3332  DiagID, TypeRep, Policy);
3333  if (isInvalid)
3334  break;
3335 
3336  DS.SetRangeEnd(Loc);
3337  ConsumeToken();
3338  continue;
3339  }
3340 
3341  // If we're in a context where the identifier could be a class name,
3342  // check whether this is a constructor declaration.
3343  if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3344  Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3345  isConstructorDeclarator(/*Unqualified*/true))
3346  goto DoneWithDeclSpec;
3347 
3348  ParsedType TypeRep = Actions.getTypeName(
3349  *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3350  false, false, nullptr, false, false,
3351  isClassTemplateDeductionContext(DSContext));
3352 
3353  // If this is not a typedef name, don't parse it as part of the declspec,
3354  // it must be an implicit int or an error.
3355  if (!TypeRep) {
3356  if (TryAnnotateTypeConstraint())
3357  goto DoneWithDeclSpec;
3358  if (Tok.isNot(tok::identifier))
3359  continue;
3360  ParsedAttributesWithRange Attrs(AttrFactory);
3361  if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3362  if (!Attrs.empty()) {
3363  AttrsLastTime = true;
3364  attrs.takeAllFrom(Attrs);
3365  }
3366  continue;
3367  }
3368  goto DoneWithDeclSpec;
3369  }
3370 
3371  // Likewise, if this is a context where the identifier could be a template
3372  // name, check whether this is a deduction guide declaration.
3373  if (getLangOpts().CPlusPlus17 &&
3374  (DSContext == DeclSpecContext::DSC_class ||
3375  DSContext == DeclSpecContext::DSC_top_level) &&
3377  Tok.getLocation()) &&
3378  isConstructorDeclarator(/*Unqualified*/ true,
3379  /*DeductionGuide*/ true))
3380  goto DoneWithDeclSpec;
3381 
3382  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3383  DiagID, TypeRep, Policy);
3384  if (isInvalid)
3385  break;
3386 
3387  DS.SetRangeEnd(Tok.getLocation());
3388  ConsumeToken(); // The identifier
3389 
3390  // Objective-C supports type arguments and protocol references
3391  // following an Objective-C object or object pointer
3392  // type. Handle either one of them.
3393  if (Tok.is(tok::less) && getLangOpts().ObjC) {
3394  SourceLocation NewEndLoc;
3395  TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3396  Loc, TypeRep, /*consumeLastToken=*/true,
3397  NewEndLoc);
3398  if (NewTypeRep.isUsable()) {
3399  DS.UpdateTypeRep(NewTypeRep.get());
3400  DS.SetRangeEnd(NewEndLoc);
3401  }
3402  }
3403 
3404  // Need to support trailing type qualifiers (e.g. "id<p> const").
3405  // If a type specifier follows, it will be diagnosed elsewhere.
3406  continue;
3407  }
3408 
3409  // type-name or placeholder-specifier
3410  case tok::annot_template_id: {
3411  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3412 
3413  if (TemplateId->hasInvalidName()) {
3414  DS.SetTypeSpecError();
3415  break;
3416  }
3417 
3418  if (TemplateId->Kind == TNK_Concept_template) {
3419  // If we've already diagnosed that this type-constraint has invalid
3420  // arguemnts, drop it and just form 'auto' or 'decltype(auto)'.
3421  if (TemplateId->hasInvalidArgs())
3422  TemplateId = nullptr;
3423 
3424  if (NextToken().is(tok::identifier)) {
3425  Diag(Loc, diag::err_placeholder_expected_auto_or_decltype_auto)
3426  << FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
3427  // Attempt to continue as if 'auto' was placed here.
3428  isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3429  TemplateId, Policy);
3430  break;
3431  }
3432  if (!NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
3433  goto DoneWithDeclSpec;
3434  ConsumeAnnotationToken();
3435  SourceLocation AutoLoc = Tok.getLocation();
3436  if (TryConsumeToken(tok::kw_decltype)) {
3437  BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3438  if (Tracker.consumeOpen()) {
3439  // Something like `void foo(Iterator decltype i)`
3440  Diag(Tok, diag::err_expected) << tok::l_paren;
3441  } else {
3442  if (!TryConsumeToken(tok::kw_auto)) {
3443  // Something like `void foo(Iterator decltype(int) i)`
3444  Tracker.skipToEnd();
3445  Diag(Tok, diag::err_placeholder_expected_auto_or_decltype_auto)
3447  Tok.getLocation()),
3448  "auto");
3449  } else {
3450  Tracker.consumeClose();
3451  }
3452  }
3453  ConsumedEnd = Tok.getLocation();
3454  // Even if something went wrong above, continue as if we've seen
3455  // `decltype(auto)`.
3456  isInvalid = DS.SetTypeSpecType(TST_decltype_auto, Loc, PrevSpec,
3457  DiagID, TemplateId, Policy);
3458  } else {
3459  isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3460  TemplateId, Policy);
3461  }
3462  break;
3463  }
3464 
3465  if (TemplateId->Kind != TNK_Type_template &&
3466  TemplateId->Kind != TNK_Undeclared_template) {
3467  // This template-id does not refer to a type name, so we're
3468  // done with the type-specifiers.
3469  goto DoneWithDeclSpec;
3470  }
3471 
3472  // If we're in a context where the template-id could be a
3473  // constructor name or specialization, check whether this is a
3474  // constructor declaration.
3475  if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3476  Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3477  isConstructorDeclarator(/*Unqualified=*/true))
3478  goto DoneWithDeclSpec;
3479 
3480  // Turn the template-id annotation token into a type annotation
3481  // token, then try again to parse it as a type-specifier.
3482  CXXScopeSpec SS;
3483  AnnotateTemplateIdTokenAsType(SS);
3484  continue;
3485  }
3486 
3487  // GNU attributes support.
3488  case tok::kw___attribute:
3489  ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3490  continue;
3491 
3492  // Microsoft declspec support.
3493  case tok::kw___declspec:
3494  ParseMicrosoftDeclSpecs(DS.getAttributes());
3495  continue;
3496 
3497  // Microsoft single token adornments.
3498  case tok::kw___forceinline: {
3499  isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3500  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3501  SourceLocation AttrNameLoc = Tok.getLocation();
3502  DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3503  nullptr, 0, ParsedAttr::AS_Keyword);
3504  break;
3505  }
3506 
3507  case tok::kw___unaligned:
3508  isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3509  getLangOpts());
3510  break;
3511 
3512  case tok::kw___sptr:
3513  case tok::kw___uptr:
3514  case tok::kw___ptr64:
3515  case tok::kw___ptr32:
3516  case tok::kw___w64:
3517  case tok::kw___cdecl:
3518  case tok::kw___stdcall:
3519  case tok::kw___fastcall:
3520  case tok::kw___thiscall:
3521  case tok::kw___regcall:
3522  case tok::kw___vectorcall:
3523  ParseMicrosoftTypeAttributes(DS.getAttributes());
3524  continue;
3525 
3526  // Borland single token adornments.
3527  case tok::kw___pascal:
3528  ParseBorlandTypeAttributes(DS.getAttributes());
3529  continue;
3530 
3531  // OpenCL single token adornments.
3532  case tok::kw___kernel:
3533  ParseOpenCLKernelAttributes(DS.getAttributes());
3534  continue;
3535 
3536  // Nullability type specifiers.
3537  case tok::kw__Nonnull:
3538  case tok::kw__Nullable:
3539  case tok::kw__Null_unspecified:
3540  ParseNullabilityTypeSpecifiers(DS.getAttributes());
3541  continue;
3542 
3543  // Objective-C 'kindof' types.
3544  case tok::kw___kindof:
3545  DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3546  nullptr, 0, ParsedAttr::AS_Keyword);
3547  (void)ConsumeToken();
3548  continue;
3549 
3550  // storage-class-specifier
3551  case tok::kw_typedef:
3553  PrevSpec, DiagID, Policy);
3554  isStorageClass = true;
3555  break;
3556  case tok::kw_extern:
3558  Diag(Tok, diag::ext_thread_before) << "extern";
3560  PrevSpec, DiagID, Policy);
3561  isStorageClass = true;
3562  break;
3563  case tok::kw___private_extern__:
3565  Loc, PrevSpec, DiagID, Policy);
3566  isStorageClass = true;
3567  break;
3568  case tok::kw_static:
3570  Diag(Tok, diag::ext_thread_before) << "static";
3572  PrevSpec, DiagID, Policy);
3573  isStorageClass = true;
3574  break;
3575  case tok::kw_auto:
3576  if (getLangOpts().CPlusPlus11) {
3577  if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3579  PrevSpec, DiagID, Policy);
3580  if (!isInvalid)
3581  Diag(Tok, diag::ext_auto_storage_class)
3583  } else
3584  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3585  DiagID, Policy);
3586  } else
3588  PrevSpec, DiagID, Policy);
3589  isStorageClass = true;
3590  break;
3591  case tok::kw___auto_type:
3592  Diag(Tok, diag::ext_auto_type);
3594  DiagID, Policy);
3595  break;
3596  case tok::kw_register:
3598  PrevSpec, DiagID, Policy);
3599  isStorageClass = true;
3600  break;
3601  case tok::kw_mutable:
3603  PrevSpec, DiagID, Policy);
3604  isStorageClass = true;
3605  break;
3606  case tok::kw___thread:
3608  PrevSpec, DiagID);
3609  isStorageClass = true;
3610  break;
3611  case tok::kw_thread_local:
3613  PrevSpec, DiagID);
3614  isStorageClass = true;
3615  break;
3616  case tok::kw__Thread_local:
3617  if (!getLangOpts().C11)
3618  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3620  Loc, PrevSpec, DiagID);
3621  isStorageClass = true;
3622  break;
3623 
3624  // function-specifier
3625  case tok::kw_inline:
3626  isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3627  break;
3628  case tok::kw_virtual:
3629  // C++ for OpenCL does not allow virtual function qualifier, to avoid
3630  // function pointers restricted in OpenCL v2.0 s6.9.a.
3631  if (getLangOpts().OpenCLCPlusPlus) {
3632  DiagID = diag::err_openclcxx_virtual_function;
3633  PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3634  isInvalid = true;
3635  }
3636  else {
3637  isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3638  }
3639  break;
3640  case tok::kw_explicit: {
3641  SourceLocation ExplicitLoc = Loc;
3642  SourceLocation CloseParenLoc;
3643  ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
3644  ConsumedEnd = ExplicitLoc;
3645  ConsumeToken(); // kw_explicit
3646  if (Tok.is(tok::l_paren)) {
3647  if (getLangOpts().CPlusPlus20 || isExplicitBool() == TPResult::True) {
3648  Diag(Tok.getLocation(), getLangOpts().CPlusPlus20
3649  ? diag::warn_cxx17_compat_explicit_bool
3650  : diag::ext_explicit_bool);
3651 
3652  ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
3653  BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3654  Tracker.consumeOpen();
3655  ExplicitExpr = ParseConstantExpression();
3656  ConsumedEnd = Tok.getLocation();
3657  if (ExplicitExpr.isUsable()) {
3658  CloseParenLoc = Tok.getLocation();
3659  Tracker.consumeClose();
3660  ExplicitSpec =
3661  Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
3662  } else
3663  Tracker.skipToEnd();
3664  } else {
3665  Diag(Tok.getLocation(), diag::warn_cxx20_compat_explicit_bool);
3666  }
3667  }
3668  isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
3669  ExplicitSpec, CloseParenLoc);
3670  break;
3671  }
3672  case tok::kw__Noreturn:
3673  if (!getLangOpts().C11)
3674  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3675  isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3676  break;
3677 
3678  // alignment-specifier
3679  case tok::kw__Alignas:
3680  if (!getLangOpts().C11)
3681  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3682  ParseAlignmentSpecifier(DS.getAttributes());
3683  continue;
3684 
3685  // friend
3686  case tok::kw_friend:
3687  if (DSContext == DeclSpecContext::DSC_class)
3688  isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3689  else {
3690  PrevSpec = ""; // not actually used by the diagnostic
3691  DiagID = diag::err_friend_invalid_in_context;
3692  isInvalid = true;
3693  }
3694  break;
3695 
3696  // Modules
3697  case tok::kw___module_private__:
3698  isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3699  break;
3700 
3701  // constexpr, consteval, constinit specifiers
3702  case tok::kw_constexpr:
3704  PrevSpec, DiagID);
3705  break;
3706  case tok::kw_consteval:
3708  PrevSpec, DiagID);
3709  break;
3710  case tok::kw_constinit:
3712  PrevSpec, DiagID);
3713  break;
3714 
3715  // type-specifier
3716  case tok::kw_short:
3718  DiagID, Policy);
3719  break;
3720  case tok::kw_long:
3723  DiagID, Policy);
3724  else
3726  PrevSpec, DiagID, Policy);
3727  break;
3728  case tok::kw___int64:
3730  PrevSpec, DiagID, Policy);
3731  break;
3732  case tok::kw_signed:
3733  isInvalid =
3734  DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
3735  break;
3736  case tok::kw_unsigned:
3738  DiagID);
3739  break;
3740  case tok::kw__Complex:
3741  if (!getLangOpts().C99)
3742  Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3744  DiagID);
3745  break;
3746  case tok::kw__Imaginary:
3747  if (!getLangOpts().C99)
3748  Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3750  DiagID);
3751  break;
3752  case tok::kw_void:
3753  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3754  DiagID, Policy);
3755  break;
3756  case tok::kw_char:
3757  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3758  DiagID, Policy);
3759  break;
3760  case tok::kw_int:
3761  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3762  DiagID, Policy);
3763  break;
3764  case tok::kw__ExtInt: {
3765  ExprResult ER = ParseExtIntegerArgument();
3766  if (ER.isInvalid())
3767  continue;
3768  isInvalid = DS.SetExtIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
3769  ConsumedEnd = PrevTokLocation;
3770  break;
3771  }
3772  case tok::kw___int128:
3773  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3774  DiagID, Policy);
3775  break;
3776  case tok::kw_half:
3777  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3778  DiagID, Policy);
3779  break;
3780  case tok::kw___bf16:
3781  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec,
3782  DiagID, Policy);
3783  break;
3784  case tok::kw_float:
3785  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3786  DiagID, Policy);
3787  break;
3788  case tok::kw_double:
3789  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3790  DiagID, Policy);
3791  break;
3792  case tok::kw__Float16:
3793  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3794  DiagID, Policy);
3795  break;
3796  case tok::kw__Accum:
3797  if (!getLangOpts().FixedPoint) {
3798  SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3799  } else {
3800  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3801  DiagID, Policy);
3802  }
3803  break;
3804  case tok::kw__Fract:
3805  if (!getLangOpts().FixedPoint) {
3806  SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3807  } else {
3808  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3809  DiagID, Policy);
3810  }
3811  break;
3812  case tok::kw__Sat:
3813  if (!getLangOpts().FixedPoint) {
3814  SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3815  } else {
3816  isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3817  }
3818  break;
3819  case tok::kw___float128:
3820  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3821  DiagID, Policy);
3822  break;
3823  case tok::kw_wchar_t:
3824  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3825  DiagID, Policy);
3826  break;
3827  case tok::kw_char8_t:
3828  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3829  DiagID, Policy);
3830  break;
3831  case tok::kw_char16_t:
3832  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3833  DiagID, Policy);
3834  break;
3835  case tok::kw_char32_t:
3836  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3837  DiagID, Policy);
3838  break;
3839  case tok::kw_bool:
3840  case tok::kw__Bool:
3841  if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
3842  Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3843 
3844  if (Tok.is(tok::kw_bool) &&
3847  PrevSpec = ""; // Not used by the diagnostic.
3848  DiagID = diag::err_bool_redeclaration;
3849  // For better error recovery.
3850  Tok.setKind(tok::identifier);
3851  isInvalid = true;
3852  } else {
3853  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3854  DiagID, Policy);
3855  }
3856  break;
3857  case tok::kw__Decimal32:
3859  DiagID, Policy);
3860  break;
3861  case tok::kw__Decimal64:
3863  DiagID, Policy);
3864  break;
3865  case tok::kw__Decimal128:
3867  DiagID, Policy);
3868  break;
3869  case tok::kw___vector:
3870  isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3871  break;
3872  case tok::kw___pixel:
3873  isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3874  break;
3875  case tok::kw___bool:
3876  isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3877  break;
3878  case tok::kw_pipe:
3879  if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200 &&
3880  !getLangOpts().OpenCLCPlusPlus)) {
3881  // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3882  // support the "pipe" word as identifier.
3884  goto DoneWithDeclSpec;
3885  }
3886  isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3887  break;
3888 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
3889  case tok::kw_##ImgType##_t: \
3890  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3891  DiagID, Policy); \
3892  break;
3893 #include "clang/Basic/OpenCLImageTypes.def"
3894  case tok::kw___unknown_anytype:
3896  PrevSpec, DiagID, Policy);
3897  break;
3898 
3899  // class-specifier:
3900  case tok::kw_class:
3901  case tok::kw_struct:
3902  case tok::kw___interface:
3903  case tok::kw_union: {
3904  tok::TokenKind Kind = Tok.getKind();
3905  ConsumeToken();
3906 
3907  // These are attributes following class specifiers.
3908  // To produce better diagnostic, we parse them when
3909  // parsing class specifier.
3910  ParsedAttributesWithRange Attributes(AttrFactory);
3911  ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3912  EnteringContext, DSContext, Attributes);
3913 
3914  // If there are attributes following class specifier,
3915  // take them over and handle them here.
3916  if (!Attributes.empty()) {
3917  AttrsLastTime = true;
3918  attrs.takeAllFrom(Attributes);
3919  }
3920  continue;
3921  }
3922 
3923  // enum-specifier:
3924  case tok::kw_enum:
3925  ConsumeToken();
3926  ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3927  continue;
3928 
3929  // cv-qualifier:
3930  case tok::kw_const:
3931  isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3932  getLangOpts());
3933  break;
3934  case tok::kw_volatile:
3935  isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3936  getLangOpts());
3937  break;
3938  case tok::kw_restrict:
3939  isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3940  getLangOpts());
3941  break;
3942 
3943  // C++ typename-specifier:
3944  case tok::kw_typename:
3946  DS.SetTypeSpecError();
3947  goto DoneWithDeclSpec;
3948  }
3949  if (!Tok.is(tok::kw_typename))
3950  continue;
3951  break;
3952 
3953  // GNU typeof support.
3954  case tok::kw_typeof:
3955  ParseTypeofSpecifier(DS);
3956  continue;
3957 
3958  case tok::annot_decltype:
3959  ParseDecltypeSpecifier(DS);
3960  continue;
3961 
3962  case tok::annot_pragma_pack:
3963  HandlePragmaPack();
3964  continue;
3965 
3966  case tok::annot_pragma_ms_pragma:
3967  HandlePragmaMSPragma();
3968  continue;
3969 
3970  case tok::annot_pragma_ms_vtordisp:
3971  HandlePragmaMSVtorDisp();
3972  continue;
3973 
3974  case tok::annot_pragma_ms_pointers_to_members:
3975  HandlePragmaMSPointersToMembers();
3976  continue;
3977 
3978  case tok::kw___underlying_type:
3979  ParseUnderlyingTypeSpecifier(DS);
3980  continue;
3981 
3982  case tok::kw__Atomic:
3983  // C11 6.7.2.4/4:
3984  // If the _Atomic keyword is immediately followed by a left parenthesis,
3985  // it is interpreted as a type specifier (with a type name), not as a
3986  // type qualifier.
3987  if (!getLangOpts().C11)
3988  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3989 
3990  if (NextToken().is(tok::l_paren)) {
3991  ParseAtomicSpecifier(DS);
3992  continue;
3993  }
3994  isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3995  getLangOpts());
3996  break;
3997 
3998  // OpenCL address space qualifiers:
3999  case tok::kw___generic:
4000  // generic address space is introduced only in OpenCL v2.0
4001  // see OpenCL C Spec v2.0 s6.5.5
4002  if (Actions.getLangOpts().OpenCLVersion < 200 &&
4003  !Actions.getLangOpts().OpenCLCPlusPlus) {
4004  DiagID = diag::err_opencl_unknown_type_specifier;
4005  PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4006  isInvalid = true;
4007  break;
4008  }
4009  LLVM_FALLTHROUGH;
4010  case tok::kw_private:
4011  // It's fine (but redundant) to check this for __generic on the
4012  // fallthrough path; we only form the __generic token in OpenCL mode.
4013  if (!getLangOpts().OpenCL)
4014  goto DoneWithDeclSpec;
4015  LLVM_FALLTHROUGH;
4016  case tok::kw___private:
4017  case tok::kw___global:
4018  case tok::kw___local:
4019  case tok::kw___constant:
4020  // OpenCL access qualifiers:
4021  case tok::kw___read_only:
4022  case tok::kw___write_only:
4023  case tok::kw___read_write:
4024  ParseOpenCLQualifiers(DS.getAttributes());
4025  break;
4026 
4027  case tok::less:
4028  // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
4029  // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
4030  // but we support it.
4031  if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
4032  goto DoneWithDeclSpec;
4033 
4034  SourceLocation StartLoc = Tok.getLocation();
4035  SourceLocation EndLoc;
4036  TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
4037  if (Type.isUsable()) {
4038  if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
4039  PrevSpec, DiagID, Type.get(),
4040  Actions.getASTContext().getPrintingPolicy()))
4041  Diag(StartLoc, DiagID) << PrevSpec;
4042 
4043  DS.SetRangeEnd(EndLoc);
4044  } else {
4045  DS.SetTypeSpecError();
4046  }
4047 
4048  // Need to support trailing type qualifiers (e.g. "id<p> const").
4049  // If a type specifier follows, it will be diagnosed elsewhere.
4050  continue;
4051  }
4052 
4053  DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
4054 
4055  // If the specifier wasn't legal, issue a diagnostic.
4056  if (isInvalid) {
4057  assert(PrevSpec && "Method did not return previous specifier!");
4058  assert(DiagID);
4059 
4060  if (DiagID == diag::ext_duplicate_declspec ||
4061  DiagID == diag::ext_warn_duplicate_declspec ||
4062  DiagID == diag::err_duplicate_declspec)
4063  Diag(Loc, DiagID) << PrevSpec
4065  SourceRange(Loc, DS.getEndLoc()));
4066  else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4067  Diag(Loc, DiagID) << getLangOpts().OpenCLCPlusPlus
4068  << getLangOpts().getOpenCLVersionTuple().getAsString()
4069  << PrevSpec << isStorageClass;
4070  } else
4071  Diag(Loc, DiagID) << PrevSpec;
4072  }
4073 
4074  if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
4075  // After an error the next token can be an annotation token.
4076  ConsumeAnyToken();
4077 
4078  AttrsLastTime = false;
4079  }
4080 }
4081 
4082 /// ParseStructDeclaration - Parse a struct declaration without the terminating
4083 /// semicolon.
4084 ///
4085 /// Note that a struct declaration refers to a declaration in a struct,
4086 /// not to the declaration of a struct.
4087 ///
4088 /// struct-declaration:
4089 /// [C2x] attributes-specifier-seq[opt]
4090 /// specifier-qualifier-list struct-declarator-list
4091 /// [GNU] __extension__ struct-declaration
4092 /// [GNU] specifier-qualifier-list
4093 /// struct-declarator-list:
4094 /// struct-declarator
4095 /// struct-declarator-list ',' struct-declarator
4096 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
4097 /// struct-declarator:
4098 /// declarator
4099 /// [GNU] declarator attributes[opt]
4100 /// declarator[opt] ':' constant-expression
4101 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
4102 ///
4103 void Parser::ParseStructDeclaration(
4104  ParsingDeclSpec &DS,
4105  llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4106 
4107  if (Tok.is(tok::kw___extension__)) {
4108  // __extension__ silences extension warnings in the subexpression.
4109  ExtensionRAIIObject O(Diags); // Use RAII to do this.
4110  ConsumeToken();
4111  return ParseStructDeclaration(DS, FieldsCallback);
4112  }
4113 
4114  // Parse leading attributes.
4115  ParsedAttributesWithRange Attrs(AttrFactory);
4116  MaybeParseCXX11Attributes(Attrs);
4117  DS.takeAttributesFrom(Attrs);
4118 
4119  // Parse the common specifier-qualifiers-list piece.
4120  ParseSpecifierQualifierList(DS);
4121 
4122  // If there are no declarators, this is a free-standing declaration
4123  // specifier. Let the actions module cope with it.
4124  if (Tok.is(tok::semi)) {
4125  RecordDecl *AnonRecord = nullptr;
4126  Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
4127  DS, AnonRecord);
4128  assert(!AnonRecord && "Did not expect anonymous struct or union here");
4129  DS.complete(TheDecl);
4130  return;
4131  }
4132 
4133  // Read struct-declarators until we find the semicolon.
4134  bool FirstDeclarator = true;
4135  SourceLocation CommaLoc;
4136  while (1) {
4137  ParsingFieldDeclarator DeclaratorInfo(*this, DS);
4138  DeclaratorInfo.D.setCommaLoc(CommaLoc);
4139 
4140  // Attributes are only allowed here on successive declarators.
4141  if (!FirstDeclarator) {
4142  // However, this does not apply for [[]] attributes (which could show up
4143  // before or after the __attribute__ attributes).
4144  DiagnoseAndSkipCXX11Attributes();
4145  MaybeParseGNUAttributes(DeclaratorInfo.D);
4146  DiagnoseAndSkipCXX11Attributes();
4147  }
4148 
4149  /// struct-declarator: declarator
4150  /// struct-declarator: declarator[opt] ':' constant-expression
4151  if (Tok.isNot(tok::colon)) {
4152  // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4154  ParseDeclarator(DeclaratorInfo.D);
4155  } else
4156  DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4157 
4158  if (TryConsumeToken(tok::colon)) {
4160  if (Res.isInvalid())
4161  SkipUntil(tok::semi, StopBeforeMatch);
4162  else
4163  DeclaratorInfo.BitfieldSize = Res.get();
4164  }
4165 
4166  // If attributes exist after the declarator, parse them.
4167  MaybeParseGNUAttributes(DeclaratorInfo.D);
4168 
4169  // We're done with this declarator; invoke the callback.
4170  FieldsCallback(DeclaratorInfo);
4171 
4172  // If we don't have a comma, it is either the end of the list (a ';')
4173  // or an error, bail out.
4174  if (!TryConsumeToken(tok::comma, CommaLoc))
4175  return;
4176 
4177  FirstDeclarator = false;
4178  }
4179 }
4180 
4181 /// ParseStructUnionBody
4182 /// struct-contents:
4183 /// struct-declaration-list
4184 /// [EXT] empty
4185 /// [GNU] "struct-declaration-list" without terminating ';'
4186 /// struct-declaration-list:
4187 /// struct-declaration
4188 /// struct-declaration-list struct-declaration
4189 /// [OBC] '@' 'defs' '(' class-name ')'
4190 ///
4191 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4193  PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4194  "parsing struct/union body");
4195  assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4196 
4197  BalancedDelimiterTracker T(*this, tok::l_brace);
4198  if (T.consumeOpen())
4199  return;
4200 
4201  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4203 
4204  // While we still have something to read, read the declarations in the struct.
4205  while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4206  Tok.isNot(tok::eof)) {
4207  // Each iteration of this loop reads one struct-declaration.
4208 
4209  // Check for extraneous top-level semicolon.
4210  if (Tok.is(tok::semi)) {
4211  ConsumeExtraSemi(InsideStruct, TagType);
4212  continue;
4213  }
4214 
4215  // Parse _Static_assert declaration.
4216  if (Tok.is(tok::kw__Static_assert)) {
4217  SourceLocation DeclEnd;
4218  ParseStaticAssertDeclaration(DeclEnd);
4219  continue;
4220  }
4221 
4222  if (Tok.is(tok::annot_pragma_pack)) {
4223  HandlePragmaPack();
4224  continue;
4225  }
4226 
4227  if (Tok.is(tok::annot_pragma_align)) {
4228  HandlePragmaAlign();
4229  continue;
4230  }
4231 
4232  if (Tok.is(tok::annot_pragma_openmp)) {
4233  // Result can be ignored, because it must be always empty.
4234  AccessSpecifier AS = AS_none;
4235  ParsedAttributesWithRange Attrs(AttrFactory);
4236  (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4237  continue;
4238  }
4239 
4240  if (tok::isPragmaAnnotation(Tok.getKind())) {
4241  Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4243  TagType, Actions.getASTContext().getPrintingPolicy());
4244  ConsumeAnnotationToken();
4245  continue;
4246  }
4247 
4248  if (!Tok.is(tok::at)) {
4249  auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4250  // Install the declarator into the current TagDecl.
4251  Decl *Field =
4252  Actions.ActOnField(getCurScope(), TagDecl,
4253  FD.D.getDeclSpec().getSourceRange().getBegin(),
4254  FD.D, FD.BitfieldSize);
4255  FD.complete(Field);
4256  };
4257 
4258  // Parse all the comma separated declarators.
4259  ParsingDeclSpec DS(*this);
4260  ParseStructDeclaration(DS, CFieldCallback);
4261  } else { // Handle @defs
4262  ConsumeToken();
4263  if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4264  Diag(Tok, diag::err_unexpected_at);
4265  SkipUntil(tok::semi);
4266  continue;
4267  }
4268  ConsumeToken();
4269  ExpectAndConsume(tok::l_paren);
4270  if (!Tok.is(tok::identifier)) {
4271  Diag(Tok, diag::err_expected) << tok::identifier;
4272  SkipUntil(tok::semi);
4273  continue;
4274  }
4275  SmallVector<Decl *, 16> Fields;
4276  Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4277  Tok.getIdentifierInfo(), Fields);
4278  ConsumeToken();
4279  ExpectAndConsume(tok::r_paren);
4280  }
4281 
4282  if (TryConsumeToken(tok::semi))
4283  continue;
4284 
4285  if (Tok.is(tok::r_brace)) {
4286  ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4287  break;
4288  }
4289 
4290  ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4291  // Skip to end of block or statement to avoid ext-warning on extra ';'.
4292  SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4293  // If we stopped at a ';', eat it.
4294  TryConsumeToken(tok::semi);
4295  }
4296 
4297  T.consumeClose();
4298 
4299  ParsedAttributes attrs(AttrFactory);
4300  // If attributes exist after struct contents, parse them.
4301  MaybeParseGNUAttributes(attrs);
4302 
4303  SmallVector<Decl *, 32> FieldDecls(TagDecl->field_begin(),
4304  TagDecl->field_end());
4305 
4306  Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4307  T.getOpenLocation(), T.getCloseLocation(), attrs);
4308  StructScope.Exit();
4309  Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4310 }
4311 
4312 /// ParseEnumSpecifier
4313 /// enum-specifier: [C99 6.7.2.2]
4314 /// 'enum' identifier[opt] '{' enumerator-list '}'
4315 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4316 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4317 /// '}' attributes[opt]
4318 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4319 /// '}'
4320 /// 'enum' identifier
4321 /// [GNU] 'enum' attributes[opt] identifier
4322 ///
4323 /// [C++11] enum-head '{' enumerator-list[opt] '}'
4324 /// [C++11] enum-head '{' enumerator-list ',' '}'
4325 ///
4326 /// enum-head: [C++11]
4327 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4328 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
4329 /// identifier enum-base[opt]
4330 ///
4331 /// enum-key: [C++11]
4332 /// 'enum'
4333 /// 'enum' 'class'
4334 /// 'enum' 'struct'
4335 ///
4336 /// enum-base: [C++11]
4337 /// ':' type-specifier-seq
4338 ///
4339 /// [C++] elaborated-type-specifier:
4340 /// [C++] 'enum' nested-name-specifier[opt] identifier
4341 ///
4342 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4343  const ParsedTemplateInfo &TemplateInfo,
4344  AccessSpecifier AS, DeclSpecContext DSC) {
4345  // Parse the tag portion of this.
4346  if (Tok.is(tok::code_completion)) {
4347  // Code completion for an enum name.
4349  return cutOffParsing();
4350  }
4351 
4352  // If attributes exist after tag, parse them.
4353  ParsedAttributesWithRange attrs(AttrFactory);
4354  MaybeParseGNUAttributes(attrs);
4355  MaybeParseCXX11Attributes(attrs);
4356  MaybeParseMicrosoftDeclSpecs(attrs);
4357 
4358  SourceLocation ScopedEnumKWLoc;
4359  bool IsScopedUsingClassTag = false;
4360 
4361  // In C++11, recognize 'enum class' and 'enum struct'.
4362  if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4363  Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4364  : diag::ext_scoped_enum);
4365  IsScopedUsingClassTag = Tok.is(tok::kw_class);
4366  ScopedEnumKWLoc = ConsumeToken();
4367 
4368  // Attributes are not allowed between these keywords. Diagnose,
4369  // but then just treat them like they appeared in the right place.
4370  ProhibitAttributes(attrs);
4371 
4372  // They are allowed afterwards, though.
4373  MaybeParseGNUAttributes(attrs);
4374  MaybeParseCXX11Attributes(attrs);
4375  MaybeParseMicrosoftDeclSpecs(attrs);
4376  }
4377 
4378  // C++11 [temp.explicit]p12:
4379  // The usual access controls do not apply to names used to specify
4380  // explicit instantiations.
4381  // We extend this to also cover explicit specializations. Note that
4382  // we don't suppress if this turns out to be an elaborated type
4383  // specifier.
4384  bool shouldDelayDiagsInTag =
4385  (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4386  TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4387  SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4388 
4389  // Determine whether this declaration is permitted to have an enum-base.
4390  AllowDefiningTypeSpec AllowEnumSpecifier =
4391  isDefiningTypeSpecifierContext(DSC);
4392  bool CanBeOpaqueEnumDeclaration =
4393  DS.isEmpty() && isOpaqueEnumDeclarationContext(DSC);
4394  bool CanHaveEnumBase = (getLangOpts().CPlusPlus11 || getLangOpts().ObjC ||
4395  getLangOpts().MicrosoftExt) &&
4396  (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes ||
4397  CanBeOpaqueEnumDeclaration);
4398 
4399  CXXScopeSpec &SS = DS.getTypeSpecScope();
4400  if (getLangOpts().CPlusPlus) {
4401  // "enum foo : bar;" is not a potential typo for "enum foo::bar;".
4403 
4404  CXXScopeSpec Spec;
4405  if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
4406  /*ObjectHadErrors=*/false,
4407  /*EnteringContext=*/true))
4408  return;
4409 
4410  if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4411  Diag(Tok, diag::err_expected) << tok::identifier;
4412  if (Tok.isNot(tok::l_brace)) {
4413  // Has no name and is not a definition.
4414  // Skip the rest of this declarator, up until the comma or semicolon.
4415  SkipUntil(tok::comma, StopAtSemi);
4416  return;
4417  }
4418  }
4419 
4420  SS = Spec;
4421  }
4422 
4423  // Must have either 'enum name' or 'enum {...}' or (rarely) 'enum : T { ... }'.
4424  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4425  Tok.isNot(tok::colon)) {
4426  Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4427 
4428  // Skip the rest of this declarator, up until the comma or semicolon.
4429  SkipUntil(tok::comma, StopAtSemi);
4430  return;
4431  }
4432 
4433  // If an identifier is present, consume and remember it.
4434  IdentifierInfo *Name = nullptr;
4435  SourceLocation NameLoc;
4436  if (Tok.is(tok::identifier)) {
4437  Name = Tok.getIdentifierInfo();
4438  NameLoc = ConsumeToken();
4439  }
4440 
4441  if (!Name && ScopedEnumKWLoc.isValid()) {
4442  // C++0x 7.2p2: The optional identifier shall not be omitted in the
4443  // declaration of a scoped enumeration.
4444  Diag(Tok, diag::err_scoped_enum_missing_identifier);
4445  ScopedEnumKWLoc = SourceLocation();
4446  IsScopedUsingClassTag = false;
4447  }
4448 
4449  // Okay, end the suppression area. We'll decide whether to emit the
4450  // diagnostics in a second.
4451  if (shouldDelayDiagsInTag)
4452  diagsFromTag.done();
4453 
4454  TypeResult BaseType;
4455  SourceRange BaseRange;
4456 
4457  bool CanBeBitfield = (getCurScope()->getFlags() & Scope::ClassScope) &&
4458  ScopedEnumKWLoc.isInvalid() && Name;
4459 
4460  // Parse the fixed underlying type.
4461  if (Tok.is(tok::colon)) {
4462  // This might be an enum-base or part of some unrelated enclosing context.
4463  //
4464  // 'enum E : base' is permitted in two circumstances:
4465  //
4466  // 1) As a defining-type-specifier, when followed by '{'.
4467  // 2) As the sole constituent of a complete declaration -- when DS is empty
4468  // and the next token is ';'.
4469  //
4470  // The restriction to defining-type-specifiers is important to allow parsing
4471  // a ? new enum E : int{}
4472  // _Generic(a, enum E : int{})
4473  // properly.
4474  //
4475  // One additional consideration applies:
4476  //
4477  // C++ [dcl.enum]p1:
4478  // A ':' following "enum nested-name-specifier[opt] identifier" within
4479  // the decl-specifier-seq of a member-declaration is parsed as part of
4480  // an enum-base.
4481  //
4482  // Other language modes supporting enumerations with fixed underlying types
4483  // do not have clear rules on this, so we disambiguate to determine whether
4484  // the tokens form a bit-field width or an enum-base.
4485 
4486  if (CanBeBitfield && !isEnumBase(CanBeOpaqueEnumDeclaration)) {
4487  // Outside C++11, do not interpret the tokens as an enum-base if they do
4488  // not make sense as one. In C++11, it's an error if this happens.
4489  if (getLangOpts().CPlusPlus11)
4490  Diag(Tok.getLocation(), diag::err_anonymous_enum_bitfield);
4491  } else if (CanHaveEnumBase || !ColonIsSacred) {
4493 
4494  // Parse a type-specifier-seq as a type. We can't just ParseTypeName here,
4495  // because under -fms-extensions,
4496  // enum E : int *p;
4497  // declares 'enum E : int; E *p;' not 'enum E : int*; E p;'.
4498  DeclSpec DS(AttrFactory);
4499  ParseSpecifierQualifierList(DS, AS, DeclSpecContext::DSC_type_specifier);
4500  Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
4501  BaseType = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
4502 
4503  BaseRange = SourceRange(ColonLoc, DeclaratorInfo.getSourceRange().getEnd());
4504 
4505  if (!getLangOpts().ObjC) {
4506  if (getLangOpts().CPlusPlus11)
4507  Diag(ColonLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type)
4508  << BaseRange;
4509  else if (getLangOpts().CPlusPlus)
4510  Diag(ColonLoc, diag::ext_cxx11_enum_fixed_underlying_type)
4511  << BaseRange;
4512  else if (getLangOpts().MicrosoftExt)
4513  Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
4514  << BaseRange;
4515  else
4516  Diag(ColonLoc, diag::ext_clang_c_enum_fixed_underlying_type)
4517  << BaseRange;
4518  }
4519  }
4520  }
4521 
4522  // There are four options here. If we have 'friend enum foo;' then this is a
4523  // friend declaration, and cannot have an accompanying definition. If we have
4524  // 'enum foo;', then this is a forward declaration. If we have
4525  // 'enum foo {...' then this is a definition. Otherwise we have something
4526  // like 'enum foo xyz', a reference.
4527  //
4528  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4529  // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4530  // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4531  //
4532  Sema::TagUseKind TUK;
4533  if (AllowEnumSpecifier == AllowDefiningTypeSpec::No)
4534  TUK = Sema::TUK_Reference;
4535  else if (Tok.is(tok::l_brace)) {
4536  if (DS.isFriendSpecified()) {
4537  Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4538  << SourceRange(DS.getFriendSpecLoc());
4539  ConsumeBrace();
4540  SkipUntil(tok::r_brace, StopAtSemi);
4541  // Discard any other definition-only pieces.
4542  attrs.clear();
4543  ScopedEnumKWLoc = SourceLocation();
4544  IsScopedUsingClassTag = false;
4545  BaseType = TypeResult();
4546  TUK = Sema::TUK_Friend;
4547  } else {
4548  TUK = Sema::TUK_Definition;
4549  }
4550  } else if (!isTypeSpecifier(DSC) &&
4551  (Tok.is(tok::semi) ||
4552  (Tok.isAtStartOfLine() &&
4553  !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4554  // An opaque-enum-declaration is required to be standalone (no preceding or
4555  // following tokens in the declaration). Sema enforces this separately by
4556  // diagnosing anything else in the DeclSpec.
4558  if (Tok.isNot(tok::semi)) {
4559  // A semicolon was missing after this declaration. Diagnose and recover.
4560  ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4561  PP.EnterToken(Tok, /*IsReinject=*/true);
4562  Tok.setKind(tok::semi);
4563  }
4564  } else {
4565  TUK = Sema::TUK_Reference;
4566  }
4567 
4568  bool IsElaboratedTypeSpecifier =
4569  TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend;
4570 
4571  // If this is an elaborated type specifier nested in a larger declaration,
4572  // and we delayed diagnostics before, just merge them into the current pool.
4573  if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4574  diagsFromTag.redelay();
4575  }
4576 
4577  MultiTemplateParamsArg TParams;
4578  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4579  TUK != Sema::TUK_Reference) {
4580  if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4581  // Skip the rest of this declarator, up until the comma or semicolon.
4582  Diag(Tok, diag::err_enum_template);
4583  SkipUntil(tok::comma, StopAtSemi);
4584  return;
4585  }
4586 
4587  if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4588  // Enumerations can't be explicitly instantiated.
4589  DS.SetTypeSpecError();
4590  Diag(StartLoc, diag::err_explicit_instantiation_enum);
4591  return;
4592  }
4593 
4594  assert(TemplateInfo.TemplateParams && "no template parameters");
4595  TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4596  TemplateInfo.TemplateParams->size());
4597  }
4598 
4599  if (!Name && TUK != Sema::TUK_Definition) {
4600  Diag(Tok, diag::err_enumerator_unnamed_no_def);
4601 
4602  // Skip the rest of this declarator, up until the comma or semicolon.
4603  SkipUntil(tok::comma, StopAtSemi);
4604  return;
4605  }
4606 
4607  // An elaborated-type-specifier has a much more constrained grammar:
4608  //
4609  // 'enum' nested-name-specifier[opt] identifier
4610  //
4611  // If we parsed any other bits, reject them now.
4612  //
4613  // MSVC and (for now at least) Objective-C permit a full enum-specifier
4614  // or opaque-enum-declaration anywhere.
4615  if (IsElaboratedTypeSpecifier && !getLangOpts().MicrosoftExt &&
4616  !getLangOpts().ObjC) {
4617  ProhibitAttributes(attrs);
4618  if (BaseType.isUsable())
4619  Diag(BaseRange.getBegin(), diag::ext_enum_base_in_type_specifier)
4620  << (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes) << BaseRange;
4621  else if (ScopedEnumKWLoc.isValid())
4622  Diag(ScopedEnumKWLoc, diag::ext_elaborated_enum_class)
4623  << FixItHint::CreateRemoval(ScopedEnumKWLoc) << IsScopedUsingClassTag;
4624  }
4625 
4626  stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4627 
4628  Sema::SkipBodyInfo SkipBody;
4629  if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4630  NextToken().is(tok::identifier))
4631  SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4632  NextToken().getIdentifierInfo(),
4633  NextToken().getLocation());
4634 
4635  bool Owned = false;
4636  bool IsDependent = false;
4637  const char *PrevSpec = nullptr;
4638  unsigned DiagID;
4639  Decl *TagDecl = Actions.ActOnTag(
4640  getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
4641  attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4642  ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
4643  DSC == DeclSpecContext::DSC_type_specifier,
4644  DSC == DeclSpecContext::DSC_template_param ||
4645  DSC == DeclSpecContext::DSC_template_type_arg,
4646  &SkipBody);
4647 
4648  if (SkipBody.ShouldSkip) {
4649  assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4650 
4651  BalancedDelimiterTracker T(*this, tok::l_brace);
4652  T.consumeOpen();
4653  T.skipToEnd();
4654 
4655  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4656  NameLoc.isValid() ? NameLoc : StartLoc,
4657  PrevSpec, DiagID, TagDecl, Owned,
4658  Actions.getASTContext().getPrintingPolicy()))
4659  Diag(StartLoc, DiagID) << PrevSpec;
4660  return;
4661  }
4662 
4663  if (IsDependent) {
4664  // This enum has a dependent nested-name-specifier. Handle it as a
4665  // dependent tag.
4666  if (!Name) {
4667  DS.SetTypeSpecError();
4668  Diag(Tok, diag::err_expected_type_name_after_typename);
4669  return;
4670  }
4671 
4672  TypeResult Type = Actions.ActOnDependentTag(
4673  getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4674  if (Type.isInvalid()) {
4675  DS.SetTypeSpecError();
4676  return;
4677  }
4678 
4679  if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4680  NameLoc.isValid() ? NameLoc : StartLoc,
4681  PrevSpec, DiagID, Type.get(),
4682  Actions.getASTContext().getPrintingPolicy()))
4683  Diag(StartLoc, DiagID) << PrevSpec;
4684 
4685  return;
4686  }
4687 
4688  if (!TagDecl) {
4689  // The action failed to produce an enumeration tag. If this is a
4690  // definition, consume the entire definition.
4691  if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4692  ConsumeBrace();
4693  SkipUntil(tok::r_brace, StopAtSemi);
4694  }
4695 
4696  DS.SetTypeSpecError();
4697  return;
4698  }
4699 
4700  if (Tok.is(tok::l_brace) && TUK == Sema::TUK_Definition) {
4701  Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4702  ParseEnumBody(StartLoc, D);
4703  if (SkipBody.CheckSameAsPrevious &&
4704  !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4705  DS.SetTypeSpecError();
4706  return;
4707  }
4708  }
4709 
4710  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4711  NameLoc.isValid() ? NameLoc : StartLoc,
4712  PrevSpec, DiagID, TagDecl, Owned,
4713  Actions.getASTContext().getPrintingPolicy()))
4714  Diag(StartLoc, DiagID) << PrevSpec;
4715 }
4716 
4717 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4718 /// enumerator-list:
4719 /// enumerator
4720 /// enumerator-list ',' enumerator
4721 /// enumerator:
4722 /// enumeration-constant attributes[opt]
4723 /// enumeration-constant attributes[opt] '=' constant-expression
4724 /// enumeration-constant:
4725 /// identifier
4726 ///
4727 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4728  // Enter the scope of the enum body and start the definition.
4729  ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4731 
4732  BalancedDelimiterTracker T(*this, tok::l_brace);
4733  T.consumeOpen();
4734 
4735  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4736  if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4737  Diag(Tok, diag::err_empty_enum);
4738 
4739  SmallVector<Decl *, 32> EnumConstantDecls;
4740  SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4741 
4742  Decl *LastEnumConstDecl = nullptr;
4743 
4744  // Parse the enumerator-list.
4745  while (Tok.isNot(tok::r_brace)) {
4746  // Parse enumerator. If failed, try skipping till the start of the next
4747  // enumerator definition.
4748  if (Tok.isNot(tok::identifier)) {
4749  Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4750  if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4751  TryConsumeToken(tok::comma))
4752  continue;
4753  break;
4754  }
4755  IdentifierInfo *Ident = Tok.getIdentifierInfo();
4756  SourceLocation IdentLoc = ConsumeToken();
4757 
4758  // If attributes exist after the enumerator, parse them.
4759  ParsedAttributesWithRange attrs(AttrFactory);
4760  MaybeParseGNUAttributes(attrs);
4761  ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4762  if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4763  if (getLangOpts().CPlusPlus)
4764  Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4765  ? diag::warn_cxx14_compat_ns_enum_attribute
4766  : diag::ext_ns_enum_attribute)
4767  << 1 /*enumerator*/;
4768  ParseCXX11Attributes(attrs);
4769  }
4770 
4771  SourceLocation EqualLoc;
4772  ExprResult AssignedVal;
4773  EnumAvailabilityDiags.emplace_back(*this);
4774 
4775  EnterExpressionEvaluationContext ConstantEvaluated(
4777  if (TryConsumeToken(tok::equal, EqualLoc)) {
4779  if (AssignedVal.isInvalid())
4780  SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4781  }
4782 
4783  // Install the enumerator constant into EnumDecl.
4784  Decl *EnumConstDecl = Actions.ActOnEnumConstant(
4785  getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4786  EqualLoc, AssignedVal.get());
4787  EnumAvailabilityDiags.back().done();
4788 
4789  EnumConstantDecls.push_back(EnumConstDecl);
4790  LastEnumConstDecl = EnumConstDecl;
4791 
4792  if (Tok.is(tok::identifier)) {
4793  // We're missing a comma between enumerators.
4795  Diag(Loc, diag::err_enumerator_list_missing_comma)
4796  << FixItHint::CreateInsertion(Loc, ", ");
4797  continue;
4798  }
4799 
4800  // Emumerator definition must be finished, only comma or r_brace are
4801  // allowed here.
4802  SourceLocation CommaLoc;
4803  if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4804  if (EqualLoc.isValid())
4805  Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4806  << tok::comma;
4807  else
4808  Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4809  if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4810  if (TryConsumeToken(tok::comma, CommaLoc))
4811  continue;
4812  } else {
4813  break;
4814  }
4815  }
4816 
4817  // If comma is followed by r_brace, emit appropriate warning.
4818  if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4819  if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4820  Diag(CommaLoc, getLangOpts().CPlusPlus ?
4821  diag::ext_enumerator_list_comma_cxx :
4822  diag::ext_enumerator_list_comma_c)
4823  << FixItHint::CreateRemoval(CommaLoc);
4824  else if (getLangOpts().CPlusPlus11)
4825  Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4826  << FixItHint::CreateRemoval(CommaLoc);
4827  break;
4828  }
4829  }
4830 
4831  // Eat the }.
4832  T.consumeClose();
4833 
4834  // If attributes exist after the identifier list, parse them.
4835  ParsedAttributes attrs(AttrFactory);
4836  MaybeParseGNUAttributes(attrs);
4837 
4838  Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4839  getCurScope(), attrs);
4840 
4841  // Now handle enum constant availability diagnostics.
4842  assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4843  for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4845  EnumAvailabilityDiags[i].redelay();
4846  PD.complete(EnumConstantDecls[i]);
4847  }
4848 
4849  EnumScope.Exit();
4850  Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4851 
4852  // The next token must be valid after an enum definition. If not, a ';'
4853  // was probably forgotten.
4854  bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4855  if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4856  ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4857  // Push this token back into the preprocessor and change our current token
4858  // to ';' so that the rest of the code recovers as though there were an
4859  // ';' after the definition.
4860  PP.EnterToken(Tok, /*IsReinject=*/true);
4861  Tok.setKind(tok::semi);
4862  }
4863 }
4864 
4865 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4866 /// is definitely a type-specifier. Return false if it isn't part of a type
4867 /// specifier or if we're not sure.
4868 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4869  switch (Tok.getKind()) {
4870  default: return false;
4871  // type-specifiers
4872  case tok::kw_short:
4873  case tok::kw_long:
4874  case tok::kw___int64:
4875  case tok::kw___int128:
4876  case tok::kw_signed:
4877  case tok::kw_unsigned:
4878  case tok::kw__Complex:
4879  case tok::kw__Imaginary:
4880  case tok::kw_void:
4881  case tok::kw_char:
4882  case tok::kw_wchar_t:
4883  case tok::kw_char8_t:
4884  case tok::kw_char16_t:
4885  case tok::kw_char32_t:
4886  case tok::kw_int:
4887  case tok::kw__ExtInt:
4888  case tok::kw___bf16:
4889  case tok::kw_half:
4890  case tok::kw_float:
4891  case tok::kw_double:
4892  case tok::kw__Accum:
4893  case tok::kw__Fract:
4894  case tok::kw__Float16:
4895  case tok::kw___float128:
4896  case tok::kw_bool:
4897  case tok::kw__Bool:
4898  case tok::kw__Decimal32:
4899  case tok::kw__Decimal64:
4900  case tok::kw__Decimal128:
4901  case tok::kw___vector:
4902 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4903 #include "clang/Basic/OpenCLImageTypes.def"
4904 
4905  // struct-or-union-specifier (C99) or class-specifier (C++)
4906  case tok::kw_class:
4907  case tok::kw_struct:
4908  case tok::kw___interface:
4909  case tok::kw_union:
4910  // enum-specifier
4911  case tok::kw_enum:
4912 
4913  // typedef-name
4914  case tok::annot_typename:
4915  return true;
4916  }
4917 }
4918 
4919 /// isTypeSpecifierQualifier - Return true if the current token could be the
4920 /// start of a specifier-qualifier-list.
4921 bool Parser::isTypeSpecifierQualifier() {
4922  switch (Tok.getKind()) {
4923  default: return false;
4924 
4925  case tok::identifier: // foo::bar
4926  if (TryAltiVecVectorToken())
4927  return true;
4928  LLVM_FALLTHROUGH;
4929  case tok::kw_typename: // typename T::type
4930  // Annotate typenames and C++ scope specifiers. If we get one, just
4931  // recurse to handle whatever we get.
4933  return true;
4934  if (Tok.is(tok::identifier))
4935  return false;
4936  return isTypeSpecifierQualifier();
4937 
4938  case tok::coloncolon: // ::foo::bar
4939  if (NextToken().is(tok::kw_new) || // ::new
4940  NextToken().is(tok::kw_delete)) // ::delete
4941  return false;
4942 
4944  return true;
4945  return isTypeSpecifierQualifier();
4946 
4947  // GNU attributes support.
4948  case tok::kw___attribute:
4949  // GNU typeof support.
4950  case tok::kw_typeof:
4951 
4952  // type-specifiers
4953  case tok::kw_short:
4954  case tok::kw_long:
4955  case tok::kw___int64:
4956  case tok::kw___int128:
4957  case tok::kw_signed:
4958  case tok::kw_unsigned:
4959  case tok::kw__Complex:
4960  case tok::kw__Imaginary:
4961  case tok::kw_void:
4962  case tok::kw_char:
4963  case tok::kw_wchar_t:
4964  case tok::kw_char8_t:
4965  case tok::kw_char16_t:
4966  case tok::kw_char32_t:
4967  case tok::kw_int:
4968  case tok::kw__ExtInt:
4969  case tok::kw_half:
4970  case tok::kw___bf16:
4971  case tok::kw_float:
4972  case tok::kw_double:
4973  case tok::kw__Accum:
4974  case tok::kw__Fract:
4975  case tok::kw__Float16:
4976  case tok::kw___float128:
4977  case tok::kw_bool:
4978  case tok::kw__Bool:
4979  case tok::kw__Decimal32:
4980  case tok::kw__Decimal64:
4981  case tok::kw__Decimal128:
4982  case tok::kw___vector:
4983 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4984 #include "clang/Basic/OpenCLImageTypes.def"
4985 
4986  // struct-or-union-specifier (C99) or class-specifier (C++)
4987  case tok::kw_class:
4988  case tok::kw_struct:
4989  case tok::kw___interface:
4990  case tok::kw_union:
4991  // enum-specifier
4992  case tok::kw_enum:
4993 
4994  // type-qualifier
4995  case tok::kw_const:
4996  case tok::kw_volatile:
4997  case tok::kw_restrict:
4998  case tok::kw__Sat:
4999 
5000  // Debugger support.
5001  case tok::kw___unknown_anytype:
5002 
5003  // typedef-name
5004  case tok::annot_typename:
5005  return true;
5006 
5007  // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5008  case tok::less:
5009  return getLangOpts().ObjC;
5010 
5011  case tok::kw___cdecl:
5012  case tok::kw___stdcall:
5013  case tok::kw___fastcall:
5014  case tok::kw___thiscall:
5015  case tok::kw___regcall:
5016  case tok::kw___vectorcall:
5017  case tok::kw___w64:
5018  case tok::kw___ptr64:
5019  case tok::kw___ptr32:
5020  case tok::kw___pascal:
5021  case tok::kw___unaligned:
5022 
5023  case tok::kw__Nonnull:
5024  case tok::kw__Nullable:
5025  case tok::kw__Null_unspecified:
5026 
5027  case tok::kw___kindof:
5028 
5029  case tok::kw___private:
5030  case tok::kw___local:
5031  case tok::kw___global:
5032  case tok::kw___constant:
5033  case tok::kw___generic:
5034  case tok::kw___read_only:
5035  case tok::kw___read_write:
5036  case tok::kw___write_only:
5037  return true;
5038 
5039  case tok::kw_private:
5040  return getLangOpts().OpenCL;
5041 
5042  // C11 _Atomic
5043  case tok::kw__Atomic:
5044  return true;
5045  }
5046 }
5047 
5048 /// isDeclarationSpecifier() - Return true if the current token is part of a
5049 /// declaration specifier.
5050 ///
5051 /// \param DisambiguatingWithExpression True to indicate that the purpose of
5052 /// this check is to disambiguate between an expression and a declaration.
5053 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
5054  switch (Tok.getKind()) {
5055  default: return false;
5056 
5057  case tok::kw_pipe:
5058  return (getLangOpts().OpenCL && getLangOpts().OpenCLVersion >= 200) ||
5059  getLangOpts().OpenCLCPlusPlus;
5060 
5061  case tok::identifier: // foo::bar
5062  // Unfortunate hack to support "Class.factoryMethod" notation.
5063  if (getLangOpts().ObjC && NextToken().is(tok::period))
5064  return false;
5065  if (TryAltiVecVectorToken())
5066  return true;
5067  LLVM_FALLTHROUGH;
5068  case tok::kw_decltype: // decltype(T())::type
5069  case tok::kw_typename: // typename T::type
5070  // Annotate typenames and C++ scope specifiers. If we get one, just
5071  // recurse to handle whatever we get.
5073  return true;
5074  if (TryAnnotateTypeConstraint())
5075  return true;
5076  if (Tok.is(tok::identifier))
5077  return false;
5078 
5079  // If we're in Objective-C and we have an Objective-C class type followed
5080  // by an identifier and then either ':' or ']', in a place where an
5081  // expression is permitted, then this is probably a class message send
5082  // missing the initial '['. In this case, we won't consider this to be
5083  // the start of a declaration.
5084  if (DisambiguatingWithExpression &&
5085  isStartOfObjCClassMessageMissingOpenBracket())
5086  return false;
5087 
5088  return isDeclarationSpecifier();
5089 
5090  case tok::coloncolon: // ::foo::bar
5091  if (NextToken().is(tok::kw_new) || // ::new
5092  NextToken().is(tok::kw_delete)) // ::delete
5093  return false;
5094 
5095  // Annotate typenames and C++ scope specifiers. If we get one, just
5096  // recurse to handle whatever we get.
5098  return true;
5099  return isDeclarationSpecifier();
5100 
5101  // storage-class-specifier
5102  case tok::kw_typedef:
5103  case tok::kw_extern:
5104  case tok::kw___private_extern__:
5105  case tok::kw_static:
5106  case tok::kw_auto:
5107  case tok::kw___auto_type:
5108  case tok::kw_register:
5109  case tok::kw___thread:
5110  case tok::kw_thread_local:
5111  case tok::kw__Thread_local:
5112 
5113  // Modules
5114  case tok::kw___module_private__:
5115 
5116  // Debugger support
5117  case tok::kw___unknown_anytype:
5118 
5119  // type-specifiers
5120  case tok::kw_short:
5121  case tok::kw_long:
5122  case tok::kw___int64:
5123  case tok::kw___int128:
5124  case tok::kw_signed:
5125  case tok::kw_unsigned:
5126  case tok::kw__Complex:
5127  case tok::kw__Imaginary:
5128  case tok::kw_void:
5129  case tok::kw_char:
5130  case tok::kw_wchar_t:
5131  case tok::kw_char8_t:
5132  case tok::kw_char16_t:
5133  case tok::kw_char32_t:
5134 
5135  case tok::kw_int:
5136  case tok::kw__ExtInt:
5137  case tok::kw_half:
5138  case tok::kw___bf16:
5139  case tok::kw_float:
5140  case tok::kw_double:
5141  case tok::kw__Accum:
5142  case tok::kw__Fract:
5143  case tok::kw__Float16:
5144  case tok::kw___float128:
5145  case tok::kw_bool:
5146  case tok::kw__Bool:
5147  case tok::kw__Decimal32:
5148  case tok::kw__Decimal64:
5149  case tok::kw__Decimal128:
5150  case tok::kw___vector:
5151 
5152  // struct-or-union-specifier (C99) or class-specifier (C++)
5153  case tok::kw_class:
5154  case tok::kw_struct:
5155  case tok::kw_union:
5156  case tok::kw___interface:
5157  // enum-specifier
5158  case tok::kw_enum:
5159 
5160  // type-qualifier
5161  case tok::kw_const:
5162  case tok::kw_volatile:
5163  case tok::kw_restrict:
5164  case tok::kw__Sat:
5165 
5166  // function-specifier
5167  case tok::kw_inline:
5168  case tok::kw_virtual:
5169  case tok::kw_explicit:
5170  case tok::kw__Noreturn:
5171 
5172  // alignment-specifier
5173  case tok::kw__Alignas:
5174 
5175  // friend keyword.
5176  case tok::kw_friend:
5177 
5178  // static_assert-declaration
5179  case tok::kw__Static_assert:
5180 
5181  // GNU typeof support.
5182  case tok::kw_typeof:
5183 
5184  // GNU attributes.
5185  case tok::kw___attribute:
5186 
5187  // C++11 decltype and constexpr.
5188  case tok::annot_decltype:
5189  case tok::kw_constexpr:
5190 
5191  // C++20 consteval and constinit.
5192  case tok::kw_consteval:
5193  case tok::kw_constinit:
5194 
5195  // C11 _Atomic
5196  case tok::kw__Atomic:
5197  return true;
5198 
5199  // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5200  case tok::less:
5201  return getLangOpts().ObjC;
5202 
5203  // typedef-name
5204  case tok::annot_typename:
5205  return !DisambiguatingWithExpression ||
5206  !isStartOfObjCClassMessageMissingOpenBracket();
5207 
5208  // placeholder-type-specifier
5209  case tok::annot_template_id: {
5210  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
5211  if (TemplateId->hasInvalidName())
5212  return true;
5213  // FIXME: What about type templates that have only been annotated as
5214  // annot_template_id, not as annot_typename?
5215  return isTypeConstraintAnnotation() &&
5216  (NextToken().is(tok::kw_auto) || NextToken().is(tok::kw_decltype));
5217  }
5218 
5219  case tok::annot_cxxscope: {
5220  TemplateIdAnnotation *TemplateId =
5221  NextToken().is(tok::annot_template_id)
5222  ? takeTemplateIdAnnotation(NextToken())
5223  : nullptr;
5224  if (TemplateId && TemplateId->hasInvalidName())
5225  return true;
5226  // FIXME: What about type templates that have only been annotated as
5227  // annot_template_id, not as annot_typename?
5228  if (NextToken().is(tok::identifier) && TryAnnotateTypeConstraint())
5229  return true;
5230  return isTypeConstraintAnnotation() &&
5231  GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype);
5232  }
5233 
5234  case tok::kw___declspec:
5235  case tok::kw___cdecl:
5236  case tok::kw___stdcall:
5237  case tok::kw___fastcall:
5238  case tok::kw___thiscall:
5239  case tok::kw___regcall:
5240  case tok::kw___vectorcall:
5241  case tok::kw___w64:
5242  case tok::kw___sptr:
5243  case tok::kw___uptr:
5244  case tok::kw___ptr64:
5245  case tok::kw___ptr32:
5246  case tok::kw___forceinline:
5247  case tok::kw___pascal:
5248  case tok::kw___unaligned:
5249 
5250  case tok::kw__Nonnull:
5251  case tok::kw__Nullable:
5252  case tok::kw__Null_unspecified:
5253 
5254  case tok::kw___kindof:
5255 
5256  case tok::kw___private:
5257  case tok::kw___local:
5258  case tok::kw___global:
5259  case tok::kw___constant:
5260  case tok::kw___generic:
5261  case tok::kw___read_only:
5262  case tok::kw___read_write:
5263  case tok::kw___write_only:
5264 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5265 #include "clang/Basic/OpenCLImageTypes.def"
5266 
5267  return true;
5268 
5269  case tok::kw_private:
5270  return getLangOpts().OpenCL;
5271  }
5272 }
5273 
5274 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
5275  TentativeParsingAction TPA(*this);
5276 
5277  // Parse the C++ scope specifier.
5278  CXXScopeSpec SS;
5279  if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
5280  /*ObjectHadErrors=*/false,
5281  /*EnteringContext=*/true)) {
5282  TPA.Revert();
5283  return false;
5284  }
5285 
5286  // Parse the constructor name.
5287  if (Tok.is(tok::identifier)) {
5288  // We already know that we have a constructor name; just consume
5289  // the token.
5290  ConsumeToken();
5291  } else if (Tok.is(tok::annot_template_id)) {
5292  ConsumeAnnotationToken();
5293  } else {
5294  TPA.Revert();
5295  return false;
5296  }
5297 
5298  // There may be attributes here, appertaining to the constructor name or type
5299  // we just stepped past.
5300  SkipCXX11Attributes();
5301 
5302  // Current class name must be followed by a left parenthesis.
5303  if (Tok.isNot(tok::l_paren)) {
5304  TPA.Revert();
5305  return false;
5306  }
5307  ConsumeParen();
5308 
5309  // A right parenthesis, or ellipsis followed by a right parenthesis signals
5310  // that we have a constructor.
5311  if (Tok.is(tok::r_paren) ||
5312  (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
5313  TPA.Revert();
5314  return true;
5315  }
5316 
5317  // A C++11 attribute here signals that we have a constructor, and is an
5318  // attribute on the first constructor parameter.
5319  if (getLangOpts().CPlusPlus11 &&
5320  isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5321  /*OuterMightBeMessageSend*/ true)) {
5322  TPA.Revert();
5323  return true;
5324  }
5325 
5326  // If we need to, enter the specified scope.
5327  DeclaratorScopeObj DeclScopeObj(*this, SS);
5328  if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
5329  DeclScopeObj.EnterDeclaratorScope();
5330 
5331  // Optionally skip Microsoft attributes.
5332  ParsedAttributes Attrs(AttrFactory);
5333  MaybeParseMicrosoftAttributes(Attrs);
5334 
5335  // Check whether the next token(s) are part of a declaration
5336  // specifier, in which case we have the start of a parameter and,
5337  // therefore, we know that this is a constructor.
5338  bool IsConstructor = false;
5339  if (isDeclarationSpecifier())
5340  IsConstructor = true;
5341  else if (Tok.is(tok::identifier) ||
5342  (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5343  // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5344  // This might be a parenthesized member name, but is more likely to
5345  // be a constructor declaration with an invalid argument type. Keep
5346  // looking.
5347  if (Tok.is(tok::annot_cxxscope))
5348  ConsumeAnnotationToken();
5349  ConsumeToken();
5350 
5351  // If this is not a constructor, we must be parsing a declarator,
5352  // which must have one of the following syntactic forms (see the
5353  // grammar extract at the start of ParseDirectDeclarator):
5354  switch (Tok.getKind()) {
5355  case tok::l_paren:
5356  // C(X ( int));
5357  case tok::l_square:
5358  // C(X [ 5]);
5359  // C(X [ [attribute]]);
5360  case tok::coloncolon:
5361  // C(X :: Y);
5362  // C(X :: *p);
5363  // Assume this isn't a constructor, rather than assuming it's a
5364  // constructor with an unnamed parameter of an ill-formed type.
5365  break;
5366 
5367  case tok::r_paren:
5368  // C(X )
5369 
5370  // Skip past the right-paren and any following attributes to get to
5371  // the function body or trailing-return-type.
5372  ConsumeParen();
5373  SkipCXX11Attributes();
5374 
5375  if (DeductionGuide) {
5376  // C(X) -> ... is a deduction guide.
5377  IsConstructor = Tok.is(tok::arrow);
5378  break;
5379  }
5380  if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
5381  // Assume these were meant to be constructors:
5382  // C(X) : (the name of a bit-field cannot be parenthesized).
5383  // C(X) try (this is otherwise ill-formed).
5384  IsConstructor = true;
5385  }
5386  if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
5387  // If we have a constructor name within the class definition,
5388  // assume these were meant to be constructors:
5389  // C(X) {
5390  // C(X) ;
5391  // ... because otherwise we would be declaring a non-static data
5392  // member that is ill-formed because it's of the same type as its
5393  // surrounding class.
5394  //
5395  // FIXME: We can actually do this whether or not the name is qualified,
5396  // because if it is qualified in this context it must be being used as
5397  // a constructor name.
5398  // currently, so we're somewhat conservative here.
5399  IsConstructor = IsUnqualified;
5400  }
5401  break;
5402 
5403  default:
5404  IsConstructor = true;
5405  break;
5406  }
5407  }
5408 
5409  TPA.Revert();
5410  return IsConstructor;
5411 }
5412 
5413 /// ParseTypeQualifierListOpt
5414 /// type-qualifier-list: [C99 6.7.5]
5415 /// type-qualifier
5416 /// [vendor] attributes
5417 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5418 /// type-qualifier-list type-qualifier
5419 /// [vendor] type-qualifier-list attributes
5420 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5421 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
5422 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
5423 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5424 /// AttrRequirements bitmask values.
5425 void Parser::ParseTypeQualifierListOpt(
5426  DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5427  bool IdentifierRequired,
5428  Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
5429  if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
5430  isCXX11AttributeSpecifier()) {
5431  ParsedAttributesWithRange attrs(AttrFactory);
5432  ParseCXX11Attributes(attrs);
5433  DS.takeAttributesFrom(attrs);
5434  }
5435 
5436  SourceLocation EndLoc;
5437 
5438  while (1) {
5439  bool isInvalid = false;
5440  const char *PrevSpec = nullptr;
5441  unsigned DiagID = 0;
5442  SourceLocation Loc = Tok.getLocation();
5443 
5444  switch (Tok.getKind()) {
5445  case tok::code_completion:
5447  (*CodeCompletionHandler)();
5448  else
5449  Actions.CodeCompleteTypeQualifiers(DS);
5450  return cutOffParsing();
5451 
5452  case tok::kw_const:
5453  isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
5454  getLangOpts());
5455  break;
5456  case tok::kw_volatile:
5457  isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5458  getLangOpts());
5459  break;
5460  case tok::kw_restrict:
5461  isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5462  getLangOpts());
5463  break;
5464  case tok::kw__Atomic:
5465  if (!AtomicAllowed)
5466  goto DoneWithTypeQuals;
5467  if (!getLangOpts().C11)
5468  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
5469  isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5470  getLangOpts());
5471  break;
5472 
5473  // OpenCL qualifiers:
5474  case tok::kw_private:
5475  if (!getLangOpts().OpenCL)
5476  goto DoneWithTypeQuals;
5477  LLVM_FALLTHROUGH;
5478  case tok::kw___private:
5479  case tok::kw___global:
5480  case tok::kw___local:
5481  case tok::kw___constant:
5482  case tok::kw___generic:
5483  case tok::kw___read_only:
5484  case tok::kw___write_only:
5485  case tok::kw___read_write:
5486  ParseOpenCLQualifiers(DS.getAttributes());
5487  break;
5488 
5489  case tok::kw___unaligned:
5490  isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5491  getLangOpts());
5492  break;
5493  case tok::kw___uptr:
5494  // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
5495  // with the MS modifier keyword.
5496  if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
5497  IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5498  if (TryKeywordIdentFallback(false))
5499  continue;
5500  }
5501  LLVM_FALLTHROUGH;
5502  case tok::kw___sptr:
5503  case tok::kw___w64:
5504  case tok::kw___ptr64:
5505  case tok::kw___ptr32:
5506  case tok::kw___cdecl:
5507  case tok::kw___stdcall:
5508  case tok::kw___fastcall:
5509  case tok::kw___thiscall:
5510  case tok::kw___regcall:
5511  case tok::kw___vectorcall:
5512  if (AttrReqs & AR_DeclspecAttributesParsed) {
5513  ParseMicrosoftTypeAttributes(DS.getAttributes());
5514  continue;
5515  }
5516  goto DoneWithTypeQuals;
5517  case tok::kw___pascal:
5518  if (AttrReqs & AR_VendorAttributesParsed) {
5519  ParseBorlandTypeAttributes(DS.getAttributes());
5520  continue;
5521  }
5522  goto DoneWithTypeQuals;
5523 
5524  // Nullability type specifiers.
5525  case tok::kw__Nonnull:
5526  case tok::kw__Nullable:
5527  case tok::kw__Null_unspecified:
5528  ParseNullabilityTypeSpecifiers(DS.getAttributes());
5529  continue;
5530 
5531  // Objective-C 'kindof' types.
5532  case tok::kw___kindof:
5533  DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
5534  nullptr, 0, ParsedAttr::AS_Keyword);
5535  (void)ConsumeToken();
5536  continue;
5537 
5538  case tok::kw___attribute:
5539  if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5540  // When GNU attributes are expressly forbidden, diagnose their usage.
5541  Diag(Tok, diag::err_attributes_not_allowed);
5542 
5543  // Parse the attributes even if they are rejected to ensure that error
5544  // recovery is graceful.
5545  if (AttrReqs & AR_GNUAttributesParsed ||
5546  AttrReqs & AR_GNUAttributesParsedAndRejected) {
5547  ParseGNUAttributes(DS.getAttributes());
5548  continue; // do *not* consume the next token!
5549  }
5550  // otherwise, FALL THROUGH!
5551  LLVM_FALLTHROUGH;
5552  default:
5553  DoneWithTypeQuals:
5554  // If this is not a type-qualifier token, we're done reading type
5555  // qualifiers. First verify that DeclSpec's are consistent.
5556  DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
5557  if (EndLoc.isValid())
5558  DS.SetRangeEnd(EndLoc);
5559  return;
5560  }
5561 
5562  // If the specifier combination wasn't legal, issue a diagnostic.
5563  if (isInvalid) {
5564  assert(PrevSpec && "Method did not return previous specifier!");
5565  Diag(Tok, DiagID) << PrevSpec;
5566  }
5567  EndLoc = ConsumeToken();
5568  }
5569 }
5570 
5571 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
5572 ///
5573 void Parser::ParseDeclarator(Declarator &D) {
5574  /// This implements the 'declarator' production in the C grammar, then checks
5575  /// for well-formedness and issues diagnostics.
5576  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5577 }
5578 
5580  DeclaratorContext TheContext) {
5581  if (Kind == tok::star || Kind == tok::caret)
5582  return true;
5583 
5584  if (Kind == tok::kw_pipe &&
5585  ((Lang.OpenCL && Lang.OpenCLVersion >= 200) || Lang.OpenCLCPlusPlus))
5586  return true;
5587 
5588  if (!Lang.CPlusPlus)
5589  return false;
5590 
5591  if (Kind == tok::amp)
5592  return true;
5593 
5594  // We parse rvalue refs in C++03, because otherwise the errors are scary.
5595  // But we must not parse them in conversion-type-ids and new-type-ids, since
5596  // those can be legitimately followed by a && operator.
5597  // (The same thing can in theory happen after a trailing-return-type, but
5598  // since those are a C++11 feature, there is no rejects-valid issue there.)
5599  if (Kind == tok::ampamp)
5600  return Lang.CPlusPlus11 || (TheContext != DeclaratorContext::ConversionId &&
5601  TheContext != DeclaratorContext::CXXNew);
5602 
5603  return false;
5604 }
5605 
5606 // Indicates whether the given declarator is a pipe declarator.
5607 static bool isPipeDeclerator(const Declarator &D) {
5608  const unsigned NumTypes = D.getNumTypeObjects();
5609 
5610  for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5612  return true;
5613 
5614  return false;
5615 }
5616 
5617 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5618 /// is parsed by the function passed to it. Pass null, and the direct-declarator
5619 /// isn't parsed at all, making this function effectively parse the C++
5620 /// ptr-operator production.
5621 ///
5622 /// If the grammar of this construct is extended, matching changes must also be
5623 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5624 /// isConstructorDeclarator.
5625 ///
5626 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5627 /// [C] pointer[opt] direct-declarator
5628 /// [C++] direct-declarator
5629 /// [C++] ptr-operator declarator
5630 ///
5631 /// pointer: [C99 6.7.5]
5632 /// '*' type-qualifier-list[opt]
5633 /// '*' type-qualifier-list[opt] pointer
5634 ///
5635 /// ptr-operator:
5636 /// '*' cv-qualifier-seq[opt]
5637 /// '&'
5638 /// [C++0x] '&&'
5639 /// [GNU] '&' restrict[opt] attributes[opt]
5640 /// [GNU?] '&&' restrict[opt] attributes[opt]
5641 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
5642 void Parser::ParseDeclaratorInternal(Declarator &D,
5643  DirectDeclParseFunction DirectDeclParser) {
5644  if (Diags.hasAllExtensionsSilenced())
5645  D.setExtension();
5646 
5647  // C++ member pointers start with a '::' or a nested-name.
5648  // Member pointers get special handling, since there's no place for the
5649  // scope spec in the generic path below.
5650  if (getLangOpts().CPlusPlus &&
5651  (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
5652  (Tok.is(tok::identifier) &&
5653  (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
5654  Tok.is(tok::annot_cxxscope))) {
5655  bool EnteringContext = D.getContext() == DeclaratorContext::File ||
5657  CXXScopeSpec SS;
5658  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
5659  /*ObjectHadErrors=*/false, EnteringContext);
5660 
5661  if (SS.isNotEmpty()) {
5662  if (Tok.isNot(tok::star)) {
5663  // The scope spec really belongs to the direct-declarator.
5664  if (D.mayHaveIdentifier())
5665  D.getCXXScopeSpec() = SS;
5666  else
5667  AnnotateScopeToken(SS, true);
5668 
5669  if (DirectDeclParser)
5670  (this->*DirectDeclParser)(D);
5671  return;
5672  }
5673 
5674  if (SS.isValid()) {
5675  checkCompoundToken(SS.getEndLoc(), tok::coloncolon,
5676  CompoundToken::MemberPtr);
5677  }
5678 
5679  SourceLocation StarLoc = ConsumeToken();
5680  D.SetRangeEnd(StarLoc);
5681  DeclSpec DS(AttrFactory);
5682  ParseTypeQualifierListOpt(DS);
5683  D.ExtendWithDeclSpec(DS);
5684 
5685  // Recurse to parse whatever is left.
5686  ParseDeclaratorInternal(D, DirectDeclParser);
5687 
5688  // Sema will have to catch (syntactically invalid) pointers into global
5689  // scope. It has to catch pointers into namespace scope anyway.
5691  SS, DS.getTypeQualifiers(), StarLoc, DS.getEndLoc()),
5692  std::move(DS.getAttributes()),
5693  /* Don't replace range end. */ SourceLocation());
5694  return;
5695  }
5696  }
5697 
5698  tok::TokenKind Kind = Tok.getKind();
5699 
5700  if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
5701  DeclSpec DS(AttrFactory);
5702  ParseTypeQualifierListOpt(DS);
5703 
5704  D.AddTypeInfo(
5706  std::move(DS.getAttributes()), SourceLocation());
5707  }
5708 
5709  // Not a pointer, C++ reference, or block.
5711  if (DirectDeclParser)
5712  (this->*DirectDeclParser)(D);
5713  return;
5714  }
5715 
5716  // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5717  // '&&' -> rvalue reference
5718  SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
5719  D.SetRangeEnd(Loc);
5720 
5721  if (Kind == tok::star || Kind == tok::caret) {
5722  // Is a pointer.
5723  DeclSpec DS(AttrFactory);
5724 
5725  // GNU attributes are not allowed here in a new-type-id, but Declspec and
5726  // C++11 attributes are allowed.
5727  unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
5729  ? AR_GNUAttributesParsed
5730  : AR_GNUAttributesParsedAndRejected);
5731  ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
5732  D.ExtendWithDeclSpec(DS);
5733 
5734  // Recursively parse the declarator.
5735  ParseDeclaratorInternal(D, DirectDeclParser);
5736  if (Kind == tok::star)
5737  // Remember that we parsed a pointer type, and remember the type-quals.
5739  DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5742  std::move(DS.getAttributes()), SourceLocation());
5743  else
5744  // Remember that we parsed a Block type, and remember the type-quals.
5745  D.AddTypeInfo(
5747  std::move(DS.getAttributes()), SourceLocation());
5748  } else {
5749  // Is a reference
5750  DeclSpec DS(AttrFactory);
5751 
5752  // Complain about rvalue references in C++03, but then go on and build
5753  // the declarator.
5754  if (Kind == tok::ampamp)
5755  Diag(Loc, getLangOpts().CPlusPlus11 ?
5756  diag::warn_cxx98_compat_rvalue_reference :
5757  diag::ext_rvalue_reference);
5758 
5759  // GNU-style and C++11 attributes are allowed here, as is restrict.
5760  ParseTypeQualifierListOpt(DS);
5761  D.ExtendWithDeclSpec(DS);
5762 
5763  // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5764  // cv-qualifiers are introduced through the use of a typedef or of a
5765  // template type argument, in which case the cv-qualifiers are ignored.
5768  Diag(DS.getConstSpecLoc(),
5769  diag::err_invalid_reference_qualifier_application) << "const";
5771  Diag(DS.getVolatileSpecLoc(),
5772  diag::err_invalid_reference_qualifier_application) << "volatile";
5773  // 'restrict' is permitted as an extension.
5775  Diag(DS.getAtomicSpecLoc(),
5776  diag::err_invalid_reference_qualifier_application) << "_Atomic";
5777  }
5778 
5779  // Recursively parse the declarator.
5780  ParseDeclaratorInternal(D, DirectDeclParser);
5781 
5782  if (D.getNumTypeObjects() > 0) {
5783  // C++ [dcl.ref]p4: There shall be no references to references.
5784  DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5785  if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5786  if (const IdentifierInfo *II = D.getIdentifier())
5787  Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5788  << II;
5789  else
5790  Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5791  << "type name";
5792 
5793  // Once we've complained about the reference-to-reference, we
5794  // can go ahead and build the (technically ill-formed)
5795  // declarator: reference collapsing will take care of it.
5796  }
5797  }
5798 
5799  // Remember that we parsed a reference type.
5801  Kind == tok::amp),
5802  std::move(DS.getAttributes()), SourceLocation());
5803  }
5804 }
5805 
5806 // When correcting from misplaced brackets before the identifier, the location
5807 // is saved inside the declarator so that other diagnostic messages can use
5808 // them. This extracts and returns that location, or returns the provided
5809 // location if a stored location does not exist.
5811  SourceLocation Loc) {
5812  if (D.getName().StartLocation.isInvalid() &&
5813  D.getName().EndLocation.isValid())
5814  return D.getName().EndLocation;
5815 
5816  return Loc;
5817 }
5818 
5819 /// ParseDirectDeclarator
5820 /// direct-declarator: [C99 6.7.5]
5821 /// [C99] identifier
5822 /// '(' declarator ')'
5823 /// [GNU] '(' attributes declarator ')'
5824 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5825 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5826 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5827 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5828 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5829 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5830 /// attribute-specifier-seq[opt]
5831 /// direct-declarator '(' parameter-type-list ')'
5832 /// direct-declarator '(' identifier-list[opt] ')'
5833 /// [GNU] direct-declarator '(' parameter-forward-declarations
5834 /// parameter-type-list[opt] ')'
5835 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
5836 /// cv-qualifier-seq[opt] exception-specification[opt]
5837 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5838 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5839 /// ref-qualifier[opt] exception-specification[opt]
5840 /// [C++] declarator-id
5841 /// [C++11] declarator-id attribute-specifier-seq[opt]
5842 ///
5843 /// declarator-id: [C++ 8]
5844 /// '...'[opt] id-expression
5845 /// '::'[opt] nested-name-specifier[opt] type-name
5846 ///
5847 /// id-expression: [C++ 5.1]
5848 /// unqualified-id
5849 /// qualified-id
5850 ///
5851 /// unqualified-id: [C++ 5.1]
5852 /// identifier
5853 /// operator-function-id
5854 /// conversion-function-id
5855 /// '~' class-name
5856 /// template-id
5857 ///
5858 /// C++17 adds the following, which we also handle here:
5859 ///
5860 /// simple-declaration:
5861 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5862 ///
5863 /// Note, any additional constructs added here may need corresponding changes
5864 /// in isConstructorDeclarator.
5865 void Parser::ParseDirectDeclarator(Declarator &D) {
5866  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
5867 
5868  if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
5869  // This might be a C++17 structured binding.
5870  if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5871  D.getCXXScopeSpec().isEmpty())
5872  return ParseDecompositionDeclarator(D);
5873 
5874  // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5875  // this context it is a bitfield. Also in range-based for statement colon
5876  // may delimit for-range-declaration.
5878  *this, D.getContext() == DeclaratorContext::Member ||
5880  getLangOpts().CPlusPlus11));
5881 
5882  // ParseDeclaratorInternal might already have parsed the scope.
5883  if (D.getCXXScopeSpec().isEmpty()) {
5884  bool EnteringContext = D.getContext() == DeclaratorContext::File ||
5886  ParseOptionalCXXScopeSpecifier(
5887  D.getCXXScopeSpec(), /*ObjectType=*/nullptr,
5888  /*ObjectHadErrors=*/false, EnteringContext);
5889  }
5890 
5891  if (D.getCXXScopeSpec().isValid()) {
5893  D.getCXXScopeSpec()))
5894  // Change the declaration context for name lookup, until this function
5895  // is exited (and the declarator has been parsed).
5896  DeclScopeObj.EnterDeclaratorScope();
5897  else if (getObjCDeclContext()) {