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