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