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