]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Parse/ParseDecl.cpp
Upgrade our copies of clang, llvm, lldb and compiler-rt to r312293 from
[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 /// \brief Normalizes an attribute name by dropping prefixed and suffixed __.
75 static StringRef normalizeAttrName(StringRef Name) {
76   if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
77     return Name.drop_front(2).drop_back(2);
78   return Name;
79 }
80
81 /// isAttributeLateParsed - Return true if the attribute has arguments that
82 /// require late parsing.
83 static bool isAttributeLateParsed(const IdentifierInfo &II) {
84 #define CLANG_ATTR_LATE_PARSED_LIST
85     return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
86 #include "clang/Parse/AttrParserStringSwitches.inc"
87         .Default(false);
88 #undef CLANG_ATTR_LATE_PARSED_LIST
89 }
90
91 /// ParseGNUAttributes - Parse a non-empty attributes list.
92 ///
93 /// [GNU] attributes:
94 ///         attribute
95 ///         attributes attribute
96 ///
97 /// [GNU]  attribute:
98 ///          '__attribute__' '(' '(' attribute-list ')' ')'
99 ///
100 /// [GNU]  attribute-list:
101 ///          attrib
102 ///          attribute_list ',' attrib
103 ///
104 /// [GNU]  attrib:
105 ///          empty
106 ///          attrib-name
107 ///          attrib-name '(' identifier ')'
108 ///          attrib-name '(' identifier ',' nonempty-expr-list ')'
109 ///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
110 ///
111 /// [GNU]  attrib-name:
112 ///          identifier
113 ///          typespec
114 ///          typequal
115 ///          storageclass
116 ///
117 /// Whether an attribute takes an 'identifier' is determined by the
118 /// attrib-name. GCC's behavior here is not worth imitating:
119 ///
120 ///  * In C mode, if the attribute argument list starts with an identifier
121 ///    followed by a ',' or an ')', and the identifier doesn't resolve to
122 ///    a type, it is parsed as an identifier. If the attribute actually
123 ///    wanted an expression, it's out of luck (but it turns out that no
124 ///    attributes work that way, because C constant expressions are very
125 ///    limited).
126 ///  * In C++ mode, if the attribute argument list starts with an identifier,
127 ///    and the attribute *wants* an identifier, it is parsed as an identifier.
128 ///    At block scope, any additional tokens between the identifier and the
129 ///    ',' or ')' are ignored, otherwise they produce a parse error.
130 ///
131 /// We follow the C++ model, but don't allow junk after the identifier.
132 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
133                                 SourceLocation *endLoc,
134                                 LateParsedAttrList *LateAttrs,
135                                 Declarator *D) {
136   assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
137
138   while (Tok.is(tok::kw___attribute)) {
139     ConsumeToken();
140     if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
141                          "attribute")) {
142       SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
143       return;
144     }
145     if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
146       SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
147       return;
148     }
149     // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
150     while (true) {
151       // Allow empty/non-empty attributes. ((__vector_size__(16),,,,))
152       if (TryConsumeToken(tok::comma))
153         continue;
154
155       // Expect an identifier or declaration specifier (const, int, etc.)
156       if (Tok.isAnnotation())
157         break;
158       IdentifierInfo *AttrName = Tok.getIdentifierInfo();
159       if (!AttrName)
160         break;
161
162       SourceLocation AttrNameLoc = ConsumeToken();
163
164       if (Tok.isNot(tok::l_paren)) {
165         attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
166                      AttributeList::AS_GNU);
167         continue;
168       }
169
170       // Handle "parameterized" attributes
171       if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
172         ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
173                               SourceLocation(), AttributeList::AS_GNU, D);
174         continue;
175       }
176
177       // Handle attributes with arguments that require late parsing.
178       LateParsedAttribute *LA =
179           new LateParsedAttribute(this, *AttrName, AttrNameLoc);
180       LateAttrs->push_back(LA);
181
182       // Attributes in a class are parsed at the end of the class, along
183       // with other late-parsed declarations.
184       if (!ClassStack.empty() && !LateAttrs->parseSoon())
185         getCurrentClass().LateParsedDeclarations.push_back(LA);
186
187       // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
188       // recursively consumes balanced parens.
189       LA->Toks.push_back(Tok);
190       ConsumeParen();
191       // Consume everything up to and including the matching right parens.
192       ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
193
194       Token Eof;
195       Eof.startToken();
196       Eof.setLocation(Tok.getLocation());
197       LA->Toks.push_back(Eof);
198     }
199
200     if (ExpectAndConsume(tok::r_paren))
201       SkipUntil(tok::r_paren, StopAtSemi);
202     SourceLocation Loc = Tok.getLocation();
203     if (ExpectAndConsume(tok::r_paren))
204       SkipUntil(tok::r_paren, StopAtSemi);
205     if (endLoc)
206       *endLoc = Loc;
207   }
208 }
209
210 /// \brief Determine whether the given attribute has an identifier argument.
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       LLVM_FALLTHROUGH;
2556     }
2557     case tok::comma:
2558     case tok::equal:
2559     case tok::kw_asm:
2560     case tok::l_brace:
2561     case tok::l_square:
2562     case tok::semi:
2563       // This looks like a variable or function declaration. The type is
2564       // probably missing. We're done parsing decl-specifiers.
2565       if (SS)
2566         AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2567       return false;
2568
2569     default:
2570       // This is probably supposed to be a type. This includes cases like:
2571       //   int f(itn);
2572       //   struct S { unsinged : 4; };
2573       break;
2574     }
2575   }
2576
2577   // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2578   // and attempt to recover.
2579   ParsedType T;
2580   IdentifierInfo *II = Tok.getIdentifierInfo();
2581   bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2582   Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2583                                   IsTemplateName);
2584   if (T) {
2585     // The action has suggested that the type T could be used. Set that as
2586     // the type in the declaration specifiers, consume the would-be type
2587     // name token, and we're done.
2588     const char *PrevSpec;
2589     unsigned DiagID;
2590     DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2591                        Actions.getASTContext().getPrintingPolicy());
2592     DS.SetRangeEnd(Tok.getLocation());
2593     ConsumeToken();
2594     // There may be other declaration specifiers after this.
2595     return true;
2596   } else if (II != Tok.getIdentifierInfo()) {
2597     // If no type was suggested, the correction is to a keyword
2598     Tok.setKind(II->getTokenID());
2599     // There may be other declaration specifiers after this.
2600     return true;
2601   }
2602
2603   // Otherwise, the action had no suggestion for us.  Mark this as an error.
2604   DS.SetTypeSpecError();
2605   DS.SetRangeEnd(Tok.getLocation());
2606   ConsumeToken();
2607
2608   // Eat any following template arguments.
2609   if (IsTemplateName) {
2610     SourceLocation LAngle, RAngle;
2611     TemplateArgList Args;
2612     ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2613   }
2614
2615   // TODO: Could inject an invalid typedef decl in an enclosing scope to
2616   // avoid rippling error messages on subsequent uses of the same type,
2617   // could be useful if #include was forgotten.
2618   return false;
2619 }
2620
2621 /// \brief Determine the declaration specifier context from the declarator
2622 /// context.
2623 ///
2624 /// \param Context the declarator context, which is one of the
2625 /// Declarator::TheContext enumerator values.
2626 Parser::DeclSpecContext
2627 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
2628   if (Context == Declarator::MemberContext)
2629     return DSC_class;
2630   if (Context == Declarator::FileContext)
2631     return DSC_top_level;
2632   if (Context == Declarator::TemplateParamContext)
2633     return DSC_template_param;
2634   if (Context == Declarator::TemplateTypeArgContext)
2635     return DSC_template_type_arg;
2636   if (Context == Declarator::TrailingReturnContext)
2637     return DSC_trailing;
2638   if (Context == Declarator::AliasDeclContext ||
2639       Context == Declarator::AliasTemplateContext)
2640     return DSC_alias_declaration;
2641   return DSC_normal;
2642 }
2643
2644 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2645 ///
2646 /// FIXME: Simply returns an alignof() expression if the argument is a
2647 /// type. Ideally, the type should be propagated directly into Sema.
2648 ///
2649 /// [C11]   type-id
2650 /// [C11]   constant-expression
2651 /// [C++0x] type-id ...[opt]
2652 /// [C++0x] assignment-expression ...[opt]
2653 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2654                                       SourceLocation &EllipsisLoc) {
2655   ExprResult ER;
2656   if (isTypeIdInParens()) {
2657     SourceLocation TypeLoc = Tok.getLocation();
2658     ParsedType Ty = ParseTypeName().get();
2659     SourceRange TypeRange(Start, Tok.getLocation());
2660     ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2661                                                Ty.getAsOpaquePtr(), TypeRange);
2662   } else
2663     ER = ParseConstantExpression();
2664
2665   if (getLangOpts().CPlusPlus11)
2666     TryConsumeToken(tok::ellipsis, EllipsisLoc);
2667
2668   return ER;
2669 }
2670
2671 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2672 /// attribute to Attrs.
2673 ///
2674 /// alignment-specifier:
2675 /// [C11]   '_Alignas' '(' type-id ')'
2676 /// [C11]   '_Alignas' '(' constant-expression ')'
2677 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2678 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2679 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2680                                      SourceLocation *EndLoc) {
2681   assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2682          "Not an alignment-specifier!");
2683
2684   IdentifierInfo *KWName = Tok.getIdentifierInfo();
2685   SourceLocation KWLoc = ConsumeToken();
2686
2687   BalancedDelimiterTracker T(*this, tok::l_paren);
2688   if (T.expectAndConsume())
2689     return;
2690
2691   SourceLocation EllipsisLoc;
2692   ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2693   if (ArgExpr.isInvalid()) {
2694     T.skipToEnd();
2695     return;
2696   }
2697
2698   T.consumeClose();
2699   if (EndLoc)
2700     *EndLoc = T.getCloseLocation();
2701
2702   ArgsVector ArgExprs;
2703   ArgExprs.push_back(ArgExpr.get());
2704   Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2705                AttributeList::AS_Keyword, EllipsisLoc);
2706 }
2707
2708 /// Determine whether we're looking at something that might be a declarator
2709 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2710 /// diagnose a missing semicolon after a prior tag definition in the decl
2711 /// specifier.
2712 ///
2713 /// \return \c true if an error occurred and this can't be any kind of
2714 /// declaration.
2715 bool
2716 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2717                                               DeclSpecContext DSContext,
2718                                               LateParsedAttrList *LateAttrs) {
2719   assert(DS.hasTagDefinition() && "shouldn't call this");
2720
2721   bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2722
2723   if (getLangOpts().CPlusPlus &&
2724       Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2725                   tok::annot_template_id) &&
2726       TryAnnotateCXXScopeToken(EnteringContext)) {
2727     SkipMalformedDecl();
2728     return true;
2729   }
2730
2731   bool HasScope = Tok.is(tok::annot_cxxscope);
2732   // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2733   Token AfterScope = HasScope ? NextToken() : Tok;
2734
2735   // Determine whether the following tokens could possibly be a
2736   // declarator.
2737   bool MightBeDeclarator = true;
2738   if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2739     // A declarator-id can't start with 'typename'.
2740     MightBeDeclarator = false;
2741   } else if (AfterScope.is(tok::annot_template_id)) {
2742     // If we have a type expressed as a template-id, this cannot be a
2743     // declarator-id (such a type cannot be redeclared in a simple-declaration).
2744     TemplateIdAnnotation *Annot =
2745         static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2746     if (Annot->Kind == TNK_Type_template)
2747       MightBeDeclarator = false;
2748   } else if (AfterScope.is(tok::identifier)) {
2749     const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2750
2751     // These tokens cannot come after the declarator-id in a
2752     // simple-declaration, and are likely to come after a type-specifier.
2753     if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2754                      tok::annot_cxxscope, tok::coloncolon)) {
2755       // Missing a semicolon.
2756       MightBeDeclarator = false;
2757     } else if (HasScope) {
2758       // If the declarator-id has a scope specifier, it must redeclare a
2759       // previously-declared entity. If that's a type (and this is not a
2760       // typedef), that's an error.
2761       CXXScopeSpec SS;
2762       Actions.RestoreNestedNameSpecifierAnnotation(
2763           Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2764       IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2765       Sema::NameClassification Classification = Actions.ClassifyName(
2766           getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2767           /*IsAddressOfOperand*/false);
2768       switch (Classification.getKind()) {
2769       case Sema::NC_Error:
2770         SkipMalformedDecl();
2771         return true;
2772
2773       case Sema::NC_Keyword:
2774       case Sema::NC_NestedNameSpecifier:
2775         llvm_unreachable("typo correction and nested name specifiers not "
2776                          "possible here");
2777
2778       case Sema::NC_Type:
2779       case Sema::NC_TypeTemplate:
2780         // Not a previously-declared non-type entity.
2781         MightBeDeclarator = false;
2782         break;
2783
2784       case Sema::NC_Unknown:
2785       case Sema::NC_Expression:
2786       case Sema::NC_VarTemplate:
2787       case Sema::NC_FunctionTemplate:
2788         // Might be a redeclaration of a prior entity.
2789         break;
2790       }
2791     }
2792   }
2793
2794   if (MightBeDeclarator)
2795     return false;
2796
2797   const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2798   Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()),
2799        diag::err_expected_after)
2800       << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2801
2802   // Try to recover from the typo, by dropping the tag definition and parsing
2803   // the problematic tokens as a type.
2804   //
2805   // FIXME: Split the DeclSpec into pieces for the standalone
2806   // declaration and pieces for the following declaration, instead
2807   // of assuming that all the other pieces attach to new declaration,
2808   // and call ParsedFreeStandingDeclSpec as appropriate.
2809   DS.ClearTypeSpecType();
2810   ParsedTemplateInfo NotATemplate;
2811   ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2812   return false;
2813 }
2814
2815 /// ParseDeclarationSpecifiers
2816 ///       declaration-specifiers: [C99 6.7]
2817 ///         storage-class-specifier declaration-specifiers[opt]
2818 ///         type-specifier declaration-specifiers[opt]
2819 /// [C99]   function-specifier declaration-specifiers[opt]
2820 /// [C11]   alignment-specifier declaration-specifiers[opt]
2821 /// [GNU]   attributes declaration-specifiers[opt]
2822 /// [Clang] '__module_private__' declaration-specifiers[opt]
2823 /// [ObjC1] '__kindof' declaration-specifiers[opt]
2824 ///
2825 ///       storage-class-specifier: [C99 6.7.1]
2826 ///         'typedef'
2827 ///         'extern'
2828 ///         'static'
2829 ///         'auto'
2830 ///         'register'
2831 /// [C++]   'mutable'
2832 /// [C++11] 'thread_local'
2833 /// [C11]   '_Thread_local'
2834 /// [GNU]   '__thread'
2835 ///       function-specifier: [C99 6.7.4]
2836 /// [C99]   'inline'
2837 /// [C++]   'virtual'
2838 /// [C++]   'explicit'
2839 /// [OpenCL] '__kernel'
2840 ///       'friend': [C++ dcl.friend]
2841 ///       'constexpr': [C++0x dcl.constexpr]
2842 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2843                                         const ParsedTemplateInfo &TemplateInfo,
2844                                         AccessSpecifier AS,
2845                                         DeclSpecContext DSContext,
2846                                         LateParsedAttrList *LateAttrs) {
2847   if (DS.getSourceRange().isInvalid()) {
2848     // Start the range at the current token but make the end of the range
2849     // invalid.  This will make the entire range invalid unless we successfully
2850     // consume a token.
2851     DS.SetRangeStart(Tok.getLocation());
2852     DS.SetRangeEnd(SourceLocation());
2853   }
2854
2855   bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2856   bool AttrsLastTime = false;
2857   ParsedAttributesWithRange attrs(AttrFactory);
2858   // We use Sema's policy to get bool macros right.
2859   PrintingPolicy Policy = Actions.getPrintingPolicy();
2860   while (1) {
2861     bool isInvalid = false;
2862     bool isStorageClass = false;
2863     const char *PrevSpec = nullptr;
2864     unsigned DiagID = 0;
2865
2866     // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2867     // implementation for VS2013 uses _Atomic as an identifier for one of the
2868     // classes in <atomic>.
2869     //
2870     // A typedef declaration containing _Atomic<...> is among the places where
2871     // the class is used.  If we are currently parsing such a declaration, treat
2872     // the token as an identifier.
2873     if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2874         DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
2875         !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
2876       Tok.setKind(tok::identifier);
2877
2878     SourceLocation Loc = Tok.getLocation();
2879
2880     switch (Tok.getKind()) {
2881     default:
2882     DoneWithDeclSpec:
2883       if (!AttrsLastTime)
2884         ProhibitAttributes(attrs);
2885       else {
2886         // Reject C++11 attributes that appertain to decl specifiers as
2887         // we don't support any C++11 attributes that appertain to decl
2888         // specifiers. This also conforms to what g++ 4.8 is doing.
2889         ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
2890
2891         DS.takeAttributesFrom(attrs);
2892       }
2893
2894       // If this is not a declaration specifier token, we're done reading decl
2895       // specifiers.  First verify that DeclSpec's are consistent.
2896       DS.Finish(Actions, Policy);
2897       return;
2898
2899     case tok::l_square:
2900     case tok::kw_alignas:
2901       if (!getLangOpts().CPlusPlus11 || !isCXX11AttributeSpecifier())
2902         goto DoneWithDeclSpec;
2903
2904       ProhibitAttributes(attrs);
2905       // FIXME: It would be good to recover by accepting the attributes,
2906       //        but attempting to do that now would cause serious
2907       //        madness in terms of diagnostics.
2908       attrs.clear();
2909       attrs.Range = SourceRange();
2910
2911       ParseCXX11Attributes(attrs);
2912       AttrsLastTime = true;
2913       continue;
2914
2915     case tok::code_completion: {
2916       Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2917       if (DS.hasTypeSpecifier()) {
2918         bool AllowNonIdentifiers
2919           = (getCurScope()->getFlags() & (Scope::ControlScope |
2920                                           Scope::BlockScope |
2921                                           Scope::TemplateParamScope |
2922                                           Scope::FunctionPrototypeScope |
2923                                           Scope::AtCatchScope)) == 0;
2924         bool AllowNestedNameSpecifiers
2925           = DSContext == DSC_top_level ||
2926             (DSContext == DSC_class && DS.isFriendSpecified());
2927
2928         Actions.CodeCompleteDeclSpec(getCurScope(), DS,
2929                                      AllowNonIdentifiers,
2930                                      AllowNestedNameSpecifiers);
2931         return cutOffParsing();
2932       }
2933
2934       if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
2935         CCC = Sema::PCC_LocalDeclarationSpecifiers;
2936       else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
2937         CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
2938                                     : Sema::PCC_Template;
2939       else if (DSContext == DSC_class)
2940         CCC = Sema::PCC_Class;
2941       else if (CurParsedObjCImpl)
2942         CCC = Sema::PCC_ObjCImplementation;
2943
2944       Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
2945       return cutOffParsing();
2946     }
2947
2948     case tok::coloncolon: // ::foo::bar
2949       // C++ scope specifier.  Annotate and loop, or bail out on error.
2950       if (TryAnnotateCXXScopeToken(EnteringContext)) {
2951         if (!DS.hasTypeSpecifier())
2952           DS.SetTypeSpecError();
2953         goto DoneWithDeclSpec;
2954       }
2955       if (Tok.is(tok::coloncolon)) // ::new or ::delete
2956         goto DoneWithDeclSpec;
2957       continue;
2958
2959     case tok::annot_cxxscope: {
2960       if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
2961         goto DoneWithDeclSpec;
2962
2963       CXXScopeSpec SS;
2964       Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2965                                                    Tok.getAnnotationRange(),
2966                                                    SS);
2967
2968       // We are looking for a qualified typename.
2969       Token Next = NextToken();
2970       if (Next.is(tok::annot_template_id) &&
2971           static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
2972             ->Kind == TNK_Type_template) {
2973         // We have a qualified template-id, e.g., N::A<int>
2974
2975         // If this would be a valid constructor declaration with template
2976         // arguments, we will reject the attempt to form an invalid type-id
2977         // referring to the injected-class-name when we annotate the token,
2978         // per C++ [class.qual]p2.
2979         //
2980         // To improve diagnostics for this case, parse the declaration as a
2981         // constructor (and reject the extra template arguments later).
2982         TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
2983         if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2984             TemplateId->Name &&
2985             Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
2986             isConstructorDeclarator(/*Unqualified*/false)) {
2987           // The user meant this to be an out-of-line constructor
2988           // definition, but template arguments are not allowed
2989           // there.  Just allow this as a constructor; we'll
2990           // complain about it later.
2991           goto DoneWithDeclSpec;
2992         }
2993
2994         DS.getTypeSpecScope() = SS;
2995         ConsumeAnnotationToken(); // The C++ scope.
2996         assert(Tok.is(tok::annot_template_id) &&
2997                "ParseOptionalCXXScopeSpecifier not working");
2998         AnnotateTemplateIdTokenAsType();
2999         continue;
3000       }
3001
3002       if (Next.is(tok::annot_typename)) {
3003         DS.getTypeSpecScope() = SS;
3004         ConsumeAnnotationToken(); // The C++ scope.
3005         if (Tok.getAnnotationValue()) {
3006           ParsedType T = getTypeAnnotation(Tok);
3007           isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3008                                          Tok.getAnnotationEndLoc(),
3009                                          PrevSpec, DiagID, T, Policy);
3010           if (isInvalid)
3011             break;
3012         }
3013         else
3014           DS.SetTypeSpecError();
3015         DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3016         ConsumeAnnotationToken(); // The typename
3017       }
3018
3019       if (Next.isNot(tok::identifier))
3020         goto DoneWithDeclSpec;
3021
3022       // Check whether this is a constructor declaration. If we're in a
3023       // context where the identifier could be a class name, and it has the
3024       // shape of a constructor declaration, process it as one.
3025       if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
3026           Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3027                                      &SS) &&
3028           isConstructorDeclarator(/*Unqualified*/ false))
3029         goto DoneWithDeclSpec;
3030
3031       ParsedType TypeRep =
3032           Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3033                               getCurScope(), &SS, false, false, nullptr,
3034                               /*IsCtorOrDtorName=*/false,
3035                               /*WantNonTrivialSourceInfo=*/true,
3036                               isClassTemplateDeductionContext(DSContext));
3037
3038       // If the referenced identifier is not a type, then this declspec is
3039       // erroneous: We already checked about that it has no type specifier, and
3040       // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
3041       // typename.
3042       if (!TypeRep) {
3043         // Eat the scope spec so the identifier is current.
3044         ConsumeAnnotationToken();
3045         ParsedAttributesWithRange Attrs(AttrFactory);
3046         if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3047           if (!Attrs.empty()) {
3048             AttrsLastTime = true;
3049             attrs.takeAllFrom(Attrs);
3050           }
3051           continue;
3052         }
3053         goto DoneWithDeclSpec;
3054       }
3055
3056       DS.getTypeSpecScope() = SS;
3057       ConsumeAnnotationToken(); // The C++ scope.
3058
3059       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3060                                      DiagID, TypeRep, Policy);
3061       if (isInvalid)
3062         break;
3063
3064       DS.SetRangeEnd(Tok.getLocation());
3065       ConsumeToken(); // The typename.
3066
3067       continue;
3068     }
3069
3070     case tok::annot_typename: {
3071       // If we've previously seen a tag definition, we were almost surely
3072       // missing a semicolon after it.
3073       if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3074         goto DoneWithDeclSpec;
3075
3076       if (Tok.getAnnotationValue()) {
3077         ParsedType T = getTypeAnnotation(Tok);
3078         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3079                                        DiagID, T, Policy);
3080       } else
3081         DS.SetTypeSpecError();
3082
3083       if (isInvalid)
3084         break;
3085
3086       DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3087       ConsumeAnnotationToken(); // The typename
3088
3089       continue;
3090     }
3091
3092     case tok::kw___is_signed:
3093       // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3094       // typically treats it as a trait. If we see __is_signed as it appears
3095       // in libstdc++, e.g.,
3096       //
3097       //   static const bool __is_signed;
3098       //
3099       // then treat __is_signed as an identifier rather than as a keyword.
3100       if (DS.getTypeSpecType() == TST_bool &&
3101           DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3102           DS.getStorageClassSpec() == DeclSpec::SCS_static)
3103         TryKeywordIdentFallback(true);
3104
3105       // We're done with the declaration-specifiers.
3106       goto DoneWithDeclSpec;
3107
3108       // typedef-name
3109     case tok::kw___super:
3110     case tok::kw_decltype:
3111     case tok::identifier: {
3112       // This identifier can only be a typedef name if we haven't already seen
3113       // a type-specifier.  Without this check we misparse:
3114       //  typedef int X; struct Y { short X; };  as 'short int'.
3115       if (DS.hasTypeSpecifier())
3116         goto DoneWithDeclSpec;
3117
3118       // If the token is an identifier named "__declspec" and Microsoft
3119       // extensions are not enabled, it is likely that there will be cascading
3120       // parse errors if this really is a __declspec attribute. Attempt to
3121       // recognize that scenario and recover gracefully.
3122       if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3123           Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3124         Diag(Loc, diag::err_ms_attributes_not_enabled);
3125
3126         // The next token should be an open paren. If it is, eat the entire
3127         // attribute declaration and continue.
3128         if (NextToken().is(tok::l_paren)) {
3129           // Consume the __declspec identifier.
3130           ConsumeToken();
3131
3132           // Eat the parens and everything between them.
3133           BalancedDelimiterTracker T(*this, tok::l_paren);
3134           if (T.consumeOpen()) {
3135             assert(false && "Not a left paren?");
3136             return;
3137           }
3138           T.skipToEnd();
3139           continue;
3140         }
3141       }
3142
3143       // In C++, check to see if this is a scope specifier like foo::bar::, if
3144       // so handle it as such.  This is important for ctor parsing.
3145       if (getLangOpts().CPlusPlus) {
3146         if (TryAnnotateCXXScopeToken(EnteringContext)) {
3147           DS.SetTypeSpecError();
3148           goto DoneWithDeclSpec;
3149         }
3150         if (!Tok.is(tok::identifier))
3151           continue;
3152       }
3153
3154       // Check for need to substitute AltiVec keyword tokens.
3155       if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3156         break;
3157
3158       // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3159       //                allow the use of a typedef name as a type specifier.
3160       if (DS.isTypeAltiVecVector())
3161         goto DoneWithDeclSpec;
3162
3163       if (DSContext == DSC_objc_method_result && isObjCInstancetype()) {
3164         ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3165         assert(TypeRep);
3166         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3167                                        DiagID, TypeRep, Policy);
3168         if (isInvalid)
3169           break;
3170
3171         DS.SetRangeEnd(Loc);
3172         ConsumeToken();
3173         continue;
3174       }
3175
3176       ParsedType TypeRep = Actions.getTypeName(
3177           *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3178           false, false, nullptr, false, false,
3179           isClassTemplateDeductionContext(DSContext));
3180
3181       // If this is not a typedef name, don't parse it as part of the declspec,
3182       // it must be an implicit int or an error.
3183       if (!TypeRep) {
3184         ParsedAttributesWithRange Attrs(AttrFactory);
3185         if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3186           if (!Attrs.empty()) {
3187             AttrsLastTime = true;
3188             attrs.takeAllFrom(Attrs);
3189           }
3190           continue;
3191         }
3192         goto DoneWithDeclSpec;
3193       }
3194
3195       // If we're in a context where the identifier could be a class name,
3196       // check whether this is a constructor declaration.
3197       if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
3198           Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3199           isConstructorDeclarator(/*Unqualified*/true))
3200         goto DoneWithDeclSpec;
3201
3202       // Likewise, if this is a context where the identifier could be a template
3203       // name, check whether this is a deduction guide declaration.
3204       if (getLangOpts().CPlusPlus1z &&
3205           (DSContext == DSC_class || DSContext == DSC_top_level) &&
3206           Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3207                                        Tok.getLocation()) &&
3208           isConstructorDeclarator(/*Unqualified*/ true,
3209                                   /*DeductionGuide*/ true))
3210         goto DoneWithDeclSpec;
3211
3212       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3213                                      DiagID, TypeRep, Policy);
3214       if (isInvalid)
3215         break;
3216
3217       DS.SetRangeEnd(Tok.getLocation());
3218       ConsumeToken(); // The identifier
3219
3220       // Objective-C supports type arguments and protocol references
3221       // following an Objective-C object or object pointer
3222       // type. Handle either one of them.
3223       if (Tok.is(tok::less) && getLangOpts().ObjC1) {
3224         SourceLocation NewEndLoc;
3225         TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3226                                   Loc, TypeRep, /*consumeLastToken=*/true,
3227                                   NewEndLoc);
3228         if (NewTypeRep.isUsable()) {
3229           DS.UpdateTypeRep(NewTypeRep.get());
3230           DS.SetRangeEnd(NewEndLoc);
3231         }
3232       }
3233
3234       // Need to support trailing type qualifiers (e.g. "id<p> const").
3235       // If a type specifier follows, it will be diagnosed elsewhere.
3236       continue;
3237     }
3238
3239       // type-name
3240     case tok::annot_template_id: {
3241       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3242       if (TemplateId->Kind != TNK_Type_template) {
3243         // This template-id does not refer to a type name, so we're
3244         // done with the type-specifiers.
3245         goto DoneWithDeclSpec;
3246       }
3247
3248       // If we're in a context where the template-id could be a
3249       // constructor name or specialization, check whether this is a
3250       // constructor declaration.
3251       if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
3252           Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3253           isConstructorDeclarator(TemplateId->SS.isEmpty()))
3254         goto DoneWithDeclSpec;
3255
3256       // Turn the template-id annotation token into a type annotation
3257       // token, then try again to parse it as a type-specifier.
3258       AnnotateTemplateIdTokenAsType();
3259       continue;
3260     }
3261
3262     // GNU attributes support.
3263     case tok::kw___attribute:
3264       ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3265       continue;
3266
3267     // Microsoft declspec support.
3268     case tok::kw___declspec:
3269       ParseMicrosoftDeclSpecs(DS.getAttributes());
3270       continue;
3271
3272     // Microsoft single token adornments.
3273     case tok::kw___forceinline: {
3274       isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3275       IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3276       SourceLocation AttrNameLoc = Tok.getLocation();
3277       DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3278                                 nullptr, 0, AttributeList::AS_Keyword);
3279       break;
3280     }
3281
3282     case tok::kw___unaligned:
3283       isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3284                                  getLangOpts());
3285       break;
3286
3287     case tok::kw___sptr:
3288     case tok::kw___uptr:
3289     case tok::kw___ptr64:
3290     case tok::kw___ptr32:
3291     case tok::kw___w64:
3292     case tok::kw___cdecl:
3293     case tok::kw___stdcall:
3294     case tok::kw___fastcall:
3295     case tok::kw___thiscall:
3296     case tok::kw___regcall:
3297     case tok::kw___vectorcall:
3298       ParseMicrosoftTypeAttributes(DS.getAttributes());
3299       continue;
3300
3301     // Borland single token adornments.
3302     case tok::kw___pascal:
3303       ParseBorlandTypeAttributes(DS.getAttributes());
3304       continue;
3305
3306     // OpenCL single token adornments.
3307     case tok::kw___kernel:
3308       ParseOpenCLKernelAttributes(DS.getAttributes());
3309       continue;
3310
3311     // Nullability type specifiers.
3312     case tok::kw__Nonnull:
3313     case tok::kw__Nullable:
3314     case tok::kw__Null_unspecified:
3315       ParseNullabilityTypeSpecifiers(DS.getAttributes());
3316       continue;
3317
3318     // Objective-C 'kindof' types.
3319     case tok::kw___kindof:
3320       DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3321                                 nullptr, 0, AttributeList::AS_Keyword);
3322       (void)ConsumeToken();
3323       continue;
3324
3325     // storage-class-specifier
3326     case tok::kw_typedef:
3327       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3328                                          PrevSpec, DiagID, Policy);
3329       isStorageClass = true;
3330       break;
3331     case tok::kw_extern:
3332       if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3333         Diag(Tok, diag::ext_thread_before) << "extern";
3334       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3335                                          PrevSpec, DiagID, Policy);
3336       isStorageClass = true;
3337       break;
3338     case tok::kw___private_extern__:
3339       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3340                                          Loc, PrevSpec, DiagID, Policy);
3341       isStorageClass = true;
3342       break;
3343     case tok::kw_static:
3344       if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3345         Diag(Tok, diag::ext_thread_before) << "static";
3346       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3347                                          PrevSpec, DiagID, Policy);
3348       isStorageClass = true;
3349       break;
3350     case tok::kw_auto:
3351       if (getLangOpts().CPlusPlus11) {
3352         if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3353           isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3354                                              PrevSpec, DiagID, Policy);
3355           if (!isInvalid)
3356             Diag(Tok, diag::ext_auto_storage_class)
3357               << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3358         } else
3359           isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3360                                          DiagID, Policy);
3361       } else
3362         isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3363                                            PrevSpec, DiagID, Policy);
3364       isStorageClass = true;
3365       break;
3366     case tok::kw___auto_type:
3367       Diag(Tok, diag::ext_auto_type);
3368       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3369                                      DiagID, Policy);
3370       break;
3371     case tok::kw_register:
3372       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3373                                          PrevSpec, DiagID, Policy);
3374       isStorageClass = true;
3375       break;
3376     case tok::kw_mutable:
3377       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3378                                          PrevSpec, DiagID, Policy);
3379       isStorageClass = true;
3380       break;
3381     case tok::kw___thread:
3382       isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3383                                                PrevSpec, DiagID);
3384       isStorageClass = true;
3385       break;
3386     case tok::kw_thread_local:
3387       isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3388                                                PrevSpec, DiagID);
3389       break;
3390     case tok::kw__Thread_local:
3391       isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3392                                                Loc, PrevSpec, DiagID);
3393       isStorageClass = true;
3394       break;
3395
3396     // function-specifier
3397     case tok::kw_inline:
3398       isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3399       break;
3400     case tok::kw_virtual:
3401       isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3402       break;
3403     case tok::kw_explicit:
3404       isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
3405       break;
3406     case tok::kw__Noreturn:
3407       if (!getLangOpts().C11)
3408         Diag(Loc, diag::ext_c11_noreturn);
3409       isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3410       break;
3411
3412     // alignment-specifier
3413     case tok::kw__Alignas:
3414       if (!getLangOpts().C11)
3415         Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
3416       ParseAlignmentSpecifier(DS.getAttributes());
3417       continue;
3418
3419     // friend
3420     case tok::kw_friend:
3421       if (DSContext == DSC_class)
3422         isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3423       else {
3424         PrevSpec = ""; // not actually used by the diagnostic
3425         DiagID = diag::err_friend_invalid_in_context;
3426         isInvalid = true;
3427       }
3428       break;
3429
3430     // Modules
3431     case tok::kw___module_private__:
3432       isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3433       break;
3434
3435     // constexpr
3436     case tok::kw_constexpr:
3437       isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3438       break;
3439
3440     // concept
3441     case tok::kw_concept:
3442       isInvalid = DS.SetConceptSpec(Loc, PrevSpec, DiagID);
3443       break;
3444
3445     // type-specifier
3446     case tok::kw_short:
3447       isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3448                                       DiagID, Policy);
3449       break;
3450     case tok::kw_long:
3451       if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
3452         isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3453                                         DiagID, Policy);
3454       else
3455         isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3456                                         DiagID, Policy);
3457       break;
3458     case tok::kw___int64:
3459         isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3460                                         DiagID, Policy);
3461       break;
3462     case tok::kw_signed:
3463       isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3464                                      DiagID);
3465       break;
3466     case tok::kw_unsigned:
3467       isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3468                                      DiagID);
3469       break;
3470     case tok::kw__Complex:
3471       isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3472                                         DiagID);
3473       break;
3474     case tok::kw__Imaginary:
3475       isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3476                                         DiagID);
3477       break;
3478     case tok::kw_void:
3479       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3480                                      DiagID, Policy);
3481       break;
3482     case tok::kw_char:
3483       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3484                                      DiagID, Policy);
3485       break;
3486     case tok::kw_int:
3487       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3488                                      DiagID, Policy);
3489       break;
3490     case tok::kw___int128:
3491       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3492                                      DiagID, Policy);
3493       break;
3494     case tok::kw_half:
3495       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3496                                      DiagID, Policy);
3497       break;
3498     case tok::kw_float:
3499       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3500                                      DiagID, Policy);
3501       break;
3502     case tok::kw_double:
3503       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3504                                      DiagID, Policy);
3505       break;
3506     case tok::kw___float128:
3507       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3508                                      DiagID, Policy);
3509       break;
3510     case tok::kw_wchar_t:
3511       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3512                                      DiagID, Policy);
3513       break;
3514     case tok::kw_char16_t:
3515       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3516                                      DiagID, Policy);
3517       break;
3518     case tok::kw_char32_t:
3519       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3520                                      DiagID, Policy);
3521       break;
3522     case tok::kw_bool:
3523     case tok::kw__Bool:
3524       if (Tok.is(tok::kw_bool) &&
3525           DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3526           DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3527         PrevSpec = ""; // Not used by the diagnostic.
3528         DiagID = diag::err_bool_redeclaration;
3529         // For better error recovery.
3530         Tok.setKind(tok::identifier);
3531         isInvalid = true;
3532       } else {
3533         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3534                                        DiagID, Policy);
3535       }
3536       break;
3537     case tok::kw__Decimal32:
3538       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3539                                      DiagID, Policy);
3540       break;
3541     case tok::kw__Decimal64:
3542       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3543                                      DiagID, Policy);
3544       break;
3545     case tok::kw__Decimal128:
3546       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3547                                      DiagID, Policy);
3548       break;
3549     case tok::kw___vector:
3550       isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3551       break;
3552     case tok::kw___pixel:
3553       isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3554       break;
3555     case tok::kw___bool:
3556       isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3557       break;
3558     case tok::kw_pipe:
3559       if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3560         // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3561         // support the "pipe" word as identifier.
3562         Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3563         goto DoneWithDeclSpec;
3564       }
3565       isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3566       break;
3567 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
3568   case tok::kw_##ImgType##_t: \
3569     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3570                                    DiagID, Policy); \
3571     break;
3572 #include "clang/Basic/OpenCLImageTypes.def"
3573     case tok::kw___unknown_anytype:
3574       isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3575                                      PrevSpec, DiagID, Policy);
3576       break;
3577
3578     // class-specifier:
3579     case tok::kw_class:
3580     case tok::kw_struct:
3581     case tok::kw___interface:
3582     case tok::kw_union: {
3583       tok::TokenKind Kind = Tok.getKind();
3584       ConsumeToken();
3585
3586       // These are attributes following class specifiers.
3587       // To produce better diagnostic, we parse them when
3588       // parsing class specifier.
3589       ParsedAttributesWithRange Attributes(AttrFactory);
3590       ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3591                           EnteringContext, DSContext, Attributes);
3592
3593       // If there are attributes following class specifier,
3594       // take them over and handle them here.
3595       if (!Attributes.empty()) {
3596         AttrsLastTime = true;
3597         attrs.takeAllFrom(Attributes);
3598       }
3599       continue;
3600     }
3601
3602     // enum-specifier:
3603     case tok::kw_enum:
3604       ConsumeToken();
3605       ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3606       continue;
3607
3608     // cv-qualifier:
3609     case tok::kw_const:
3610       isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3611                                  getLangOpts());
3612       break;
3613     case tok::kw_volatile:
3614       isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3615                                  getLangOpts());
3616       break;
3617     case tok::kw_restrict:
3618       isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3619                                  getLangOpts());
3620       break;
3621
3622     // C++ typename-specifier:
3623     case tok::kw_typename:
3624       if (TryAnnotateTypeOrScopeToken()) {
3625         DS.SetTypeSpecError();
3626         goto DoneWithDeclSpec;
3627       }
3628       if (!Tok.is(tok::kw_typename))
3629         continue;
3630       break;
3631
3632     // GNU typeof support.
3633     case tok::kw_typeof:
3634       ParseTypeofSpecifier(DS);
3635       continue;
3636
3637     case tok::annot_decltype:
3638       ParseDecltypeSpecifier(DS);
3639       continue;
3640
3641     case tok::annot_pragma_pack:
3642       HandlePragmaPack();
3643       continue;
3644
3645     case tok::annot_pragma_ms_pragma:
3646       HandlePragmaMSPragma();
3647       continue;
3648
3649     case tok::annot_pragma_ms_vtordisp:
3650       HandlePragmaMSVtorDisp();
3651       continue;
3652
3653     case tok::annot_pragma_ms_pointers_to_members:
3654       HandlePragmaMSPointersToMembers();
3655       continue;
3656
3657     case tok::kw___underlying_type:
3658       ParseUnderlyingTypeSpecifier(DS);
3659       continue;
3660
3661     case tok::kw__Atomic:
3662       // C11 6.7.2.4/4:
3663       //   If the _Atomic keyword is immediately followed by a left parenthesis,
3664       //   it is interpreted as a type specifier (with a type name), not as a
3665       //   type qualifier.
3666       if (NextToken().is(tok::l_paren)) {
3667         ParseAtomicSpecifier(DS);
3668         continue;
3669       }
3670       isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3671                                  getLangOpts());
3672       break;
3673
3674     // OpenCL qualifiers:
3675     case tok::kw___generic:
3676       // generic address space is introduced only in OpenCL v2.0
3677       // see OpenCL C Spec v2.0 s6.5.5
3678       if (Actions.getLangOpts().OpenCLVersion < 200) {
3679         DiagID = diag::err_opencl_unknown_type_specifier;
3680         PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3681         isInvalid = true;
3682         break;
3683       };
3684       LLVM_FALLTHROUGH;
3685     case tok::kw___private:
3686     case tok::kw___global:
3687     case tok::kw___local:
3688     case tok::kw___constant:
3689     case tok::kw___read_only:
3690     case tok::kw___write_only:
3691     case tok::kw___read_write:
3692       ParseOpenCLQualifiers(DS.getAttributes());
3693       break;
3694
3695     case tok::less:
3696       // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3697       // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
3698       // but we support it.
3699       if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
3700         goto DoneWithDeclSpec;
3701
3702       SourceLocation StartLoc = Tok.getLocation();
3703       SourceLocation EndLoc;
3704       TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3705       if (Type.isUsable()) {
3706         if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3707                                PrevSpec, DiagID, Type.get(),
3708                                Actions.getASTContext().getPrintingPolicy()))
3709           Diag(StartLoc, DiagID) << PrevSpec;
3710         
3711         DS.SetRangeEnd(EndLoc);
3712       } else {
3713         DS.SetTypeSpecError();
3714       }
3715
3716       // Need to support trailing type qualifiers (e.g. "id<p> const").
3717       // If a type specifier follows, it will be diagnosed elsewhere.
3718       continue;
3719     }
3720     // If the specifier wasn't legal, issue a diagnostic.
3721     if (isInvalid) {
3722       assert(PrevSpec && "Method did not return previous specifier!");
3723       assert(DiagID);
3724
3725       if (DiagID == diag::ext_duplicate_declspec)
3726         Diag(Tok, DiagID)
3727           << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
3728       else if (DiagID == diag::err_opencl_unknown_type_specifier) {
3729         const int OpenCLVer = getLangOpts().OpenCLVersion;
3730         std::string VerSpec = llvm::to_string(OpenCLVer / 100) +
3731                               std::string (".") +
3732                               llvm::to_string((OpenCLVer % 100) / 10);
3733         Diag(Tok, DiagID) << VerSpec << PrevSpec << isStorageClass;
3734       } else
3735         Diag(Tok, DiagID) << PrevSpec;
3736     }
3737
3738     DS.SetRangeEnd(Tok.getLocation());
3739     if (DiagID != diag::err_bool_redeclaration)
3740       ConsumeToken();
3741
3742     AttrsLastTime = false;
3743   }
3744 }
3745
3746 /// ParseStructDeclaration - Parse a struct declaration without the terminating
3747 /// semicolon.
3748 ///
3749 ///       struct-declaration:
3750 ///         specifier-qualifier-list struct-declarator-list
3751 /// [GNU]   __extension__ struct-declaration
3752 /// [GNU]   specifier-qualifier-list
3753 ///       struct-declarator-list:
3754 ///         struct-declarator
3755 ///         struct-declarator-list ',' struct-declarator
3756 /// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
3757 ///       struct-declarator:
3758 ///         declarator
3759 /// [GNU]   declarator attributes[opt]
3760 ///         declarator[opt] ':' constant-expression
3761 /// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
3762 ///
3763 void Parser::ParseStructDeclaration(
3764     ParsingDeclSpec &DS,
3765     llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
3766
3767   if (Tok.is(tok::kw___extension__)) {
3768     // __extension__ silences extension warnings in the subexpression.
3769     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
3770     ConsumeToken();
3771     return ParseStructDeclaration(DS, FieldsCallback);
3772   }
3773
3774   // Parse the common specifier-qualifiers-list piece.
3775   ParseSpecifierQualifierList(DS);
3776
3777   // If there are no declarators, this is a free-standing declaration
3778   // specifier. Let the actions module cope with it.
3779   if (Tok.is(tok::semi)) {
3780     RecordDecl *AnonRecord = nullptr;
3781     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
3782                                                        DS, AnonRecord);
3783     assert(!AnonRecord && "Did not expect anonymous struct or union here");
3784     DS.complete(TheDecl);
3785     return;
3786   }
3787
3788   // Read struct-declarators until we find the semicolon.
3789   bool FirstDeclarator = true;
3790   SourceLocation CommaLoc;
3791   while (1) {
3792     ParsingFieldDeclarator DeclaratorInfo(*this, DS);
3793     DeclaratorInfo.D.setCommaLoc(CommaLoc);
3794
3795     // Attributes are only allowed here on successive declarators.
3796     if (!FirstDeclarator)
3797       MaybeParseGNUAttributes(DeclaratorInfo.D);
3798
3799     /// struct-declarator: declarator
3800     /// struct-declarator: declarator[opt] ':' constant-expression
3801     if (Tok.isNot(tok::colon)) {
3802       // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3803       ColonProtectionRAIIObject X(*this);
3804       ParseDeclarator(DeclaratorInfo.D);
3805     } else
3806       DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
3807
3808     if (TryConsumeToken(tok::colon)) {
3809       ExprResult Res(ParseConstantExpression());
3810       if (Res.isInvalid())
3811         SkipUntil(tok::semi, StopBeforeMatch);
3812       else
3813         DeclaratorInfo.BitfieldSize = Res.get();
3814     }
3815
3816     // If attributes exist after the declarator, parse them.
3817     MaybeParseGNUAttributes(DeclaratorInfo.D);
3818
3819     // We're done with this declarator;  invoke the callback.
3820     FieldsCallback(DeclaratorInfo);
3821
3822     // If we don't have a comma, it is either the end of the list (a ';')
3823     // or an error, bail out.
3824     if (!TryConsumeToken(tok::comma, CommaLoc))
3825       return;
3826
3827     FirstDeclarator = false;
3828   }
3829 }
3830
3831 /// ParseStructUnionBody
3832 ///       struct-contents:
3833 ///         struct-declaration-list
3834 /// [EXT]   empty
3835 /// [GNU]   "struct-declaration-list" without terminatoring ';'
3836 ///       struct-declaration-list:
3837 ///         struct-declaration
3838 ///         struct-declaration-list struct-declaration
3839 /// [OBC]   '@' 'defs' '(' class-name ')'
3840 ///
3841 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
3842                                   unsigned TagType, Decl *TagDecl) {
3843   PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3844                                       "parsing struct/union body");
3845   assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
3846
3847   BalancedDelimiterTracker T(*this, tok::l_brace);
3848   if (T.consumeOpen())
3849     return;
3850
3851   ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
3852   Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3853
3854   SmallVector<Decl *, 32> FieldDecls;
3855
3856   // While we still have something to read, read the declarations in the struct.
3857   while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3858          Tok.isNot(tok::eof)) {
3859     // Each iteration of this loop reads one struct-declaration.
3860
3861     // Check for extraneous top-level semicolon.
3862     if (Tok.is(tok::semi)) {
3863       ConsumeExtraSemi(InsideStruct, TagType);
3864       continue;
3865     }
3866
3867     // Parse _Static_assert declaration.
3868     if (Tok.is(tok::kw__Static_assert)) {
3869       SourceLocation DeclEnd;
3870       ParseStaticAssertDeclaration(DeclEnd);
3871       continue;
3872     }
3873
3874     if (Tok.is(tok::annot_pragma_pack)) {
3875       HandlePragmaPack();
3876       continue;
3877     }
3878
3879     if (Tok.is(tok::annot_pragma_align)) {
3880       HandlePragmaAlign();
3881       continue;
3882     }
3883
3884     if (Tok.is(tok::annot_pragma_openmp)) {
3885       // Result can be ignored, because it must be always empty.
3886       AccessSpecifier AS = AS_none;
3887       ParsedAttributesWithRange Attrs(AttrFactory);
3888       (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
3889       continue;
3890     }
3891
3892     if (!Tok.is(tok::at)) {
3893       auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
3894         // Install the declarator into the current TagDecl.
3895         Decl *Field =
3896             Actions.ActOnField(getCurScope(), TagDecl,
3897                                FD.D.getDeclSpec().getSourceRange().getBegin(),
3898                                FD.D, FD.BitfieldSize);
3899         FieldDecls.push_back(Field);
3900         FD.complete(Field);
3901       };
3902
3903       // Parse all the comma separated declarators.
3904       ParsingDeclSpec DS(*this);
3905       ParseStructDeclaration(DS, CFieldCallback);
3906     } else { // Handle @defs
3907       ConsumeToken();
3908       if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
3909         Diag(Tok, diag::err_unexpected_at);
3910         SkipUntil(tok::semi);
3911         continue;
3912       }
3913       ConsumeToken();
3914       ExpectAndConsume(tok::l_paren);
3915       if (!Tok.is(tok::identifier)) {
3916         Diag(Tok, diag::err_expected) << tok::identifier;
3917         SkipUntil(tok::semi);
3918         continue;
3919       }
3920       SmallVector<Decl *, 16> Fields;
3921       Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
3922                         Tok.getIdentifierInfo(), Fields);
3923       FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
3924       ConsumeToken();
3925       ExpectAndConsume(tok::r_paren);
3926     }
3927
3928     if (TryConsumeToken(tok::semi))
3929       continue;
3930
3931     if (Tok.is(tok::r_brace)) {
3932       ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
3933       break;
3934     }
3935
3936     ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
3937     // Skip to end of block or statement to avoid ext-warning on extra ';'.
3938     SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
3939     // If we stopped at a ';', eat it.
3940     TryConsumeToken(tok::semi);
3941   }
3942
3943   T.consumeClose();
3944
3945   ParsedAttributes attrs(AttrFactory);
3946   // If attributes exist after struct contents, parse them.
3947   MaybeParseGNUAttributes(attrs);
3948
3949   Actions.ActOnFields(getCurScope(),
3950                       RecordLoc, TagDecl, FieldDecls,
3951                       T.getOpenLocation(), T.getCloseLocation(),
3952                       attrs.getList());
3953   StructScope.Exit();
3954   Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
3955 }
3956
3957 /// ParseEnumSpecifier
3958 ///       enum-specifier: [C99 6.7.2.2]
3959 ///         'enum' identifier[opt] '{' enumerator-list '}'
3960 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
3961 /// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
3962 ///                                                 '}' attributes[opt]
3963 /// [MS]    'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
3964 ///                                                 '}'
3965 ///         'enum' identifier
3966 /// [GNU]   'enum' attributes[opt] identifier
3967 ///
3968 /// [C++11] enum-head '{' enumerator-list[opt] '}'
3969 /// [C++11] enum-head '{' enumerator-list ','  '}'
3970 ///
3971 ///       enum-head: [C++11]
3972 ///         enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
3973 ///         enum-key attribute-specifier-seq[opt] nested-name-specifier
3974 ///             identifier enum-base[opt]
3975 ///
3976 ///       enum-key: [C++11]
3977 ///         'enum'
3978 ///         'enum' 'class'
3979 ///         'enum' 'struct'
3980 ///
3981 ///       enum-base: [C++11]
3982 ///         ':' type-specifier-seq
3983 ///
3984 /// [C++] elaborated-type-specifier:
3985 /// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
3986 ///
3987 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
3988                                 const ParsedTemplateInfo &TemplateInfo,
3989                                 AccessSpecifier AS, DeclSpecContext DSC) {
3990   // Parse the tag portion of this.
3991   if (Tok.is(tok::code_completion)) {
3992     // Code completion for an enum name.
3993     Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
3994     return cutOffParsing();
3995   }
3996
3997   // If attributes exist after tag, parse them.
3998   ParsedAttributesWithRange attrs(AttrFactory);
3999   MaybeParseGNUAttributes(attrs);
4000   MaybeParseCXX11Attributes(attrs);
4001   MaybeParseMicrosoftDeclSpecs(attrs);
4002
4003   SourceLocation ScopedEnumKWLoc;
4004   bool IsScopedUsingClassTag = false;
4005
4006   // In C++11, recognize 'enum class' and 'enum struct'.
4007   if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4008     Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4009                                         : diag::ext_scoped_enum);
4010     IsScopedUsingClassTag = Tok.is(tok::kw_class);
4011     ScopedEnumKWLoc = ConsumeToken();
4012
4013     // Attributes are not allowed between these keywords.  Diagnose,
4014     // but then just treat them like they appeared in the right place.
4015     ProhibitAttributes(attrs);
4016
4017     // They are allowed afterwards, though.
4018     MaybeParseGNUAttributes(attrs);
4019     MaybeParseCXX11Attributes(attrs);
4020     MaybeParseMicrosoftDeclSpecs(attrs);
4021   }
4022
4023   // C++11 [temp.explicit]p12:
4024   //   The usual access controls do not apply to names used to specify
4025   //   explicit instantiations.
4026   // We extend this to also cover explicit specializations.  Note that
4027   // we don't suppress if this turns out to be an elaborated type
4028   // specifier.
4029   bool shouldDelayDiagsInTag =
4030     (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4031      TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4032   SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4033
4034   // Enum definitions should not be parsed in a trailing-return-type.
4035   bool AllowDeclaration = DSC != DSC_trailing;
4036
4037   bool AllowFixedUnderlyingType = AllowDeclaration &&
4038     (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
4039      getLangOpts().ObjC2);
4040
4041   CXXScopeSpec &SS = DS.getTypeSpecScope();
4042   if (getLangOpts().CPlusPlus) {
4043     // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4044     // if a fixed underlying type is allowed.
4045     ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
4046
4047     CXXScopeSpec Spec;
4048     if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
4049                                        /*EnteringContext=*/true))
4050       return;
4051
4052     if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4053       Diag(Tok, diag::err_expected) << tok::identifier;
4054       if (Tok.isNot(tok::l_brace)) {
4055         // Has no name and is not a definition.
4056         // Skip the rest of this declarator, up until the comma or semicolon.
4057         SkipUntil(tok::comma, StopAtSemi);
4058         return;
4059       }
4060     }
4061
4062     SS = Spec;
4063   }
4064
4065   // Must have either 'enum name' or 'enum {...}'.
4066   if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4067       !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
4068     Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4069
4070     // Skip the rest of this declarator, up until the comma or semicolon.
4071     SkipUntil(tok::comma, StopAtSemi);
4072     return;
4073   }
4074
4075   // If an identifier is present, consume and remember it.
4076   IdentifierInfo *Name = nullptr;
4077   SourceLocation NameLoc;
4078   if (Tok.is(tok::identifier)) {
4079     Name = Tok.getIdentifierInfo();
4080     NameLoc = ConsumeToken();
4081   }
4082
4083   if (!Name && ScopedEnumKWLoc.isValid()) {
4084     // C++0x 7.2p2: The optional identifier shall not be omitted in the
4085     // declaration of a scoped enumeration.
4086     Diag(Tok, diag::err_scoped_enum_missing_identifier);
4087     ScopedEnumKWLoc = SourceLocation();
4088     IsScopedUsingClassTag = false;
4089   }
4090
4091   // Okay, end the suppression area.  We'll decide whether to emit the
4092   // diagnostics in a second.
4093   if (shouldDelayDiagsInTag)
4094     diagsFromTag.done();
4095
4096   TypeResult BaseType;
4097
4098   // Parse the fixed underlying type.
4099   bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4100   if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
4101     bool PossibleBitfield = false;
4102     if (CanBeBitfield) {
4103       // If we're in class scope, this can either be an enum declaration with
4104       // an underlying type, or a declaration of a bitfield member. We try to
4105       // use a simple disambiguation scheme first to catch the common cases
4106       // (integer literal, sizeof); if it's still ambiguous, we then consider
4107       // anything that's a simple-type-specifier followed by '(' as an
4108       // expression. This suffices because function types are not valid
4109       // underlying types anyway.
4110       EnterExpressionEvaluationContext Unevaluated(
4111           Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4112       TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
4113       // If the next token starts an expression, we know we're parsing a
4114       // bit-field. This is the common case.
4115       if (TPR == TPResult::True)
4116         PossibleBitfield = true;
4117       // If the next token starts a type-specifier-seq, it may be either a
4118       // a fixed underlying type or the start of a function-style cast in C++;
4119       // lookahead one more token to see if it's obvious that we have a
4120       // fixed underlying type.
4121       else if (TPR == TPResult::False &&
4122                GetLookAheadToken(2).getKind() == tok::semi) {
4123         // Consume the ':'.
4124         ConsumeToken();
4125       } else {
4126         // We have the start of a type-specifier-seq, so we have to perform
4127         // tentative parsing to determine whether we have an expression or a
4128         // type.
4129         TentativeParsingAction TPA(*this);
4130
4131         // Consume the ':'.
4132         ConsumeToken();
4133
4134         // If we see a type specifier followed by an open-brace, we have an
4135         // ambiguity between an underlying type and a C++11 braced
4136         // function-style cast. Resolve this by always treating it as an
4137         // underlying type.
4138         // FIXME: The standard is not entirely clear on how to disambiguate in
4139         // this case.
4140         if ((getLangOpts().CPlusPlus &&
4141              isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
4142             (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
4143           // We'll parse this as a bitfield later.
4144           PossibleBitfield = true;
4145           TPA.Revert();
4146         } else {
4147           // We have a type-specifier-seq.
4148           TPA.Commit();
4149         }
4150       }
4151     } else {
4152       // Consume the ':'.
4153       ConsumeToken();
4154     }
4155
4156     if (!PossibleBitfield) {
4157       SourceRange Range;
4158       BaseType = ParseTypeName(&Range);
4159
4160       if (getLangOpts().CPlusPlus11) {
4161         Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4162       } else if (!getLangOpts().ObjC2) {
4163         if (getLangOpts().CPlusPlus)
4164           Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
4165         else
4166           Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
4167       }
4168     }
4169   }
4170
4171   // There are four options here.  If we have 'friend enum foo;' then this is a
4172   // friend declaration, and cannot have an accompanying definition. If we have
4173   // 'enum foo;', then this is a forward declaration.  If we have
4174   // 'enum foo {...' then this is a definition. Otherwise we have something
4175   // like 'enum foo xyz', a reference.
4176   //
4177   // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4178   // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
4179   // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
4180   //
4181   Sema::TagUseKind TUK;
4182   if (!AllowDeclaration) {
4183     TUK = Sema::TUK_Reference;
4184   } else if (Tok.is(tok::l_brace)) {
4185     if (DS.isFriendSpecified()) {
4186       Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4187         << SourceRange(DS.getFriendSpecLoc());
4188       ConsumeBrace();
4189       SkipUntil(tok::r_brace, StopAtSemi);
4190       TUK = Sema::TUK_Friend;
4191     } else {
4192       TUK = Sema::TUK_Definition;
4193     }
4194   } else if (!isTypeSpecifier(DSC) &&
4195              (Tok.is(tok::semi) ||
4196               (Tok.isAtStartOfLine() &&
4197                !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4198     TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4199     if (Tok.isNot(tok::semi)) {
4200       // A semicolon was missing after this declaration. Diagnose and recover.
4201       ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4202       PP.EnterToken(Tok);
4203       Tok.setKind(tok::semi);
4204     }
4205   } else {
4206     TUK = Sema::TUK_Reference;
4207   }
4208
4209   // If this is an elaborated type specifier, and we delayed
4210   // diagnostics before, just merge them into the current pool.
4211   if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4212     diagsFromTag.redelay();
4213   }
4214
4215   MultiTemplateParamsArg TParams;
4216   if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4217       TUK != Sema::TUK_Reference) {
4218     if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4219       // Skip the rest of this declarator, up until the comma or semicolon.
4220       Diag(Tok, diag::err_enum_template);
4221       SkipUntil(tok::comma, StopAtSemi);
4222       return;
4223     }
4224
4225     if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4226       // Enumerations can't be explicitly instantiated.
4227       DS.SetTypeSpecError();
4228       Diag(StartLoc, diag::err_explicit_instantiation_enum);
4229       return;
4230     }
4231
4232     assert(TemplateInfo.TemplateParams && "no template parameters");
4233     TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4234                                      TemplateInfo.TemplateParams->size());
4235   }
4236
4237   if (TUK == Sema::TUK_Reference)
4238     ProhibitAttributes(attrs);
4239
4240   if (!Name && TUK != Sema::TUK_Definition) {
4241     Diag(Tok, diag::err_enumerator_unnamed_no_def);
4242
4243     // Skip the rest of this declarator, up until the comma or semicolon.
4244     SkipUntil(tok::comma, StopAtSemi);
4245     return;
4246   }
4247
4248   stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4249
4250   Sema::SkipBodyInfo SkipBody;
4251   if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4252       NextToken().is(tok::identifier))
4253     SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4254                                               NextToken().getIdentifierInfo(),
4255                                               NextToken().getLocation());
4256
4257   bool Owned = false;
4258   bool IsDependent = false;
4259   const char *PrevSpec = nullptr;
4260   unsigned DiagID;
4261   Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
4262                                    StartLoc, SS, Name, NameLoc, attrs.getList(),
4263                                    AS, DS.getModulePrivateSpecLoc(), TParams,
4264                                    Owned, IsDependent, ScopedEnumKWLoc,
4265                                    IsScopedUsingClassTag, BaseType,
4266                                    DSC == DSC_type_specifier,
4267                                    DSC == DSC_template_param ||
4268                                    DSC == DSC_template_type_arg, &SkipBody);
4269
4270   if (SkipBody.ShouldSkip) {
4271     assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4272
4273     BalancedDelimiterTracker T(*this, tok::l_brace);
4274     T.consumeOpen();
4275     T.skipToEnd();
4276
4277     if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4278                            NameLoc.isValid() ? NameLoc : StartLoc,
4279                            PrevSpec, DiagID, TagDecl, Owned,
4280                            Actions.getASTContext().getPrintingPolicy()))
4281       Diag(StartLoc, DiagID) << PrevSpec;
4282     return;
4283   }
4284
4285   if (IsDependent) {
4286     // This enum has a dependent nested-name-specifier. Handle it as a
4287     // dependent tag.
4288     if (!Name) {
4289       DS.SetTypeSpecError();
4290       Diag(Tok, diag::err_expected_type_name_after_typename);
4291       return;
4292     }
4293
4294     TypeResult Type = Actions.ActOnDependentTag(
4295         getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4296     if (Type.isInvalid()) {
4297       DS.SetTypeSpecError();
4298       return;
4299     }
4300
4301     if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4302                            NameLoc.isValid() ? NameLoc : StartLoc,
4303                            PrevSpec, DiagID, Type.get(),
4304                            Actions.getASTContext().getPrintingPolicy()))
4305       Diag(StartLoc, DiagID) << PrevSpec;
4306
4307     return;
4308   }
4309
4310   if (!TagDecl) {
4311     // The action failed to produce an enumeration tag. If this is a
4312     // definition, consume the entire definition.
4313     if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4314       ConsumeBrace();
4315       SkipUntil(tok::r_brace, StopAtSemi);
4316     }
4317
4318     DS.SetTypeSpecError();
4319     return;
4320   }
4321
4322   if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4323     Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4324     ParseEnumBody(StartLoc, D);
4325     if (SkipBody.CheckSameAsPrevious &&
4326         !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4327       DS.SetTypeSpecError();
4328       return;
4329     }
4330   }
4331
4332   if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4333                          NameLoc.isValid() ? NameLoc : StartLoc,
4334                          PrevSpec, DiagID, TagDecl, Owned,
4335                          Actions.getASTContext().getPrintingPolicy()))
4336     Diag(StartLoc, DiagID) << PrevSpec;
4337 }
4338
4339 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4340 ///       enumerator-list:
4341 ///         enumerator
4342 ///         enumerator-list ',' enumerator
4343 ///       enumerator:
4344 ///         enumeration-constant attributes[opt]
4345 ///         enumeration-constant attributes[opt] '=' constant-expression
4346 ///       enumeration-constant:
4347 ///         identifier
4348 ///
4349 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4350   // Enter the scope of the enum body and start the definition.
4351   ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4352   Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4353
4354   BalancedDelimiterTracker T(*this, tok::l_brace);
4355   T.consumeOpen();
4356
4357   // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4358   if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4359     Diag(Tok, diag::err_empty_enum);
4360
4361   SmallVector<Decl *, 32> EnumConstantDecls;
4362   SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4363
4364   Decl *LastEnumConstDecl = nullptr;
4365
4366   // Parse the enumerator-list.
4367   while (Tok.isNot(tok::r_brace)) {
4368     // Parse enumerator. If failed, try skipping till the start of the next
4369     // enumerator definition.
4370     if (Tok.isNot(tok::identifier)) {
4371       Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4372       if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4373           TryConsumeToken(tok::comma))
4374         continue;
4375       break;
4376     }
4377     IdentifierInfo *Ident = Tok.getIdentifierInfo();
4378     SourceLocation IdentLoc = ConsumeToken();
4379
4380     // If attributes exist after the enumerator, parse them.
4381     ParsedAttributesWithRange attrs(AttrFactory);
4382     MaybeParseGNUAttributes(attrs);
4383     ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4384     if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
4385       if (!getLangOpts().CPlusPlus1z)
4386         Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
4387             << 1 /*enumerator*/;
4388       ParseCXX11Attributes(attrs);
4389     }
4390
4391     SourceLocation EqualLoc;
4392     ExprResult AssignedVal;
4393     EnumAvailabilityDiags.emplace_back(*this);
4394
4395     if (TryConsumeToken(tok::equal, EqualLoc)) {
4396       AssignedVal = ParseConstantExpression();
4397       if (AssignedVal.isInvalid())
4398         SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4399     }
4400
4401     // Install the enumerator constant into EnumDecl.
4402     Decl *EnumConstDecl = Actions.ActOnEnumConstant(
4403         getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident,
4404         attrs.getList(), EqualLoc, AssignedVal.get());
4405     EnumAvailabilityDiags.back().done();
4406
4407     EnumConstantDecls.push_back(EnumConstDecl);
4408     LastEnumConstDecl = EnumConstDecl;
4409
4410     if (Tok.is(tok::identifier)) {
4411       // We're missing a comma between enumerators.
4412       SourceLocation Loc = getEndOfPreviousToken();
4413       Diag(Loc, diag::err_enumerator_list_missing_comma)
4414         << FixItHint::CreateInsertion(Loc, ", ");
4415       continue;
4416     }
4417
4418     // Emumerator definition must be finished, only comma or r_brace are
4419     // allowed here.
4420     SourceLocation CommaLoc;
4421     if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4422       if (EqualLoc.isValid())
4423         Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4424                                                            << tok::comma;
4425       else
4426         Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4427       if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4428         if (TryConsumeToken(tok::comma, CommaLoc))
4429           continue;
4430       } else {
4431         break;
4432       }
4433     }
4434
4435     // If comma is followed by r_brace, emit appropriate warning.
4436     if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4437       if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4438         Diag(CommaLoc, getLangOpts().CPlusPlus ?
4439                diag::ext_enumerator_list_comma_cxx :
4440                diag::ext_enumerator_list_comma_c)
4441           << FixItHint::CreateRemoval(CommaLoc);
4442       else if (getLangOpts().CPlusPlus11)
4443         Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4444           << FixItHint::CreateRemoval(CommaLoc);
4445       break;
4446     }
4447   }
4448
4449   // Eat the }.
4450   T.consumeClose();
4451
4452   // If attributes exist after the identifier list, parse them.
4453   ParsedAttributes attrs(AttrFactory);
4454   MaybeParseGNUAttributes(attrs);
4455
4456   Actions.ActOnEnumBody(StartLoc, T.getRange(),
4457                         EnumDecl, EnumConstantDecls,
4458                         getCurScope(),
4459                         attrs.getList());
4460
4461   // Now handle enum constant availability diagnostics.
4462   assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4463   for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4464     ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4465     EnumAvailabilityDiags[i].redelay();
4466     PD.complete(EnumConstantDecls[i]);
4467   }
4468
4469   EnumScope.Exit();
4470   Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4471
4472   // The next token must be valid after an enum definition. If not, a ';'
4473   // was probably forgotten.
4474   bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4475   if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4476     ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4477     // Push this token back into the preprocessor and change our current token
4478     // to ';' so that the rest of the code recovers as though there were an
4479     // ';' after the definition.
4480     PP.EnterToken(Tok);
4481     Tok.setKind(tok::semi);
4482   }
4483 }
4484
4485 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4486 /// is definitely a type-specifier.  Return false if it isn't part of a type
4487 /// specifier or if we're not sure.
4488 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4489   switch (Tok.getKind()) {
4490   default: return false;
4491     // type-specifiers
4492   case tok::kw_short:
4493   case tok::kw_long:
4494   case tok::kw___int64:
4495   case tok::kw___int128:
4496   case tok::kw_signed:
4497   case tok::kw_unsigned:
4498   case tok::kw__Complex:
4499   case tok::kw__Imaginary:
4500   case tok::kw_void:
4501   case tok::kw_char:
4502   case tok::kw_wchar_t:
4503   case tok::kw_char16_t:
4504   case tok::kw_char32_t:
4505   case tok::kw_int:
4506   case tok::kw_half:
4507   case tok::kw_float:
4508   case tok::kw_double:
4509   case tok::kw___float128:
4510   case tok::kw_bool:
4511   case tok::kw__Bool:
4512   case tok::kw__Decimal32:
4513   case tok::kw__Decimal64:
4514   case tok::kw__Decimal128:
4515   case tok::kw___vector:
4516 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4517 #include "clang/Basic/OpenCLImageTypes.def"
4518
4519     // struct-or-union-specifier (C99) or class-specifier (C++)
4520   case tok::kw_class:
4521   case tok::kw_struct:
4522   case tok::kw___interface:
4523   case tok::kw_union:
4524     // enum-specifier
4525   case tok::kw_enum:
4526
4527     // typedef-name
4528   case tok::annot_typename:
4529     return true;
4530   }
4531 }
4532
4533 /// isTypeSpecifierQualifier - Return true if the current token could be the
4534 /// start of a specifier-qualifier-list.
4535 bool Parser::isTypeSpecifierQualifier() {
4536   switch (Tok.getKind()) {
4537   default: return false;
4538
4539   case tok::identifier:   // foo::bar
4540     if (TryAltiVecVectorToken())
4541       return true;
4542     // Fall through.
4543   case tok::kw_typename:  // typename T::type
4544     // Annotate typenames and C++ scope specifiers.  If we get one, just
4545     // recurse to handle whatever we get.
4546     if (TryAnnotateTypeOrScopeToken())
4547       return true;
4548     if (Tok.is(tok::identifier))
4549       return false;
4550     return isTypeSpecifierQualifier();
4551
4552   case tok::coloncolon:   // ::foo::bar
4553     if (NextToken().is(tok::kw_new) ||    // ::new
4554         NextToken().is(tok::kw_delete))   // ::delete
4555       return false;
4556
4557     if (TryAnnotateTypeOrScopeToken())
4558       return true;
4559     return isTypeSpecifierQualifier();
4560
4561     // GNU attributes support.
4562   case tok::kw___attribute:
4563     // GNU typeof support.
4564   case tok::kw_typeof:
4565
4566     // type-specifiers
4567   case tok::kw_short:
4568   case tok::kw_long:
4569   case tok::kw___int64:
4570   case tok::kw___int128:
4571   case tok::kw_signed:
4572   case tok::kw_unsigned:
4573   case tok::kw__Complex:
4574   case tok::kw__Imaginary:
4575   case tok::kw_void:
4576   case tok::kw_char:
4577   case tok::kw_wchar_t:
4578   case tok::kw_char16_t:
4579   case tok::kw_char32_t:
4580   case tok::kw_int:
4581   case tok::kw_half:
4582   case tok::kw_float:
4583   case tok::kw_double:
4584   case tok::kw___float128:
4585   case tok::kw_bool:
4586   case tok::kw__Bool:
4587   case tok::kw__Decimal32:
4588   case tok::kw__Decimal64:
4589   case tok::kw__Decimal128:
4590   case tok::kw___vector:
4591 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4592 #include "clang/Basic/OpenCLImageTypes.def"
4593
4594     // struct-or-union-specifier (C99) or class-specifier (C++)
4595   case tok::kw_class:
4596   case tok::kw_struct:
4597   case tok::kw___interface:
4598   case tok::kw_union:
4599     // enum-specifier
4600   case tok::kw_enum:
4601
4602     // type-qualifier
4603   case tok::kw_const:
4604   case tok::kw_volatile:
4605   case tok::kw_restrict:
4606
4607     // Debugger support.
4608   case tok::kw___unknown_anytype:
4609
4610     // typedef-name
4611   case tok::annot_typename:
4612     return true;
4613
4614     // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4615   case tok::less:
4616     return getLangOpts().ObjC1;
4617
4618   case tok::kw___cdecl:
4619   case tok::kw___stdcall:
4620   case tok::kw___fastcall:
4621   case tok::kw___thiscall:
4622   case tok::kw___regcall:
4623   case tok::kw___vectorcall:
4624   case tok::kw___w64:
4625   case tok::kw___ptr64:
4626   case tok::kw___ptr32:
4627   case tok::kw___pascal:
4628   case tok::kw___unaligned:
4629
4630   case tok::kw__Nonnull:
4631   case tok::kw__Nullable:
4632   case tok::kw__Null_unspecified:
4633
4634   case tok::kw___kindof:
4635
4636   case tok::kw___private:
4637   case tok::kw___local:
4638   case tok::kw___global:
4639   case tok::kw___constant:
4640   case tok::kw___generic:
4641   case tok::kw___read_only:
4642   case tok::kw___read_write:
4643   case tok::kw___write_only:
4644
4645     return true;
4646
4647   // C11 _Atomic
4648   case tok::kw__Atomic:
4649     return true;
4650   }
4651 }
4652
4653 /// isDeclarationSpecifier() - Return true if the current token is part of a
4654 /// declaration specifier.
4655 ///
4656 /// \param DisambiguatingWithExpression True to indicate that the purpose of
4657 /// this check is to disambiguate between an expression and a declaration.
4658 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4659   switch (Tok.getKind()) {
4660   default: return false;
4661
4662   case tok::kw_pipe:
4663     return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4664
4665   case tok::identifier:   // foo::bar
4666     // Unfortunate hack to support "Class.factoryMethod" notation.
4667     if (getLangOpts().ObjC1 && NextToken().is(tok::period))
4668       return false;
4669     if (TryAltiVecVectorToken())
4670       return true;
4671     // Fall through.
4672   case tok::kw_decltype: // decltype(T())::type
4673   case tok::kw_typename: // typename T::type
4674     // Annotate typenames and C++ scope specifiers.  If we get one, just
4675     // recurse to handle whatever we get.
4676     if (TryAnnotateTypeOrScopeToken())
4677       return true;
4678     if (Tok.is(tok::identifier))
4679       return false;
4680
4681     // If we're in Objective-C and we have an Objective-C class type followed
4682     // by an identifier and then either ':' or ']', in a place where an
4683     // expression is permitted, then this is probably a class message send
4684     // missing the initial '['. In this case, we won't consider this to be
4685     // the start of a declaration.
4686     if (DisambiguatingWithExpression &&
4687         isStartOfObjCClassMessageMissingOpenBracket())
4688       return false;
4689
4690     return isDeclarationSpecifier();
4691
4692   case tok::coloncolon:   // ::foo::bar
4693     if (NextToken().is(tok::kw_new) ||    // ::new
4694         NextToken().is(tok::kw_delete))   // ::delete
4695       return false;
4696
4697     // Annotate typenames and C++ scope specifiers.  If we get one, just
4698     // recurse to handle whatever we get.
4699     if (TryAnnotateTypeOrScopeToken())
4700       return true;
4701     return isDeclarationSpecifier();
4702
4703     // storage-class-specifier
4704   case tok::kw_typedef:
4705   case tok::kw_extern:
4706   case tok::kw___private_extern__:
4707   case tok::kw_static:
4708   case tok::kw_auto:
4709   case tok::kw___auto_type:
4710   case tok::kw_register:
4711   case tok::kw___thread:
4712   case tok::kw_thread_local:
4713   case tok::kw__Thread_local:
4714
4715     // Modules
4716   case tok::kw___module_private__:
4717
4718     // Debugger support
4719   case tok::kw___unknown_anytype:
4720
4721     // type-specifiers
4722   case tok::kw_short:
4723   case tok::kw_long:
4724   case tok::kw___int64:
4725   case tok::kw___int128:
4726   case tok::kw_signed:
4727   case tok::kw_unsigned:
4728   case tok::kw__Complex:
4729   case tok::kw__Imaginary:
4730   case tok::kw_void:
4731   case tok::kw_char:
4732   case tok::kw_wchar_t:
4733   case tok::kw_char16_t:
4734   case tok::kw_char32_t:
4735
4736   case tok::kw_int:
4737   case tok::kw_half:
4738   case tok::kw_float:
4739   case tok::kw_double:
4740   case tok::kw___float128:
4741   case tok::kw_bool:
4742   case tok::kw__Bool:
4743   case tok::kw__Decimal32:
4744   case tok::kw__Decimal64:
4745   case tok::kw__Decimal128:
4746   case tok::kw___vector:
4747
4748     // struct-or-union-specifier (C99) or class-specifier (C++)
4749   case tok::kw_class:
4750   case tok::kw_struct:
4751   case tok::kw_union:
4752   case tok::kw___interface:
4753     // enum-specifier
4754   case tok::kw_enum:
4755
4756     // type-qualifier
4757   case tok::kw_const:
4758   case tok::kw_volatile:
4759   case tok::kw_restrict:
4760
4761     // function-specifier
4762   case tok::kw_inline:
4763   case tok::kw_virtual:
4764   case tok::kw_explicit:
4765   case tok::kw__Noreturn:
4766
4767     // alignment-specifier
4768   case tok::kw__Alignas:
4769
4770     // friend keyword.
4771   case tok::kw_friend:
4772
4773     // static_assert-declaration
4774   case tok::kw__Static_assert:
4775
4776     // GNU typeof support.
4777   case tok::kw_typeof:
4778
4779     // GNU attributes.
4780   case tok::kw___attribute:
4781
4782     // C++11 decltype and constexpr.
4783   case tok::annot_decltype:
4784   case tok::kw_constexpr:
4785
4786     // C++ Concepts TS - concept
4787   case tok::kw_concept:
4788
4789     // C11 _Atomic
4790   case tok::kw__Atomic:
4791     return true;
4792
4793     // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4794   case tok::less:
4795     return getLangOpts().ObjC1;
4796
4797     // typedef-name
4798   case tok::annot_typename:
4799     return !DisambiguatingWithExpression ||
4800            !isStartOfObjCClassMessageMissingOpenBracket();
4801
4802   case tok::kw___declspec:
4803   case tok::kw___cdecl:
4804   case tok::kw___stdcall:
4805   case tok::kw___fastcall:
4806   case tok::kw___thiscall:
4807   case tok::kw___regcall:
4808   case tok::kw___vectorcall:
4809   case tok::kw___w64:
4810   case tok::kw___sptr:
4811   case tok::kw___uptr:
4812   case tok::kw___ptr64:
4813   case tok::kw___ptr32:
4814   case tok::kw___forceinline:
4815   case tok::kw___pascal:
4816   case tok::kw___unaligned:
4817
4818   case tok::kw__Nonnull:
4819   case tok::kw__Nullable:
4820   case tok::kw__Null_unspecified:
4821
4822   case tok::kw___kindof:
4823
4824   case tok::kw___private:
4825   case tok::kw___local:
4826   case tok::kw___global:
4827   case tok::kw___constant:
4828   case tok::kw___generic:
4829   case tok::kw___read_only:
4830   case tok::kw___read_write:
4831   case tok::kw___write_only:
4832 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4833 #include "clang/Basic/OpenCLImageTypes.def"
4834
4835     return true;
4836   }
4837 }
4838
4839 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
4840   TentativeParsingAction TPA(*this);
4841
4842   // Parse the C++ scope specifier.
4843   CXXScopeSpec SS;
4844   if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
4845                                      /*EnteringContext=*/true)) {
4846     TPA.Revert();
4847     return false;
4848   }
4849
4850   // Parse the constructor name.
4851   if (Tok.is(tok::identifier)) {
4852     // We already know that we have a constructor name; just consume
4853     // the token.
4854     ConsumeToken();
4855   } else if (Tok.is(tok::annot_template_id)) {
4856     ConsumeAnnotationToken();
4857   } else {
4858     TPA.Revert();
4859     return false;
4860   }
4861
4862   // There may be attributes here, appertaining to the constructor name or type
4863   // we just stepped past.
4864   SkipCXX11Attributes();
4865
4866   // Current class name must be followed by a left parenthesis.
4867   if (Tok.isNot(tok::l_paren)) {
4868     TPA.Revert();
4869     return false;
4870   }
4871   ConsumeParen();
4872
4873   // A right parenthesis, or ellipsis followed by a right parenthesis signals
4874   // that we have a constructor.
4875   if (Tok.is(tok::r_paren) ||
4876       (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
4877     TPA.Revert();
4878     return true;
4879   }
4880
4881   // A C++11 attribute here signals that we have a constructor, and is an
4882   // attribute on the first constructor parameter.
4883   if (getLangOpts().CPlusPlus11 &&
4884       isCXX11AttributeSpecifier(/*Disambiguate*/ false,
4885                                 /*OuterMightBeMessageSend*/ true)) {
4886     TPA.Revert();
4887     return true;
4888   }
4889
4890   // If we need to, enter the specified scope.
4891   DeclaratorScopeObj DeclScopeObj(*this, SS);
4892   if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
4893     DeclScopeObj.EnterDeclaratorScope();
4894
4895   // Optionally skip Microsoft attributes.
4896   ParsedAttributes Attrs(AttrFactory);
4897   MaybeParseMicrosoftAttributes(Attrs);
4898
4899   // Check whether the next token(s) are part of a declaration
4900   // specifier, in which case we have the start of a parameter and,
4901   // therefore, we know that this is a constructor.
4902   bool IsConstructor = false;
4903   if (isDeclarationSpecifier())
4904     IsConstructor = true;
4905   else if (Tok.is(tok::identifier) ||
4906            (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
4907     // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
4908     // This might be a parenthesized member name, but is more likely to
4909     // be a constructor declaration with an invalid argument type. Keep
4910     // looking.
4911     if (Tok.is(tok::annot_cxxscope))
4912       ConsumeAnnotationToken();
4913     ConsumeToken();
4914
4915     // If this is not a constructor, we must be parsing a declarator,
4916     // which must have one of the following syntactic forms (see the
4917     // grammar extract at the start of ParseDirectDeclarator):
4918     switch (Tok.getKind()) {
4919     case tok::l_paren:
4920       // C(X   (   int));
4921     case tok::l_square:
4922       // C(X   [   5]);
4923       // C(X   [   [attribute]]);
4924     case tok::coloncolon:
4925       // C(X   ::   Y);
4926       // C(X   ::   *p);
4927       // Assume this isn't a constructor, rather than assuming it's a
4928       // constructor with an unnamed parameter of an ill-formed type.
4929       break;
4930
4931     case tok::r_paren:
4932       // C(X   )
4933
4934       // Skip past the right-paren and any following attributes to get to
4935       // the function body or trailing-return-type.
4936       ConsumeParen();
4937       SkipCXX11Attributes();
4938
4939       if (DeductionGuide) {
4940         // C(X) -> ... is a deduction guide.
4941         IsConstructor = Tok.is(tok::arrow);
4942         break;
4943       }
4944       if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
4945         // Assume these were meant to be constructors:
4946         //   C(X)   :    (the name of a bit-field cannot be parenthesized).
4947         //   C(X)   try  (this is otherwise ill-formed).
4948         IsConstructor = true;
4949       }
4950       if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
4951         // If we have a constructor name within the class definition,
4952         // assume these were meant to be constructors:
4953         //   C(X)   {
4954         //   C(X)   ;
4955         // ... because otherwise we would be declaring a non-static data
4956         // member that is ill-formed because it's of the same type as its
4957         // surrounding class.
4958         //
4959         // FIXME: We can actually do this whether or not the name is qualified,
4960         // because if it is qualified in this context it must be being used as
4961         // a constructor name.
4962         // currently, so we're somewhat conservative here.
4963         IsConstructor = IsUnqualified;
4964       }
4965       break;
4966
4967     default:
4968       IsConstructor = true;
4969       break;
4970     }
4971   }
4972
4973   TPA.Revert();
4974   return IsConstructor;
4975 }
4976
4977 /// ParseTypeQualifierListOpt
4978 ///          type-qualifier-list: [C99 6.7.5]
4979 ///            type-qualifier
4980 /// [vendor]   attributes
4981 ///              [ only if AttrReqs & AR_VendorAttributesParsed ]
4982 ///            type-qualifier-list type-qualifier
4983 /// [vendor]   type-qualifier-list attributes
4984 ///              [ only if AttrReqs & AR_VendorAttributesParsed ]
4985 /// [C++0x]    attribute-specifier[opt] is allowed before cv-qualifier-seq
4986 ///              [ only if AttReqs & AR_CXX11AttributesParsed ]
4987 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
4988 /// AttrRequirements bitmask values.
4989 void Parser::ParseTypeQualifierListOpt(
4990     DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
4991     bool IdentifierRequired,
4992     Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
4993   if (getLangOpts().CPlusPlus11 && (AttrReqs & AR_CXX11AttributesParsed) &&
4994       isCXX11AttributeSpecifier()) {
4995     ParsedAttributesWithRange attrs(AttrFactory);
4996     ParseCXX11Attributes(attrs);
4997     DS.takeAttributesFrom(attrs);
4998   }
4999
5000   SourceLocation EndLoc;
5001
5002   while (1) {
5003     bool isInvalid = false;
5004     const char *PrevSpec = nullptr;
5005     unsigned DiagID = 0;
5006     SourceLocation Loc = Tok.getLocation();
5007
5008     switch (Tok.getKind()) {
5009     case tok::code_completion:
5010       if (CodeCompletionHandler)
5011         (*CodeCompletionHandler)();
5012       else
5013         Actions.CodeCompleteTypeQualifiers(DS);
5014       return cutOffParsing();
5015
5016     case tok::kw_const:
5017       isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec, DiagID,
5018                                  getLangOpts());
5019       break;
5020     case tok::kw_volatile:
5021       isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5022                                  getLangOpts());
5023       break;
5024     case tok::kw_restrict:
5025       isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5026                                  getLangOpts());
5027       break;
5028     case tok::kw__Atomic:
5029       if (!AtomicAllowed)
5030         goto DoneWithTypeQuals;
5031       isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5032                                  getLangOpts());
5033       break;
5034
5035     // OpenCL qualifiers:
5036     case tok::kw___private:
5037     case tok::kw___global:
5038     case tok::kw___local:
5039     case tok::kw___constant:
5040     case tok::kw___generic:
5041     case tok::kw___read_only:
5042     case tok::kw___write_only:
5043     case tok::kw___read_write:
5044       ParseOpenCLQualifiers(DS.getAttributes());
5045       break;
5046
5047     case tok::kw___unaligned:
5048       isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5049                                  getLangOpts());
5050       break;
5051     case tok::kw___uptr:
5052       // GNU libc headers in C mode use '__uptr' as an identifer which conflicts
5053       // with the MS modifier keyword.
5054       if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
5055           IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5056         if (TryKeywordIdentFallback(false))
5057           continue;
5058       }
5059       LLVM_FALLTHROUGH;
5060     case tok::kw___sptr:
5061     case tok::kw___w64:
5062     case tok::kw___ptr64:
5063     case tok::kw___ptr32:
5064     case tok::kw___cdecl:
5065     case tok::kw___stdcall:
5066     case tok::kw___fastcall:
5067     case tok::kw___thiscall:
5068     case tok::kw___regcall:
5069     case tok::kw___vectorcall:
5070       if (AttrReqs & AR_DeclspecAttributesParsed) {
5071         ParseMicrosoftTypeAttributes(DS.getAttributes());
5072         continue;
5073       }
5074       goto DoneWithTypeQuals;
5075     case tok::kw___pascal:
5076       if (AttrReqs & AR_VendorAttributesParsed) {
5077         ParseBorlandTypeAttributes(DS.getAttributes());
5078         continue;
5079       }
5080       goto DoneWithTypeQuals;
5081
5082     // Nullability type specifiers.
5083     case tok::kw__Nonnull:
5084     case tok::kw__Nullable:
5085     case tok::kw__Null_unspecified:
5086       ParseNullabilityTypeSpecifiers(DS.getAttributes());
5087       continue;
5088
5089     // Objective-C 'kindof' types.
5090     case tok::kw___kindof:
5091       DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
5092                                 nullptr, 0, AttributeList::AS_Keyword);
5093       (void)ConsumeToken();
5094       continue;
5095
5096     case tok::kw___attribute:
5097       if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5098         // When GNU attributes are expressly forbidden, diagnose their usage.
5099         Diag(Tok, diag::err_attributes_not_allowed);
5100
5101       // Parse the attributes even if they are rejected to ensure that error
5102       // recovery is graceful.
5103       if (AttrReqs & AR_GNUAttributesParsed ||
5104           AttrReqs & AR_GNUAttributesParsedAndRejected) {
5105         ParseGNUAttributes(DS.getAttributes());
5106         continue; // do *not* consume the next token!
5107       }
5108       // otherwise, FALL THROUGH!
5109       LLVM_FALLTHROUGH;
5110     default:
5111       DoneWithTypeQuals:
5112       // If this is not a type-qualifier token, we're done reading type
5113       // qualifiers.  First verify that DeclSpec's are consistent.
5114       DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
5115       if (EndLoc.isValid())
5116         DS.SetRangeEnd(EndLoc);
5117       return;
5118     }
5119
5120     // If the specifier combination wasn't legal, issue a diagnostic.
5121     if (isInvalid) {
5122       assert(PrevSpec && "Method did not return previous specifier!");
5123       Diag(Tok, DiagID) << PrevSpec;
5124     }
5125     EndLoc = ConsumeToken();
5126   }
5127 }
5128
5129 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
5130 ///
5131 void Parser::ParseDeclarator(Declarator &D) {
5132   /// This implements the 'declarator' production in the C grammar, then checks
5133   /// for well-formedness and issues diagnostics.
5134   ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5135 }
5136
5137 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
5138                                unsigned TheContext) {
5139   if (Kind == tok::star || Kind == tok::caret)
5140     return true;
5141
5142   if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
5143     return true;
5144
5145   if (!Lang.CPlusPlus)
5146     return false;
5147
5148   if (Kind == tok::amp)
5149     return true;
5150
5151   // We parse rvalue refs in C++03, because otherwise the errors are scary.
5152   // But we must not parse them in conversion-type-ids and new-type-ids, since
5153   // those can be legitimately followed by a && operator.
5154   // (The same thing can in theory happen after a trailing-return-type, but
5155   // since those are a C++11 feature, there is no rejects-valid issue there.)
5156   if (Kind == tok::ampamp)
5157     return Lang.CPlusPlus11 || (TheContext != Declarator::ConversionIdContext &&
5158                                 TheContext != Declarator::CXXNewContext);
5159
5160   return false;
5161 }
5162
5163 // Indicates whether the given declarator is a pipe declarator.
5164 static bool isPipeDeclerator(const Declarator &D) {
5165   const unsigned NumTypes = D.getNumTypeObjects();
5166
5167   for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5168     if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5169       return true;
5170
5171   return false;
5172 }
5173
5174 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5175 /// is parsed by the function passed to it. Pass null, and the direct-declarator
5176 /// isn't parsed at all, making this function effectively parse the C++
5177 /// ptr-operator production.
5178 ///
5179 /// If the grammar of this construct is extended, matching changes must also be
5180 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5181 /// isConstructorDeclarator.
5182 ///
5183 ///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5184 /// [C]     pointer[opt] direct-declarator
5185 /// [C++]   direct-declarator
5186 /// [C++]   ptr-operator declarator
5187 ///
5188 ///       pointer: [C99 6.7.5]
5189 ///         '*' type-qualifier-list[opt]
5190 ///         '*' type-qualifier-list[opt] pointer
5191 ///
5192 ///       ptr-operator:
5193 ///         '*' cv-qualifier-seq[opt]
5194 ///         '&'
5195 /// [C++0x] '&&'
5196 /// [GNU]   '&' restrict[opt] attributes[opt]
5197 /// [GNU?]  '&&' restrict[opt] attributes[opt]
5198 ///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
5199 void Parser::ParseDeclaratorInternal(Declarator &D,
5200                                      DirectDeclParseFunction DirectDeclParser) {
5201   if (Diags.hasAllExtensionsSilenced())
5202     D.setExtension();
5203
5204   // C++ member pointers start with a '::' or a nested-name.
5205   // Member pointers get special handling, since there's no place for the
5206   // scope spec in the generic path below.
5207   if (getLangOpts().CPlusPlus &&
5208       (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
5209        (Tok.is(tok::identifier) &&
5210         (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
5211        Tok.is(tok::annot_cxxscope))) {
5212     bool EnteringContext = D.getContext() == Declarator::FileContext ||
5213                            D.getContext() == Declarator::MemberContext;
5214     CXXScopeSpec SS;
5215     ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
5216
5217     if (SS.isNotEmpty()) {
5218       if (Tok.isNot(tok::star)) {
5219         // The scope spec really belongs to the direct-declarator.
5220         if (D.mayHaveIdentifier())
5221           D.getCXXScopeSpec() = SS;
5222         else
5223           AnnotateScopeToken(SS, true);
5224
5225         if (DirectDeclParser)
5226           (this->*DirectDeclParser)(D);
5227         return;
5228       }
5229
5230       SourceLocation Loc = ConsumeToken();
5231       D.SetRangeEnd(Loc);
5232       DeclSpec DS(AttrFactory);
5233       ParseTypeQualifierListOpt(DS);
5234       D.ExtendWithDeclSpec(DS);
5235
5236       // Recurse to parse whatever is left.
5237       ParseDeclaratorInternal(D, DirectDeclParser);
5238
5239       // Sema will have to catch (syntactically invalid) pointers into global
5240       // scope. It has to catch pointers into namespace scope anyway.
5241       D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
5242                                                       DS.getLocEnd()),
5243                     DS.getAttributes(),
5244                     /* Don't replace range end. */SourceLocation());
5245       return;
5246     }
5247   }
5248
5249   tok::TokenKind Kind = Tok.getKind();
5250
5251   if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
5252     DeclSpec DS(AttrFactory);
5253     ParseTypeQualifierListOpt(DS);
5254
5255     D.AddTypeInfo(
5256         DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
5257         DS.getAttributes(), SourceLocation());
5258   }
5259
5260   // Not a pointer, C++ reference, or block.
5261   if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
5262     if (DirectDeclParser)
5263       (this->*DirectDeclParser)(D);
5264     return;
5265   }
5266
5267   // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5268   // '&&' -> rvalue reference
5269   SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
5270   D.SetRangeEnd(Loc);
5271
5272   if (Kind == tok::star || Kind == tok::caret) {
5273     // Is a pointer.
5274     DeclSpec DS(AttrFactory);
5275
5276     // GNU attributes are not allowed here in a new-type-id, but Declspec and
5277     // C++11 attributes are allowed.
5278     unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
5279                             ((D.getContext() != Declarator::CXXNewContext)
5280                                  ? AR_GNUAttributesParsed
5281                                  : AR_GNUAttributesParsedAndRejected);
5282     ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
5283     D.ExtendWithDeclSpec(DS);
5284
5285     // Recursively parse the declarator.
5286     ParseDeclaratorInternal(D, DirectDeclParser);
5287     if (Kind == tok::star)
5288       // Remember that we parsed a pointer type, and remember the type-quals.
5289       D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
5290                                                 DS.getConstSpecLoc(),
5291                                                 DS.getVolatileSpecLoc(),
5292                                                 DS.getRestrictSpecLoc(),
5293                                                 DS.getAtomicSpecLoc(),
5294                                                 DS.getUnalignedSpecLoc()),
5295                     DS.getAttributes(),
5296                     SourceLocation());
5297     else
5298       // Remember that we parsed a Block type, and remember the type-quals.
5299       D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
5300                                                      Loc),
5301                     DS.getAttributes(),
5302                     SourceLocation());
5303   } else {
5304     // Is a reference
5305     DeclSpec DS(AttrFactory);
5306
5307     // Complain about rvalue references in C++03, but then go on and build
5308     // the declarator.
5309     if (Kind == tok::ampamp)
5310       Diag(Loc, getLangOpts().CPlusPlus11 ?
5311            diag::warn_cxx98_compat_rvalue_reference :
5312            diag::ext_rvalue_reference);
5313
5314     // GNU-style and C++11 attributes are allowed here, as is restrict.
5315     ParseTypeQualifierListOpt(DS);
5316     D.ExtendWithDeclSpec(DS);
5317
5318     // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5319     // cv-qualifiers are introduced through the use of a typedef or of a
5320     // template type argument, in which case the cv-qualifiers are ignored.
5321     if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5322       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5323         Diag(DS.getConstSpecLoc(),
5324              diag::err_invalid_reference_qualifier_application) << "const";
5325       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5326         Diag(DS.getVolatileSpecLoc(),
5327              diag::err_invalid_reference_qualifier_application) << "volatile";
5328       // 'restrict' is permitted as an extension.
5329       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5330         Diag(DS.getAtomicSpecLoc(),
5331              diag::err_invalid_reference_qualifier_application) << "_Atomic";
5332     }
5333
5334     // Recursively parse the declarator.
5335     ParseDeclaratorInternal(D, DirectDeclParser);
5336
5337     if (D.getNumTypeObjects() > 0) {
5338       // C++ [dcl.ref]p4: There shall be no references to references.
5339       DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5340       if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5341         if (const IdentifierInfo *II = D.getIdentifier())
5342           Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5343            << II;
5344         else
5345           Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5346             << "type name";
5347
5348         // Once we've complained about the reference-to-reference, we
5349         // can go ahead and build the (technically ill-formed)
5350         // declarator: reference collapsing will take care of it.
5351       }
5352     }
5353
5354     // Remember that we parsed a reference type.
5355     D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
5356                                                 Kind == tok::amp),
5357                   DS.getAttributes(),
5358                   SourceLocation());
5359   }
5360 }
5361
5362 // When correcting from misplaced brackets before the identifier, the location
5363 // is saved inside the declarator so that other diagnostic messages can use
5364 // them.  This extracts and returns that location, or returns the provided
5365 // location if a stored location does not exist.
5366 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5367                                                 SourceLocation Loc) {
5368   if (D.getName().StartLocation.isInvalid() &&
5369       D.getName().EndLocation.isValid())
5370     return D.getName().EndLocation;
5371
5372   return Loc;
5373 }
5374
5375 /// ParseDirectDeclarator
5376 ///       direct-declarator: [C99 6.7.5]
5377 /// [C99]   identifier
5378 ///         '(' declarator ')'
5379 /// [GNU]   '(' attributes declarator ')'
5380 /// [C90]   direct-declarator '[' constant-expression[opt] ']'
5381 /// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5382 /// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5383 /// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5384 /// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
5385 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5386 ///                    attribute-specifier-seq[opt]
5387 ///         direct-declarator '(' parameter-type-list ')'
5388 ///         direct-declarator '(' identifier-list[opt] ')'
5389 /// [GNU]   direct-declarator '(' parameter-forward-declarations
5390 ///                    parameter-type-list[opt] ')'
5391 /// [C++]   direct-declarator '(' parameter-declaration-clause ')'
5392 ///                    cv-qualifier-seq[opt] exception-specification[opt]
5393 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5394 ///                    attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5395 ///                    ref-qualifier[opt] exception-specification[opt]
5396 /// [C++]   declarator-id
5397 /// [C++11] declarator-id attribute-specifier-seq[opt]
5398 ///
5399 ///       declarator-id: [C++ 8]
5400 ///         '...'[opt] id-expression
5401 ///         '::'[opt] nested-name-specifier[opt] type-name
5402 ///
5403 ///       id-expression: [C++ 5.1]
5404 ///         unqualified-id
5405 ///         qualified-id
5406 ///
5407 ///       unqualified-id: [C++ 5.1]
5408 ///         identifier
5409 ///         operator-function-id
5410 ///         conversion-function-id
5411 ///          '~' class-name
5412 ///         template-id
5413 ///
5414 /// C++17 adds the following, which we also handle here:
5415 ///
5416 ///       simple-declaration:
5417 ///         <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5418 ///
5419 /// Note, any additional constructs added here may need corresponding changes
5420 /// in isConstructorDeclarator.
5421 void Parser::ParseDirectDeclarator(Declarator &D) {
5422   DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
5423
5424   if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
5425     // This might be a C++17 structured binding.
5426     if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5427         D.getCXXScopeSpec().isEmpty())
5428       return ParseDecompositionDeclarator(D);
5429
5430     // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5431     // this context it is a bitfield. Also in range-based for statement colon
5432     // may delimit for-range-declaration.
5433     ColonProtectionRAIIObject X(*this,
5434                                 D.getContext() == Declarator::MemberContext ||
5435                                     (D.getContext() == Declarator::ForContext &&
5436                                      getLangOpts().CPlusPlus11));
5437
5438     // ParseDeclaratorInternal might already have parsed the scope.
5439     if (D.getCXXScopeSpec().isEmpty()) {
5440       bool EnteringContext = D.getContext() == Declarator::FileContext ||
5441                              D.getContext() == Declarator::MemberContext;
5442       ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
5443                                      EnteringContext);
5444     }
5445
5446     if (D.getCXXScopeSpec().isValid()) {
5447       if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5448                                              D.getCXXScopeSpec()))
5449         // Change the declaration context for name lookup, until this function
5450         // is exited (and the declarator has been parsed).
5451         DeclScopeObj.EnterDeclaratorScope();
5452       else if (getObjCDeclContext()) {
5453         // Ensure that we don't interpret the next token as an identifier when
5454         // dealing with declarations in an Objective-C container.
5455         D.SetIdentifier(nullptr, Tok.getLocation());
5456         D.setInvalidType(true);
5457         ConsumeToken();
5458         goto PastIdentifier;
5459       }
5460     }
5461
5462     // C++0x [dcl.fct]p14:
5463     //   There is a syntactic ambiguity when an ellipsis occurs at the end of a
5464     //   parameter-declaration-clause without a preceding comma. In this case,
5465     //   the ellipsis is parsed as part of the abstract-declarator if the type
5466     //   of the parameter either names a template parameter pack that has not
5467     //   been expanded or contains auto; otherwise, it is parsed as part of the
5468     //   parameter-declaration-clause.
5469     if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
5470         !((D.getContext() == Declarator::PrototypeContext ||
5471            D.getContext() == Declarator::LambdaExprParameterContext ||
5472            D.getContext() == Declarator::BlockLiteralContext) &&
5473           NextToken().is(tok::r_paren) &&
5474           !D.hasGroupingParens() &&
5475           !Actions.containsUnexpandedParameterPacks(D) &&
5476           D.getDeclSpec().getTypeSpecType() != TST_auto)) {
5477       SourceLocation EllipsisLoc = ConsumeToken();
5478       if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
5479         // The ellipsis was put in the wrong place. Recover, and explain to
5480         // the user what they should have done.
5481         ParseDeclarator(D);
5482         if (EllipsisLoc.isValid())
5483           DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5484         return;
5485       } else
5486         D.setEllipsisLoc(EllipsisLoc);
5487
5488       // The ellipsis can't be followed by a parenthesized declarator. We
5489       // check for that in ParseParenDeclarator, after we have disambiguated
5490       // the l_paren token.
5491     }
5492
5493     if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5494                     tok::tilde)) {
5495       // We found something that indicates the start of an unqualified-id.
5496       // Parse that unqualified-id.
5497       bool AllowConstructorName;
5498       bool AllowDeductionGuide;
5499       if (D.getDeclSpec().hasTypeSpecifier()) {
5500         AllowConstructorName = false;
5501         AllowDeductionGuide = false;
5502       } else if (D.getCXXScopeSpec().isSet()) {
5503         AllowConstructorName =
5504           (D.getContext() == Declarator::FileContext ||
5505            D.getContext() == Declarator::MemberContext);
5506         AllowDeductionGuide = false;
5507       } else {
5508         AllowConstructorName = (D.getContext() == Declarator::MemberContext);
5509         AllowDeductionGuide = 
5510           (D.getContext() == Declarator::FileContext ||
5511            D.getContext() == Declarator::MemberContext);
5512       }
5513
5514       SourceLocation TemplateKWLoc;
5515       bool HadScope = D.getCXXScopeSpec().isValid();
5516       if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5517                              /*EnteringContext=*/true,
5518                              /*AllowDestructorName=*/true, AllowConstructorName,
5519                              AllowDeductionGuide, nullptr, TemplateKWLoc,
5520                              D.getName()) ||
5521           // Once we're past the identifier, if the scope was bad, mark the
5522           // whole declarator bad.
5523           D.getCXXScopeSpec().isInvalid()) {
5524         D.SetIdentifier(nullptr, Tok.getLocation());
5525         D.setInvalidType(true);
5526       } else {
5527         // ParseUnqualifiedId might have parsed a scope specifier during error
5528         // recovery. If it did so, enter that scope.
5529         if (!HadScope && D.getCXXScopeSpec().isValid() &&
5530             Actions.ShouldEnterDeclaratorScope(getCurScope(),
5531                                                D.getCXXScopeSpec()))
5532           DeclScopeObj.EnterDeclaratorScope();
5533
5534         // Parsed the unqualified-id; update range information and move along.
5535         if (D.getSourceRange().getBegin().isInvalid())
5536           D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5537         D.SetRangeEnd(D.getName().getSourceRange().getEnd());
5538       }
5539       goto PastIdentifier;
5540     }
5541
5542     if (D.getCXXScopeSpec().isNotEmpty()) {
5543       // We have a scope specifier but no following unqualified-id.
5544       Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5545            diag::err_expected_unqualified_id)
5546           << /*C++*/1;
5547       D.SetIdentifier(nullptr, Tok.getLocation());
5548       goto PastIdentifier;
5549     }
5550   } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
5551     assert(!getLangOpts().CPlusPlus &&
5552            "There's a C++-specific check for tok::identifier above");
5553     assert(Tok.getIdentifierInfo() && "Not an identifier?");
5554     D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5555     D.SetRangeEnd(Tok.getLocation());
5556     ConsumeToken();
5557     goto PastIdentifier;
5558   } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5559     // We're not allowed an identifier here, but we got one. Try to figure out
5560     // if the user was trying to attach a name to the type, or whether the name
5561     // is some unrelated trailing syntax.
5562     bool DiagnoseIdentifier = false;
5563     if (D.hasGroupingParens())
5564       // An identifier within parens is unlikely to be intended to be anything
5565       // other than a name being "declared".
5566       DiagnoseIdentifier = true;
5567     else if (D.getContext() == Declarator::TemplateTypeArgContext)
5568       // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5569       DiagnoseIdentifier =
5570           NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
5571     else if (D.getContext() == Declarator::AliasDeclContext ||
5572              D.getContext() == Declarator::AliasTemplateContext)
5573       // The most likely error is that the ';' was forgotten.
5574       DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
5575     else if (D.getContext() == Declarator::TrailingReturnContext &&
5576              !isCXX11VirtSpecifier(Tok))
5577       DiagnoseIdentifier = NextToken().isOneOf(
5578           tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5579     if (DiagnoseIdentifier) {
5580       Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5581         << FixItHint::CreateRemoval(Tok.getLocation());
5582       D.SetIdentifier(nullptr, Tok.getLocation());
5583       ConsumeToken();
5584       goto PastIdentifier;
5585     }
5586   }
5587
5588   if (Tok.is(tok::l_paren)) {
5589     // direct-declarator: '(' declarator ')'
5590     // direct-declarator: '(' attributes declarator ')'
5591     // Example: 'char (*X)'   or 'int (*XX)(void)'
5592     ParseParenDeclarator(D);
5593
5594     // If the declarator was parenthesized, we entered the declarator
5595     // scope when parsing the parenthesized declarator, then exited
5596     // the scope already. Re-enter the scope, if we need to.
5597     if (D.getCXXScopeSpec().isSet()) {
5598       // If there was an error parsing parenthesized declarator, declarator
5599       // scope may have been entered before. Don't do it again.
5600       if (!D.isInvalidType() &&
5601           Actions.ShouldEnterDeclaratorScope(getCurScope(),
5602                                              D.getCXXScopeSpec()))
5603         // Change the declaration context for name lookup, until this function
5604         // is exited (and the declarator has been parsed).
5605         DeclScopeObj.EnterDeclaratorScope();
5606     }
5607   } else if (D.mayOmitIdentifier()) {
5608     // This could be something simple like "int" (in which case the declarator
5609     // portion is empty), if an abstract-declarator is allowed.
5610     D.SetIdentifier(nullptr, Tok.getLocation());
5611
5612     // The grammar for abstract-pack-declarator does not allow grouping parens.
5613     // FIXME: Revisit this once core issue 1488 is resolved.
5614     if (D.hasEllipsis() && D.hasGroupingParens())
5615       Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5616            diag::ext_abstract_pack_declarator_parens);
5617   } else {
5618     if (Tok.getKind() == tok::annot_pragma_parser_crash)
5619       LLVM_BUILTIN_TRAP;
5620     if (Tok.is(tok::l_square))
5621       return ParseMisplacedBracketDeclarator(D);
5622     if (D.getContext() == Declarator::MemberContext) {
5623       // Objective-C++: Detect C++ keywords and try to prevent further errors by
5624       // treating these keyword as valid member names.
5625       if (getLangOpts().ObjC1 && getLangOpts().CPlusPlus &&
5626           Tok.getIdentifierInfo() &&
5627           Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5628         Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5629              diag::err_expected_member_name_or_semi_objcxx_keyword)
5630             << Tok.getIdentifierInfo()
5631             << (D.getDeclSpec().isEmpty() ? SourceRange()
5632                                           : D.getDeclSpec().getSourceRange());
5633         D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5634         D.SetRangeEnd(Tok.getLocation());
5635         ConsumeToken();
5636         goto PastIdentifier;
5637       }
5638       Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5639            diag::err_expected_member_name_or_semi)
5640           << (D.getDeclSpec().isEmpty() ? SourceRange()
5641                                         : D.getDeclSpec().getSourceRange());
5642     } else if (getLangOpts().CPlusPlus) {
5643       if (Tok.isOneOf(tok::period, tok::arrow))
5644         Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
5645       else {
5646         SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5647         if (Tok.isAtStartOfLine() && Loc.isValid())
5648           Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5649               << getLangOpts().CPlusPlus;
5650         else
5651           Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5652                diag::err_expected_unqualified_id)
5653               << getLangOpts().CPlusPlus;
5654       }
5655     } else {
5656       Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5657            diag::err_expected_either)
5658           << tok::identifier << tok::l_paren;
5659     }
5660     D.SetIdentifier(nullptr, Tok.getLocation());
5661     D.setInvalidType(true);
5662   }
5663
5664  PastIdentifier:
5665   assert(D.isPastIdentifier() &&
5666          "Haven't past the location of the identifier yet?");
5667
5668   // Don't parse attributes unless we have parsed an unparenthesized name.
5669   if (D.hasName() && !D.getNumTypeObjects())
5670     MaybeParseCXX11Attributes(D);
5671
5672   while (1) {
5673     if (Tok.is(tok::l_paren)) {
5674       // Enter function-declaration scope, limiting any declarators to the
5675       // function prototype scope, including parameter declarators.
5676       ParseScope PrototypeScope(this,
5677                                 Scope::FunctionPrototypeScope|Scope::DeclScope|
5678                                 (D.isFunctionDeclaratorAFunctionDeclaration()
5679                                    ? Scope::FunctionDeclarationScope : 0));
5680
5681       // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5682       // In such a case, check if we actually have a function declarator; if it
5683       // is not, the declarator has been fully parsed.
5684       bool IsAmbiguous = false;
5685       if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5686         // The name of the declarator, if any, is tentatively declared within
5687         // a possible direct initializer.
5688         TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5689         bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5690         TentativelyDeclaredIdentifiers.pop_back();
5691         if (!IsFunctionDecl)
5692           break;
5693       }
5694       ParsedAttributes attrs(AttrFactory);
5695       BalancedDelimiterTracker T(*this, tok::l_paren);
5696       T.consumeOpen();
5697       ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
5698       PrototypeScope.Exit();
5699     } else if (Tok.is(tok::l_square)) {
5700       ParseBracketDeclarator(D);
5701     } else {
5702       break;
5703     }
5704   }
5705 }
5706
5707 void Parser::ParseDecompositionDeclarator(Declarator &D) {
5708   assert(Tok.is(tok::l_square));
5709
5710   // If this doesn't look like a structured binding, maybe it's a misplaced
5711   // array declarator.
5712   // FIXME: Consume the l_square first so we don't need extra lookahead for
5713   // this.
5714   if (!(NextToken().is(tok::identifier) &&
5715         GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5716       !(NextToken().is(tok::r_square) &&
5717         GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5718     return ParseMisplacedBracketDeclarator(D);
5719
5720   BalancedDelimiterTracker T(*this, tok::l_square);
5721   T.consumeOpen();
5722
5723   SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5724   while (Tok.isNot(tok::r_square)) {
5725     if (!Bindings.empty()) {
5726       if (Tok.is(tok::comma))
5727         ConsumeToken();
5728       else {
5729         if (Tok.is(tok::identifier)) {
5730           SourceLocation EndLoc = getEndOfPreviousToken();
5731           Diag(EndLoc, diag::err_expected)
5732               << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
5733         } else {
5734           Diag(Tok, diag::err_expected_comma_or_rsquare);
5735         }
5736
5737         SkipUntil(tok::r_square, tok::comma, tok::identifier,
5738                   StopAtSemi | StopBeforeMatch);
5739         if (Tok.is(tok::comma))
5740           ConsumeToken();
5741         else if (Tok.isNot(tok::identifier))
5742           break;
5743       }
5744     }
5745
5746     if (Tok.isNot(tok::identifier)) {
5747       Diag(Tok, diag::err_expected) << tok::identifier;
5748       break;
5749     }
5750
5751     Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
5752     ConsumeToken();
5753   }
5754
5755   if (Tok.isNot(tok::r_square))
5756     // We've already diagnosed a problem here.
5757     T.skipToEnd();
5758   else {
5759     // C++17 does not allow the identifier-list in a structured binding
5760     // to be empty.
5761     if (Bindings.empty())
5762       Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
5763
5764     T.consumeClose();
5765   }
5766
5767   return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
5768                                     T.getCloseLocation());
5769 }
5770
5771 /// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
5772 /// only called before the identifier, so these are most likely just grouping
5773 /// parens for precedence.  If we find that these are actually function
5774 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5775 ///
5776 ///       direct-declarator:
5777 ///         '(' declarator ')'
5778 /// [GNU]   '(' attributes declarator ')'
5779 ///         direct-declarator '(' parameter-type-list ')'
5780 ///         direct-declarator '(' identifier-list[opt] ')'
5781 /// [GNU]   direct-declarator '(' parameter-forward-declarations
5782 ///                    parameter-type-list[opt] ')'
5783 ///
5784 void Parser::ParseParenDeclarator(Declarator &D) {
5785   BalancedDelimiterTracker T(*this, tok::l_paren);
5786   T.consumeOpen();
5787
5788   assert(!D.isPastIdentifier() && "Should be called before passing identifier");
5789
5790   // Eat any attributes before we look at whether this is a grouping or function
5791   // declarator paren.  If this is a grouping paren, the attribute applies to
5792   // the type being built up, for example:
5793   //     int (__attribute__(()) *x)(long y)
5794   // If this ends up not being a grouping paren, the attribute applies to the
5795   // first argument, for example:
5796   //     int (__attribute__(()) int x)
5797   // In either case, we need to eat any attributes to be able to determine what
5798   // sort of paren this is.
5799   //
5800   ParsedAttributes attrs(AttrFactory);
5801   bool RequiresArg = false;
5802   if (Tok.is(tok::kw___attribute)) {
5803     ParseGNUAttributes(attrs);
5804
5805     // We require that the argument list (if this is a non-grouping paren) be
5806     // present even if the attribute list was empty.
5807     RequiresArg = true;
5808   }
5809
5810   // Eat any Microsoft extensions.
5811   ParseMicrosoftTypeAttributes(attrs);
5812
5813   // Eat any Borland extensions.
5814   if  (Tok.is(tok::kw___pascal))
5815     ParseBorlandTypeAttributes(attrs);
5816
5817   // If we haven't past the identifier yet (or where the identifier would be
5818   // stored, if this is an abstract declarator), then this is probably just
5819   // grouping parens. However, if this could be an abstract-declarator, then
5820   // this could also be the start of function arguments (consider 'void()').
5821   bool isGrouping;
5822
5823   if (!D.mayOmitIdentifier()) {
5824     // If this can't be an abstract-declarator, this *must* be a grouping
5825     // paren, because we haven't seen the identifier yet.
5826     isGrouping = true;
5827   } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
5828              (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
5829               NextToken().is(tok::r_paren)) || // C++ int(...)
5830              isDeclarationSpecifier() ||       // 'int(int)' is a function.
5831              isCXX11AttributeSpecifier()) {    // 'int([[]]int)' is a function.
5832     // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
5833     // considered to be a type, not a K&R identifier-list.
5834     isGrouping = false;
5835   } else {
5836     // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
5837     isGrouping = true;
5838   }
5839
5840   // If this is a grouping paren, handle:
5841   // direct-declarator: '(' declarator ')'
5842   // direct-declarator: '(' attributes declarator ')'
5843   if (isGrouping) {
5844     SourceLocation EllipsisLoc = D.getEllipsisLoc();
5845     D.setEllipsisLoc(SourceLocation());
5846
5847     bool hadGroupingParens = D.hasGroupingParens();
5848     D.setGroupingParens(true);
5849     ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5850     // Match the ')'.
5851     T.consumeClose();
5852     D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
5853                                             T.getCloseLocation()),
5854                   attrs, T.getCloseLocation());
5855
5856     D.setGroupingParens(hadGroupingParens);
5857
5858     // An ellipsis cannot be placed outside parentheses.
5859     if (EllipsisLoc.isValid())
5860       DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5861
5862     return;
5863   }
5864
5865   // Okay, if this wasn't a grouping paren, it must be the start of a function
5866   // argument list.  Recognize that this declarator will never have an
5867   // identifier (and remember where it would have been), then call into
5868   // ParseFunctionDeclarator to handle of argument list.
5869   D.SetIdentifier(nullptr, Tok.getLocation());
5870
5871   // Enter function-declaration scope, limiting any declarators to the
5872   // function prototype scope, including parameter declarators.
5873   ParseScope PrototypeScope(this,
5874                             Scope::FunctionPrototypeScope | Scope::DeclScope |
5875                             (D.isFunctionDeclaratorAFunctionDeclaration()
5876                                ? Scope::FunctionDeclarationScope : 0));
5877   ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
5878   PrototypeScope.Exit();
5879 }
5880
5881 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
5882 /// declarator D up to a paren, which indicates that we are parsing function
5883 /// arguments.
5884 ///
5885 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
5886 /// immediately after the open paren - they should be considered to be the
5887 /// first argument of a parameter.
5888 ///
5889 /// If RequiresArg is true, then the first argument of the function is required
5890 /// to be present and required to not be an identifier list.
5891 ///
5892 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
5893 /// (C++11) ref-qualifier[opt], exception-specification[opt],
5894 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
5895 ///
5896 /// [C++11] exception-specification:
5897 ///           dynamic-exception-specification
5898 ///           noexcept-specification
5899 ///
5900 void Parser::ParseFunctionDeclarator(Declarator &D,
5901                                      ParsedAttributes &FirstArgAttrs,
5902                                      BalancedDelimiterTracker &Tracker,
5903                                      bool IsAmbiguous,
5904                                      bool RequiresArg) {
5905   assert(getCurScope()->isFunctionPrototypeScope() &&
5906          "Should call from a Function scope");
5907   // lparen is already consumed!
5908   assert(D.isPastIdentifier() && "Should not call before identifier!");
5909
5910   // This should be true when the function has typed arguments.
5911   // Otherwise, it is treated as a K&R-style function.
5912   bool HasProto = false;
5913   // Build up an array of information about the parsed arguments.
5914   SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
5915   // Remember where we see an ellipsis, if any.
5916   SourceLocation EllipsisLoc;
5917
5918   DeclSpec DS(AttrFactory);
5919   bool RefQualifierIsLValueRef = true;
5920   SourceLocation RefQualifierLoc;
5921   SourceLocation ConstQualifierLoc;
5922   SourceLocation VolatileQualifierLoc;
5923   SourceLocation RestrictQualifierLoc;
5924   ExceptionSpecificationType ESpecType = EST_None;
5925   SourceRange ESpecRange;
5926   SmallVector<ParsedType, 2> DynamicExceptions;
5927   SmallVector<SourceRange, 2> DynamicExceptionRanges;
5928   ExprResult NoexceptExpr;
5929   CachedTokens *ExceptionSpecTokens = nullptr;
5930   ParsedAttributes FnAttrs(AttrFactory);
5931   TypeResult TrailingReturnType;
5932
5933   /* LocalEndLoc is the end location for the local FunctionTypeLoc.
5934      EndLoc is the end location for the function declarator.
5935      They differ for trailing return types. */
5936   SourceLocation StartLoc, LocalEndLoc, EndLoc;
5937   SourceLocation LParenLoc, RParenLoc;
5938   LParenLoc = Tracker.getOpenLocation();
5939   StartLoc = LParenLoc;
5940
5941   if (isFunctionDeclaratorIdentifierList()) {
5942     if (RequiresArg)
5943       Diag(Tok, diag::err_argument_required_after_attribute);
5944
5945     ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
5946
5947     Tracker.consumeClose();
5948     RParenLoc = Tracker.getCloseLocation();
5949     LocalEndLoc = RParenLoc;
5950     EndLoc = RParenLoc;
5951   } else {
5952     if (Tok.isNot(tok::r_paren))
5953       ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, 
5954                                       EllipsisLoc);
5955     else if (RequiresArg)
5956       Diag(Tok, diag::err_argument_required_after_attribute);
5957
5958     HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
5959
5960     // If we have the closing ')', eat it.
5961     Tracker.consumeClose();
5962     RParenLoc = Tracker.getCloseLocation();
5963     LocalEndLoc = RParenLoc;
5964     EndLoc = RParenLoc;
5965
5966     if (getLangOpts().CPlusPlus) {
5967       // FIXME: Accept these components in any order, and produce fixits to
5968       // correct the order if the user gets it wrong. Ideally we should deal
5969       // with the pure-specifier in the same way.
5970
5971       // Parse cv-qualifier-seq[opt].
5972       ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
5973                                 /*AtomicAllowed*/ false,
5974                                 /*IdentifierRequired=*/false,
5975                                 llvm::function_ref<void()>([&]() {
5976                                   Actions.CodeCompleteFunctionQualifiers(DS, D);
5977                                 }));
5978       if (!DS.getSourceRange().getEnd().isInvalid()) {
5979         EndLoc = DS.getSourceRange().getEnd();
5980         ConstQualifierLoc = DS.getConstSpecLoc();
5981         VolatileQualifierLoc = DS.getVolatileSpecLoc();
5982         RestrictQualifierLoc = DS.getRestrictSpecLoc();
5983       }
5984
5985       // Parse ref-qualifier[opt].
5986       if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
5987         EndLoc = RefQualifierLoc;
5988
5989       // C++11 [expr.prim.general]p3:
5990       //   If a declaration declares a member function or member function
5991       //   template of a class X, the expression this is a prvalue of type
5992       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5993       //   and the end of the function-definition, member-declarator, or
5994       //   declarator.
5995       // FIXME: currently, "static" case isn't handled correctly.
5996       bool IsCXX11MemberFunction =
5997         getLangOpts().CPlusPlus11 &&
5998         D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5999         (D.getContext() == Declarator::MemberContext
6000          ? !D.getDeclSpec().isFriendSpecified()
6001          : D.getContext() == Declarator::FileContext &&
6002            D.getCXXScopeSpec().isValid() &&
6003            Actions.CurContext->isRecord());
6004       Sema::CXXThisScopeRAII ThisScope(Actions,
6005                                dyn_cast<CXXRecordDecl>(Actions.CurContext),
6006                                DS.getTypeQualifiers() |
6007                                (D.getDeclSpec().isConstexprSpecified() &&
6008                                 !getLangOpts().CPlusPlus14
6009                                   ? Qualifiers::Const : 0),
6010                                IsCXX11MemberFunction);
6011
6012       // Parse exception-specification[opt].
6013       bool Delayed = D.isFirstDeclarationOfMember() &&
6014                      D.isFunctionDeclaratorAFunctionDeclaration();
6015       if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6016           GetLookAheadToken(0).is(tok::kw_noexcept) &&
6017           GetLookAheadToken(1).is(tok::l_paren) &&
6018           GetLookAheadToken(2).is(tok::kw_noexcept) &&
6019           GetLookAheadToken(3).is(tok::l_paren) &&
6020           GetLookAheadToken(4).is(tok::identifier) &&
6021           GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6022         // HACK: We've got an exception-specification
6023         //   noexcept(noexcept(swap(...)))
6024         // or
6025         //   noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6026         // on a 'swap' member function. This is a libstdc++ bug; the lookup
6027         // for 'swap' will only find the function we're currently declaring,
6028         // whereas it expects to find a non-member swap through ADL. Turn off
6029         // delayed parsing to give it a chance to find what it expects.
6030         Delayed = false;
6031       }
6032       ESpecType = tryParseExceptionSpecification(Delayed,
6033                                                  ESpecRange,
6034                                                  DynamicExceptions,
6035                                                  DynamicExceptionRanges,
6036                                                  NoexceptExpr,
6037                                                  ExceptionSpecTokens);
6038       if (ESpecType != EST_None)
6039         EndLoc = ESpecRange.getEnd();
6040
6041       // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6042       // after the exception-specification.
6043       MaybeParseCXX11Attributes(FnAttrs);
6044
6045       // Parse trailing-return-type[opt].
6046       LocalEndLoc = EndLoc;
6047       if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
6048         Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
6049         if (D.getDeclSpec().getTypeSpecType() == TST_auto)
6050           StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
6051         LocalEndLoc = Tok.getLocation();
6052         SourceRange Range;
6053         TrailingReturnType = ParseTrailingReturnType(Range);
6054         EndLoc = Range.getEnd();
6055       }
6056     }
6057   }
6058
6059   // Collect non-parameter declarations from the prototype if this is a function
6060   // declaration. They will be moved into the scope of the function. Only do
6061   // this in C and not C++, where the decls will continue to live in the
6062   // surrounding context.
6063   SmallVector<NamedDecl *, 0> DeclsInPrototype;
6064   if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6065       !getLangOpts().CPlusPlus) {
6066     for (Decl *D : getCurScope()->decls()) {
6067       NamedDecl *ND = dyn_cast<NamedDecl>(D);
6068       if (!ND || isa<ParmVarDecl>(ND))
6069         continue;
6070       DeclsInPrototype.push_back(ND);
6071     }
6072   }
6073
6074   // Remember that we parsed a function type, and remember the attributes.
6075   D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
6076                                              IsAmbiguous,
6077                                              LParenLoc,
6078                                              ParamInfo.data(), ParamInfo.size(),
6079                                              EllipsisLoc, RParenLoc,
6080                                              DS.getTypeQualifiers(),
6081                                              RefQualifierIsLValueRef,
6082                                              RefQualifierLoc, ConstQualifierLoc,
6083                                              VolatileQualifierLoc,
6084                                              RestrictQualifierLoc,
6085                                              /*MutableLoc=*/SourceLocation(),
6086                                              ESpecType, ESpecRange,
6087                                              DynamicExceptions.data(),
6088                                              DynamicExceptionRanges.data(),
6089                                              DynamicExceptions.size(),
6090                                              NoexceptExpr.isUsable() ?
6091                                                NoexceptExpr.get() : nullptr,
6092                                              ExceptionSpecTokens,
6093                                              DeclsInPrototype,
6094                                              StartLoc, LocalEndLoc, D,
6095                                              TrailingReturnType),
6096                 FnAttrs, EndLoc);
6097 }
6098
6099 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6100 /// true if a ref-qualifier is found.
6101 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6102                                SourceLocation &RefQualifierLoc) {
6103   if (Tok.isOneOf(tok::amp, tok::ampamp)) {
6104     Diag(Tok, getLangOpts().CPlusPlus11 ?
6105          diag::warn_cxx98_compat_ref_qualifier :
6106          diag::ext_ref_qualifier);
6107
6108     RefQualifierIsLValueRef = Tok.is(tok::amp);
6109     RefQualifierLoc = ConsumeToken();
6110     return true;
6111   }
6112   return false;
6113 }
6114
6115 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
6116 /// identifier list form for a K&R-style function:  void foo(a,b,c)
6117 ///
6118 /// Note that identifier-lists are only allowed for normal declarators, not for
6119 /// abstract-declarators.
6120 bool Parser::isFunctionDeclaratorIdentifierList() {
6121   return !getLangOpts().CPlusPlus
6122          && Tok.is(tok::identifier)
6123          && !TryAltiVecVectorToken()
6124          // K&R identifier lists can't have typedefs as identifiers, per C99
6125          // 6.7.5.3p11.
6126          && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6127          // Identifier lists follow a really simple grammar: the identifiers can
6128          // be followed *only* by a ", identifier" or ")".  However, K&R
6129          // identifier lists are really rare in the brave new modern world, and
6130          // it is very common for someone to typo a type in a non-K&R style
6131          // list.  If we are presented with something like: "void foo(intptr x,
6132          // float y)", we don't want to start parsing the function declarator as
6133          // though it is a K&R style declarator just because intptr is an
6134          // invalid type.
6135          //
6136          // To handle this, we check to see if the token after the first
6137          // identifier is a "," or ")".  Only then do we parse it as an
6138          // identifier list.
6139          && (!Tok.is(tok::eof) &&
6140              (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
6141 }
6142
6143 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6144 /// we found a K&R-style identifier list instead of a typed parameter list.
6145 ///
6146 /// After returning, ParamInfo will hold the parsed parameters.
6147 ///
6148 ///       identifier-list: [C99 6.7.5]
6149 ///         identifier
6150 ///         identifier-list ',' identifier
6151 ///
6152 void Parser::ParseFunctionDeclaratorIdentifierList(
6153        Declarator &D,
6154        SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
6155   // If there was no identifier specified for the declarator, either we are in
6156   // an abstract-declarator, or we are in a parameter declarator which was found
6157   // to be abstract.  In abstract-declarators, identifier lists are not valid:
6158   // diagnose this.
6159   if (!D.getIdentifier())
6160     Diag(Tok, diag::ext_ident_list_in_param);
6161
6162   // Maintain an efficient lookup of params we have seen so far.
6163   llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6164
6165   do {
6166     // If this isn't an identifier, report the error and skip until ')'.
6167     if (Tok.isNot(tok::identifier)) {
6168       Diag(Tok, diag::err_expected) << tok::identifier;
6169       SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
6170       // Forget we parsed anything.
6171       ParamInfo.clear();
6172       return;
6173     }
6174
6175     IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6176
6177     // Reject 'typedef int y; int test(x, y)', but continue parsing.
6178     if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6179       Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6180
6181     // Verify that the argument identifier has not already been mentioned.
6182     if (!ParamsSoFar.insert(ParmII).second) {
6183       Diag(Tok, diag::err_param_redefinition) << ParmII;
6184     } else {
6185       // Remember this identifier in ParamInfo.
6186       ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6187                                                      Tok.getLocation(),
6188                                                      nullptr));
6189     }
6190
6191     // Eat the identifier.
6192     ConsumeToken();
6193     // The list continues if we see a comma.
6194   } while (TryConsumeToken(tok::comma));
6195 }
6196
6197 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6198 /// after the opening parenthesis. This function will not parse a K&R-style
6199 /// identifier list.
6200 ///
6201 /// D is the declarator being parsed.  If FirstArgAttrs is non-null, then the
6202 /// caller parsed those arguments immediately after the open paren - they should
6203 /// be considered to be part of the first parameter.
6204 ///
6205 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6206 /// be the location of the ellipsis, if any was parsed.
6207 ///
6208 ///       parameter-type-list: [C99 6.7.5]
6209 ///         parameter-list
6210 ///         parameter-list ',' '...'
6211 /// [C++]   parameter-list '...'
6212 ///
6213 ///       parameter-list: [C99 6.7.5]
6214 ///         parameter-declaration
6215 ///         parameter-list ',' parameter-declaration
6216 ///
6217 ///       parameter-declaration: [C99 6.7.5]
6218 ///         declaration-specifiers declarator
6219 /// [C++]   declaration-specifiers declarator '=' assignment-expression
6220 /// [C++11]                                       initializer-clause
6221 /// [GNU]   declaration-specifiers declarator attributes
6222 ///         declaration-specifiers abstract-declarator[opt]
6223 /// [C++]   declaration-specifiers abstract-declarator[opt]
6224 ///           '=' assignment-expression
6225 /// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
6226 /// [C++11] attribute-specifier-seq parameter-declaration
6227 ///
6228 void Parser::ParseParameterDeclarationClause(
6229        Declarator &D,
6230        ParsedAttributes &FirstArgAttrs,
6231        SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
6232        SourceLocation &EllipsisLoc) {
6233   do {
6234     // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6235     // before deciding this was a parameter-declaration-clause.
6236     if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
6237       break;
6238
6239     // Parse the declaration-specifiers.
6240     // Just use the ParsingDeclaration "scope" of the declarator.
6241     DeclSpec DS(AttrFactory);
6242
6243     // Parse any C++11 attributes.
6244     MaybeParseCXX11Attributes(DS.getAttributes());
6245
6246     // Skip any Microsoft attributes before a param.
6247     MaybeParseMicrosoftAttributes(DS.getAttributes());
6248
6249     SourceLocation DSStart = Tok.getLocation();
6250
6251     // If the caller parsed attributes for the first argument, add them now.
6252     // Take them so that we only apply the attributes to the first parameter.
6253     // FIXME: If we can leave the attributes in the token stream somehow, we can
6254     // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6255     // too much hassle.
6256     DS.takeAttributesFrom(FirstArgAttrs);
6257
6258     ParseDeclarationSpecifiers(DS);
6259
6260
6261     // Parse the declarator.  This is "PrototypeContext" or 
6262     // "LambdaExprParameterContext", because we must accept either 
6263     // 'declarator' or 'abstract-declarator' here.
6264     Declarator ParmDeclarator(DS, 
6265               D.getContext() == Declarator::LambdaExprContext ?
6266                                   Declarator::LambdaExprParameterContext : 
6267                                                 Declarator::PrototypeContext);
6268     ParseDeclarator(ParmDeclarator);
6269
6270     // Parse GNU attributes, if present.
6271     MaybeParseGNUAttributes(ParmDeclarator);
6272
6273     // Remember this parsed parameter in ParamInfo.
6274     IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
6275
6276     // DefArgToks is used when the parsing of default arguments needs
6277     // to be delayed.
6278     std::unique_ptr<CachedTokens> DefArgToks;
6279
6280     // If no parameter was specified, verify that *something* was specified,
6281     // otherwise we have a missing type and identifier.
6282     if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
6283         ParmDeclarator.getNumTypeObjects() == 0) {
6284       // Completely missing, emit error.
6285       Diag(DSStart, diag::err_missing_param);
6286     } else {
6287       // Otherwise, we have something.  Add it and let semantic analysis try
6288       // to grok it and add the result to the ParamInfo we are building.
6289
6290       // Last chance to recover from a misplaced ellipsis in an attempted
6291       // parameter pack declaration.
6292       if (Tok.is(tok::ellipsis) &&
6293           (NextToken().isNot(tok::r_paren) ||
6294            (!ParmDeclarator.getEllipsisLoc().isValid() &&
6295             !Actions.isUnexpandedParameterPackPermitted())) &&
6296           Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6297         DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6298
6299       // Inform the actions module about the parameter declarator, so it gets
6300       // added to the current scope.
6301       Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
6302       // Parse the default argument, if any. We parse the default
6303       // arguments in all dialects; the semantic analysis in
6304       // ActOnParamDefaultArgument will reject the default argument in
6305       // C.
6306       if (Tok.is(tok::equal)) {
6307         SourceLocation EqualLoc = Tok.getLocation();
6308
6309         // Parse the default argument
6310         if (D.getContext() == Declarator::MemberContext) {
6311           // If we're inside a class definition, cache the tokens
6312           // corresponding to the default argument. We'll actually parse
6313           // them when we see the end of the class definition.
6314           DefArgToks.reset(new CachedTokens);
6315
6316           SourceLocation ArgStartLoc = NextToken().getLocation();
6317           if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
6318             DefArgToks.reset();
6319             Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6320           } else {
6321             Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
6322                                                       ArgStartLoc);
6323           }
6324         } else {
6325           // Consume the '='.
6326           ConsumeToken();
6327
6328           // The argument isn't actually potentially evaluated unless it is
6329           // used.
6330           EnterExpressionEvaluationContext Eval(
6331               Actions,
6332               Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6333               Param);
6334
6335           ExprResult DefArgResult;
6336           if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
6337             Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
6338             DefArgResult = ParseBraceInitializer();
6339           } else
6340             DefArgResult = ParseAssignmentExpression();
6341           DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
6342           if (DefArgResult.isInvalid()) {
6343             Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6344             SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
6345           } else {
6346             // Inform the actions module about the default argument
6347             Actions.ActOnParamDefaultArgument(Param, EqualLoc,
6348                                               DefArgResult.get());
6349           }
6350         }
6351       }
6352
6353       ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6354                                           ParmDeclarator.getIdentifierLoc(), 
6355                                           Param, std::move(DefArgToks)));
6356     }
6357
6358     if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6359       if (!getLangOpts().CPlusPlus) {
6360         // We have ellipsis without a preceding ',', which is ill-formed
6361         // in C. Complain and provide the fix.
6362         Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6363             << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6364       } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6365                  Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6366         // It looks like this was supposed to be a parameter pack. Warn and
6367         // point out where the ellipsis should have gone.
6368         SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6369         Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6370           << ParmEllipsis.isValid() << ParmEllipsis;
6371         if (ParmEllipsis.isValid()) {
6372           Diag(ParmEllipsis,
6373                diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6374         } else {
6375           Diag(ParmDeclarator.getIdentifierLoc(),
6376                diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6377             << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6378                                           "...")
6379             << !ParmDeclarator.hasName();
6380         }
6381         Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
6382           << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6383       }
6384
6385       // We can't have any more parameters after an ellipsis.
6386       break;
6387     }
6388
6389     // If the next token is a comma, consume it and keep reading arguments.
6390   } while (TryConsumeToken(tok::comma));
6391 }
6392
6393 /// [C90]   direct-declarator '[' constant-expression[opt] ']'
6394 /// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6395 /// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6396 /// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6397 /// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
6398 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
6399 ///                           attribute-specifier-seq[opt]
6400 void Parser::ParseBracketDeclarator(Declarator &D) {
6401   if (CheckProhibitedCXX11Attribute())
6402     return;
6403
6404   BalancedDelimiterTracker T(*this, tok::l_square);
6405   T.consumeOpen();
6406
6407   // C array syntax has many features, but by-far the most common is [] and [4].
6408   // This code does a fast path to handle some of the most obvious cases.
6409   if (Tok.getKind() == tok::r_square) {
6410     T.consumeClose();
6411     ParsedAttributes attrs(AttrFactory);
6412     MaybeParseCXX11Attributes(attrs);
6413
6414     // Remember that we parsed the empty array type.
6415     D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
6416                                             T.getOpenLocation(),
6417                                             T.getCloseLocation()),
6418                   attrs, T.getCloseLocation());
6419     return;
6420   } else if (Tok.getKind() == tok::numeric_constant &&
6421              GetLookAheadToken(1).is(tok::r_square)) {
6422     // [4] is very common.  Parse the numeric constant expression.
6423     ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
6424     ConsumeToken();
6425
6426     T.consumeClose();
6427     ParsedAttributes attrs(AttrFactory);
6428     MaybeParseCXX11Attributes(attrs);
6429
6430     // Remember that we parsed a array type, and remember its features.
6431     D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false,
6432                                             ExprRes.get(),
6433                                             T.getOpenLocation(),
6434                                             T.getCloseLocation()),
6435                   attrs, T.getCloseLocation());
6436     return;
6437   } else if (Tok.getKind() == tok::code_completion) {
6438     Actions.CodeCompleteBracketDeclarator(getCurScope());
6439     return cutOffParsing();
6440   }
6441
6442   // If valid, this location is the position where we read the 'static' keyword.
6443   SourceLocation StaticLoc;
6444   TryConsumeToken(tok::kw_static, StaticLoc);
6445
6446   // If there is a type-qualifier-list, read it now.
6447   // Type qualifiers in an array subscript are a C99 feature.
6448   DeclSpec DS(AttrFactory);
6449   ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
6450
6451   // If we haven't already read 'static', check to see if there is one after the
6452   // type-qualifier-list.
6453   if (!StaticLoc.isValid())
6454     TryConsumeToken(tok::kw_static, StaticLoc);
6455
6456   // Handle "direct-declarator [ type-qual-list[opt] * ]".
6457   bool isStar = false;
6458   ExprResult NumElements;
6459
6460   // Handle the case where we have '[*]' as the array size.  However, a leading
6461   // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
6462   // the token after the star is a ']'.  Since stars in arrays are
6463   // infrequent, use of lookahead is not costly here.
6464   if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
6465     ConsumeToken();  // Eat the '*'.
6466
6467     if (StaticLoc.isValid()) {
6468       Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
6469       StaticLoc = SourceLocation();  // Drop the static.
6470     }
6471     isStar = true;
6472   } else if (Tok.isNot(tok::r_square)) {
6473     // Note, in C89, this production uses the constant-expr production instead
6474     // of assignment-expr.  The only difference is that assignment-expr allows
6475     // things like '=' and '*='.  Sema rejects these in C89 mode because they
6476     // are not i-c-e's, so we don't need to distinguish between the two here.
6477
6478     // Parse the constant-expression or assignment-expression now (depending
6479     // on dialect).
6480     if (getLangOpts().CPlusPlus) {
6481       NumElements = ParseConstantExpression();
6482     } else {
6483       EnterExpressionEvaluationContext Unevaluated(
6484           Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6485       NumElements =
6486           Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
6487     }
6488   } else {
6489     if (StaticLoc.isValid()) {
6490       Diag(StaticLoc, diag::err_unspecified_size_with_static);
6491       StaticLoc = SourceLocation();  // Drop the static.
6492     }
6493   }
6494
6495   // If there was an error parsing the assignment-expression, recover.
6496   if (NumElements.isInvalid()) {
6497     D.setInvalidType(true);
6498     // If the expression was invalid, skip it.
6499     SkipUntil(tok::r_square, StopAtSemi);
6500     return;
6501   }
6502
6503   T.consumeClose();
6504
6505   MaybeParseCXX11Attributes(DS.getAttributes());
6506
6507   // Remember that we parsed a array type, and remember its features.
6508   D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
6509                                           StaticLoc.isValid(), isStar,
6510                                           NumElements.get(),
6511                                           T.getOpenLocation(),
6512                                           T.getCloseLocation()),
6513                 DS.getAttributes(), T.getCloseLocation());
6514 }
6515
6516 /// Diagnose brackets before an identifier.
6517 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6518   assert(Tok.is(tok::l_square) && "Missing opening bracket");
6519   assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6520
6521   SourceLocation StartBracketLoc = Tok.getLocation();
6522   Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6523
6524   while (Tok.is(tok::l_square)) {
6525     ParseBracketDeclarator(TempDeclarator);
6526   }
6527
6528   // Stuff the location of the start of the brackets into the Declarator.
6529   // The diagnostics from ParseDirectDeclarator will make more sense if
6530   // they use this location instead.
6531   if (Tok.is(tok::semi))
6532     D.getName().EndLocation = StartBracketLoc;
6533
6534   SourceLocation SuggestParenLoc = Tok.getLocation();
6535
6536   // Now that the brackets are removed, try parsing the declarator again.
6537   ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6538
6539   // Something went wrong parsing the brackets, in which case,
6540   // ParseBracketDeclarator has emitted an error, and we don't need to emit
6541   // one here.
6542   if (TempDeclarator.getNumTypeObjects() == 0)
6543     return;
6544
6545   // Determine if parens will need to be suggested in the diagnostic.
6546   bool NeedParens = false;
6547   if (D.getNumTypeObjects() != 0) {
6548     switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6549     case DeclaratorChunk::Pointer:
6550     case DeclaratorChunk::Reference:
6551     case DeclaratorChunk::BlockPointer:
6552     case DeclaratorChunk::MemberPointer:
6553     case DeclaratorChunk::Pipe:
6554       NeedParens = true;
6555       break;
6556     case DeclaratorChunk::Array:
6557     case DeclaratorChunk::Function:
6558     case DeclaratorChunk::Paren:
6559       break;
6560     }
6561   }
6562
6563   if (NeedParens) {
6564     // Create a DeclaratorChunk for the inserted parens.
6565     ParsedAttributes attrs(AttrFactory);
6566     SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6567     D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), attrs,
6568                   SourceLocation());
6569   }
6570
6571   // Adding back the bracket info to the end of the Declarator.
6572   for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6573     const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
6574     ParsedAttributes attrs(AttrFactory);
6575     attrs.set(Chunk.Common.AttrList);
6576     D.AddTypeInfo(Chunk, attrs, SourceLocation());
6577   }
6578
6579   // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6580   // If parentheses are required, always suggest them.
6581   if (!D.getIdentifier() && !NeedParens)
6582     return;
6583
6584   SourceLocation EndBracketLoc = TempDeclarator.getLocEnd();
6585
6586   // Generate the move bracket error message.
6587   SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
6588   SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6589
6590   if (NeedParens) {
6591     Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6592         << getLangOpts().CPlusPlus
6593         << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6594         << FixItHint::CreateInsertion(EndLoc, ")")
6595         << FixItHint::CreateInsertionFromRange(
6596                EndLoc, CharSourceRange(BracketRange, true))
6597         << FixItHint::CreateRemoval(BracketRange);
6598   } else {
6599     Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6600         << getLangOpts().CPlusPlus
6601         << FixItHint::CreateInsertionFromRange(
6602                EndLoc, CharSourceRange(BracketRange, true))
6603         << FixItHint::CreateRemoval(BracketRange);
6604   }
6605 }
6606
6607 /// [GNU]   typeof-specifier:
6608 ///           typeof ( expressions )
6609 ///           typeof ( type-name )
6610 /// [GNU/C++] typeof unary-expression
6611 ///
6612 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
6613   assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
6614   Token OpTok = Tok;
6615   SourceLocation StartLoc = ConsumeToken();
6616
6617   const bool hasParens = Tok.is(tok::l_paren);
6618
6619   EnterExpressionEvaluationContext Unevaluated(
6620       Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6621       Sema::ReuseLambdaContextDecl);
6622
6623   bool isCastExpr;
6624   ParsedType CastTy;
6625   SourceRange CastRange;
6626   ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6627       ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
6628   if (hasParens)
6629     DS.setTypeofParensRange(CastRange);
6630
6631   if (CastRange.getEnd().isInvalid())
6632     // FIXME: Not accurate, the range gets one token more than it should.
6633     DS.SetRangeEnd(Tok.getLocation());
6634   else
6635     DS.SetRangeEnd(CastRange.getEnd());
6636
6637   if (isCastExpr) {
6638     if (!CastTy) {
6639       DS.SetTypeSpecError();
6640       return;
6641     }
6642
6643     const char *PrevSpec = nullptr;
6644     unsigned DiagID;
6645     // Check for duplicate type specifiers (e.g. "int typeof(int)").
6646     if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
6647                            DiagID, CastTy,
6648                            Actions.getASTContext().getPrintingPolicy()))
6649       Diag(StartLoc, DiagID) << PrevSpec;
6650     return;
6651   }
6652
6653   // If we get here, the operand to the typeof was an expression.
6654   if (Operand.isInvalid()) {
6655     DS.SetTypeSpecError();
6656     return;
6657   }
6658
6659   // We might need to transform the operand if it is potentially evaluated.
6660   Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6661   if (Operand.isInvalid()) {
6662     DS.SetTypeSpecError();
6663     return;
6664   }
6665
6666   const char *PrevSpec = nullptr;
6667   unsigned DiagID;
6668   // Check for duplicate type specifiers (e.g. "int typeof(int)").
6669   if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
6670                          DiagID, Operand.get(),
6671                          Actions.getASTContext().getPrintingPolicy()))
6672     Diag(StartLoc, DiagID) << PrevSpec;
6673 }
6674
6675 /// [C11]   atomic-specifier:
6676 ///           _Atomic ( type-name )
6677 ///
6678 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
6679   assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6680          "Not an atomic specifier");
6681
6682   SourceLocation StartLoc = ConsumeToken();
6683   BalancedDelimiterTracker T(*this, tok::l_paren);
6684   if (T.consumeOpen())
6685     return;
6686
6687   TypeResult Result = ParseTypeName();
6688   if (Result.isInvalid()) {
6689     SkipUntil(tok::r_paren, StopAtSemi);
6690     return;
6691   }
6692
6693   // Match the ')'
6694   T.consumeClose();
6695
6696   if (T.getCloseLocation().isInvalid())
6697     return;
6698
6699   DS.setTypeofParensRange(T.getRange());
6700   DS.SetRangeEnd(T.getCloseLocation());
6701
6702   const char *PrevSpec = nullptr;
6703   unsigned DiagID;
6704   if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
6705                          DiagID, Result.get(),
6706                          Actions.getASTContext().getPrintingPolicy()))
6707     Diag(StartLoc, DiagID) << PrevSpec;
6708 }
6709
6710 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6711 /// from TryAltiVecVectorToken.
6712 bool Parser::TryAltiVecVectorTokenOutOfLine() {
6713   Token Next = NextToken();
6714   switch (Next.getKind()) {
6715   default: return false;
6716   case tok::kw_short:
6717   case tok::kw_long:
6718   case tok::kw_signed:
6719   case tok::kw_unsigned:
6720   case tok::kw_void:
6721   case tok::kw_char:
6722   case tok::kw_int:
6723   case tok::kw_float:
6724   case tok::kw_double:
6725   case tok::kw_bool:
6726   case tok::kw___bool:
6727   case tok::kw___pixel:
6728     Tok.setKind(tok::kw___vector);
6729     return true;
6730   case tok::identifier:
6731     if (Next.getIdentifierInfo() == Ident_pixel) {
6732       Tok.setKind(tok::kw___vector);
6733       return true;
6734     }
6735     if (Next.getIdentifierInfo() == Ident_bool) {
6736       Tok.setKind(tok::kw___vector);
6737       return true;
6738     }
6739     return false;
6740   }
6741 }
6742
6743 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6744                                       const char *&PrevSpec, unsigned &DiagID,
6745                                       bool &isInvalid) {
6746   const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
6747   if (Tok.getIdentifierInfo() == Ident_vector) {
6748     Token Next = NextToken();
6749     switch (Next.getKind()) {
6750     case tok::kw_short:
6751     case tok::kw_long:
6752     case tok::kw_signed:
6753     case tok::kw_unsigned:
6754     case tok::kw_void:
6755     case tok::kw_char:
6756     case tok::kw_int:
6757     case tok::kw_float:
6758     case tok::kw_double:
6759     case tok::kw_bool:
6760     case tok::kw___bool:
6761     case tok::kw___pixel:
6762       isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
6763       return true;
6764     case tok::identifier:
6765       if (Next.getIdentifierInfo() == Ident_pixel) {
6766         isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6767         return true;
6768       }
6769       if (Next.getIdentifierInfo() == Ident_bool) {
6770         isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6771         return true;
6772       }
6773       break;
6774     default:
6775       break;
6776     }
6777   } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
6778              DS.isTypeAltiVecVector()) {
6779     isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
6780     return true;
6781   } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
6782              DS.isTypeAltiVecVector()) {
6783     isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
6784     return true;
6785   }
6786   return false;
6787 }