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