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