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