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