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