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