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