1 //===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the Declaration portions of the Parser interfaces.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Parse/Parser.h"
14 #include "clang/Parse/RAIIObjectsForParser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/PrettyDeclStackTrace.h"
18 #include "clang/Basic/AddressSpaces.h"
19 #include "clang/Basic/Attributes.h"
20 #include "clang/Basic/CharInfo.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Parse/ParseDiagnostic.h"
23 #include "clang/Sema/Lookup.h"
24 #include "clang/Sema/ParsedTemplate.h"
25 #include "clang/Sema/Scope.h"
26 #include "llvm/ADT/Optional.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringSwitch.h"
31 using namespace clang;
33 //===----------------------------------------------------------------------===//
34 // C99 6.7: Declarations.
35 //===----------------------------------------------------------------------===//
38 /// type-name: [C99 6.7.6]
39 /// specifier-qualifier-list abstract-declarator[opt]
41 /// Called type-id in C++.
42 TypeResult Parser::ParseTypeName(SourceRange *Range,
43 DeclaratorContext Context,
46 ParsedAttributes *Attrs) {
47 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
48 if (DSC == DeclSpecContext::DSC_normal)
49 DSC = DeclSpecContext::DSC_type_specifier;
51 // Parse the common declaration-specifiers piece.
52 DeclSpec DS(AttrFactory);
54 DS.addAttributes(*Attrs);
55 ParseSpecifierQualifierList(DS, AS, DSC);
57 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
59 // Parse the abstract-declarator, if present.
60 Declarator DeclaratorInfo(DS, Context);
61 ParseDeclarator(DeclaratorInfo);
63 *Range = DeclaratorInfo.getSourceRange();
65 if (DeclaratorInfo.isInvalidType())
68 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
71 /// Normalizes an attribute name by dropping prefixed and suffixed __.
72 static StringRef normalizeAttrName(StringRef Name) {
73 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
74 return Name.drop_front(2).drop_back(2);
78 /// isAttributeLateParsed - Return true if the attribute has arguments that
79 /// require late parsing.
80 static bool isAttributeLateParsed(const IdentifierInfo &II) {
81 #define CLANG_ATTR_LATE_PARSED_LIST
82 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
83 #include "clang/Parse/AttrParserStringSwitches.inc"
85 #undef CLANG_ATTR_LATE_PARSED_LIST
88 /// Check if the a start and end source location expand to the same macro.
89 static bool FindLocsWithCommonFileID(Preprocessor &PP, SourceLocation StartLoc,
90 SourceLocation EndLoc) {
91 if (!StartLoc.isMacroID() || !EndLoc.isMacroID())
94 SourceManager &SM = PP.getSourceManager();
95 if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
98 bool AttrStartIsInMacro =
99 Lexer::isAtStartOfMacroExpansion(StartLoc, SM, PP.getLangOpts());
100 bool AttrEndIsInMacro =
101 Lexer::isAtEndOfMacroExpansion(EndLoc, SM, PP.getLangOpts());
102 return AttrStartIsInMacro && AttrEndIsInMacro;
105 /// ParseGNUAttributes - Parse a non-empty attributes list.
107 /// [GNU] attributes:
109 /// attributes attribute
112 /// '__attribute__' '(' '(' attribute-list ')' ')'
114 /// [GNU] attribute-list:
116 /// attribute_list ',' attrib
121 /// attrib-name '(' identifier ')'
122 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
123 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
125 /// [GNU] attrib-name:
131 /// Whether an attribute takes an 'identifier' is determined by the
132 /// attrib-name. GCC's behavior here is not worth imitating:
134 /// * In C mode, if the attribute argument list starts with an identifier
135 /// followed by a ',' or an ')', and the identifier doesn't resolve to
136 /// a type, it is parsed as an identifier. If the attribute actually
137 /// wanted an expression, it's out of luck (but it turns out that no
138 /// attributes work that way, because C constant expressions are very
140 /// * In C++ mode, if the attribute argument list starts with an identifier,
141 /// and the attribute *wants* an identifier, it is parsed as an identifier.
142 /// At block scope, any additional tokens between the identifier and the
143 /// ',' or ')' are ignored, otherwise they produce a parse error.
145 /// We follow the C++ model, but don't allow junk after the identifier.
146 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
147 SourceLocation *endLoc,
148 LateParsedAttrList *LateAttrs,
150 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
152 while (Tok.is(tok::kw___attribute)) {
153 SourceLocation AttrTokLoc = ConsumeToken();
154 unsigned OldNumAttrs = attrs.size();
155 unsigned OldNumLateAttrs = LateAttrs ? LateAttrs->size() : 0;
157 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
159 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
162 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
163 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
166 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
168 // Eat preceeding commas to allow __attribute__((,,,foo))
169 while (TryConsumeToken(tok::comma))
172 // Expect an identifier or declaration specifier (const, int, etc.)
173 if (Tok.isAnnotation())
175 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
179 SourceLocation AttrNameLoc = ConsumeToken();
181 if (Tok.isNot(tok::l_paren)) {
182 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
187 // Handle "parameterized" attributes
188 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
189 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
190 SourceLocation(), ParsedAttr::AS_GNU, D);
194 // Handle attributes with arguments that require late parsing.
195 LateParsedAttribute *LA =
196 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
197 LateAttrs->push_back(LA);
199 // Attributes in a class are parsed at the end of the class, along
200 // with other late-parsed declarations.
201 if (!ClassStack.empty() && !LateAttrs->parseSoon())
202 getCurrentClass().LateParsedDeclarations.push_back(LA);
204 // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
205 // recursively consumes balanced parens.
206 LA->Toks.push_back(Tok);
208 // Consume everything up to and including the matching right parens.
209 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
213 Eof.setLocation(Tok.getLocation());
214 LA->Toks.push_back(Eof);
215 } while (Tok.is(tok::comma));
217 if (ExpectAndConsume(tok::r_paren))
218 SkipUntil(tok::r_paren, StopAtSemi);
219 SourceLocation Loc = Tok.getLocation();
220 if (ExpectAndConsume(tok::r_paren))
221 SkipUntil(tok::r_paren, StopAtSemi);
225 // If this was declared in a macro, attach the macro IdentifierInfo to the
227 auto &SM = PP.getSourceManager();
228 if (!SM.isWrittenInBuiltinFile(SM.getSpellingLoc(AttrTokLoc)) &&
229 FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)) {
230 CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
231 StringRef FoundName =
232 Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
233 IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
235 for (unsigned i = OldNumAttrs; i < attrs.size(); ++i)
236 attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
239 for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); ++i)
240 (*LateAttrs)[i]->MacroII = MacroII;
246 /// Determine whether the given attribute has an identifier argument.
247 static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
248 #define CLANG_ATTR_IDENTIFIER_ARG_LIST
249 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
250 #include "clang/Parse/AttrParserStringSwitches.inc"
252 #undef CLANG_ATTR_IDENTIFIER_ARG_LIST
255 /// Determine whether the given attribute has a variadic identifier argument.
256 static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II) {
257 #define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
258 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
259 #include "clang/Parse/AttrParserStringSwitches.inc"
261 #undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
264 /// Determine whether the given attribute treats kw_this as an identifier.
265 static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II) {
266 #define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
267 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
268 #include "clang/Parse/AttrParserStringSwitches.inc"
270 #undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
273 /// Determine whether the given attribute parses a type argument.
274 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
275 #define CLANG_ATTR_TYPE_ARG_LIST
276 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
277 #include "clang/Parse/AttrParserStringSwitches.inc"
279 #undef CLANG_ATTR_TYPE_ARG_LIST
282 /// Determine whether the given attribute requires parsing its arguments
283 /// in an unevaluated context or not.
284 static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
285 #define CLANG_ATTR_ARG_CONTEXT_LIST
286 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
287 #include "clang/Parse/AttrParserStringSwitches.inc"
289 #undef CLANG_ATTR_ARG_CONTEXT_LIST
292 IdentifierLoc *Parser::ParseIdentifierLoc() {
293 assert(Tok.is(tok::identifier) && "expected an identifier");
294 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
296 Tok.getIdentifierInfo());
301 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
302 SourceLocation AttrNameLoc,
303 ParsedAttributes &Attrs,
304 SourceLocation *EndLoc,
305 IdentifierInfo *ScopeName,
306 SourceLocation ScopeLoc,
307 ParsedAttr::Syntax Syntax) {
308 BalancedDelimiterTracker Parens(*this, tok::l_paren);
309 Parens.consumeOpen();
312 if (Tok.isNot(tok::r_paren))
315 if (Parens.consumeClose())
322 Attrs.addNewTypeAttr(&AttrName,
323 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
324 ScopeName, ScopeLoc, T.get(), Syntax);
326 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
327 ScopeName, ScopeLoc, nullptr, 0, Syntax);
330 unsigned Parser::ParseAttributeArgsCommon(
331 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
332 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
333 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
334 // Ignore the left paren location for now.
337 bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
338 bool AttributeIsTypeArgAttr = attributeIsTypeArgAttr(*AttrName);
340 // Interpret "kw_this" as an identifier if the attributed requests it.
341 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
342 Tok.setKind(tok::identifier);
345 if (Tok.is(tok::identifier)) {
346 // If this attribute wants an 'identifier' argument, make it so.
347 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName) ||
348 attributeHasVariadicIdentifierArg(*AttrName);
349 ParsedAttr::Kind AttrKind =
350 ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
352 // If we don't know how to parse this attribute, but this is the only
353 // token in this argument, assume it's meant to be an identifier.
354 if (AttrKind == ParsedAttr::UnknownAttribute ||
355 AttrKind == ParsedAttr::IgnoredAttribute) {
356 const Token &Next = NextToken();
357 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
361 ArgExprs.push_back(ParseIdentifierLoc());
364 ParsedType TheParsedType;
365 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
367 if (!ArgExprs.empty())
370 // Parse the non-empty comma-separated list of expressions.
372 // Interpret "kw_this" as an identifier if the attributed requests it.
373 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
374 Tok.setKind(tok::identifier);
377 if (AttributeIsTypeArgAttr) {
378 TypeResult T = ParseTypeName();
380 SkipUntil(tok::r_paren, StopAtSemi);
384 TheParsedType = T.get();
385 break; // FIXME: Multiple type arguments are not implemented.
386 } else if (Tok.is(tok::identifier) &&
387 attributeHasVariadicIdentifierArg(*AttrName)) {
388 ArgExprs.push_back(ParseIdentifierLoc());
390 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
391 EnterExpressionEvaluationContext Unevaluated(
393 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
394 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
397 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
398 if (ArgExpr.isInvalid()) {
399 SkipUntil(tok::r_paren, StopAtSemi);
402 ArgExprs.push_back(ArgExpr.get());
404 // Eat the comma, move to the next argument
405 } while (TryConsumeToken(tok::comma));
408 SourceLocation RParen = Tok.getLocation();
409 if (!ExpectAndConsume(tok::r_paren)) {
410 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
412 if (AttributeIsTypeArgAttr && !TheParsedType.get().isNull()) {
413 Attrs.addNewTypeAttr(AttrName, SourceRange(AttrNameLoc, RParen),
414 ScopeName, ScopeLoc, TheParsedType, Syntax);
416 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
417 ArgExprs.data(), ArgExprs.size(), Syntax);
424 return static_cast<unsigned>(ArgExprs.size() + !TheParsedType.get().isNull());
427 /// Parse the arguments to a parameterized GNU attribute or
428 /// a C++11 attribute in "gnu" namespace.
429 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
430 SourceLocation AttrNameLoc,
431 ParsedAttributes &Attrs,
432 SourceLocation *EndLoc,
433 IdentifierInfo *ScopeName,
434 SourceLocation ScopeLoc,
435 ParsedAttr::Syntax Syntax,
438 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
440 ParsedAttr::Kind AttrKind =
441 ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
443 if (AttrKind == ParsedAttr::AT_Availability) {
444 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
447 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
448 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
449 ScopeName, ScopeLoc, Syntax);
451 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
452 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
453 ScopeName, ScopeLoc, Syntax);
455 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
456 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
457 ScopeName, ScopeLoc, Syntax);
459 } else if (attributeIsTypeArgAttr(*AttrName)) {
460 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
465 // These may refer to the function arguments, but need to be parsed early to
466 // participate in determining whether it's a redeclaration.
467 llvm::Optional<ParseScope> PrototypeScope;
468 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
469 D && D->isFunctionDeclarator()) {
470 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
471 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
472 Scope::FunctionDeclarationScope |
474 for (unsigned i = 0; i != FTI.NumParams; ++i) {
475 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
476 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
480 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
484 unsigned Parser::ParseClangAttributeArgs(
485 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
486 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
487 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
488 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
490 ParsedAttr::Kind AttrKind =
491 ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
495 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
496 ScopeName, ScopeLoc, Syntax);
497 case ParsedAttr::AT_ExternalSourceSymbol:
498 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
499 ScopeName, ScopeLoc, Syntax);
501 case ParsedAttr::AT_Availability:
502 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
505 case ParsedAttr::AT_ObjCBridgeRelated:
506 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
507 ScopeName, ScopeLoc, Syntax);
509 case ParsedAttr::AT_TypeTagForDatatype:
510 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
511 ScopeName, ScopeLoc, Syntax);
514 return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
517 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
518 SourceLocation AttrNameLoc,
519 ParsedAttributes &Attrs) {
520 // If the attribute isn't known, we will not attempt to parse any
522 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
523 getTargetInfo(), getLangOpts())) {
524 // Eat the left paren, then skip to the ending right paren.
526 SkipUntil(tok::r_paren);
530 SourceLocation OpenParenLoc = Tok.getLocation();
532 if (AttrName->getName() == "property") {
533 // The property declspec is more complex in that it can take one or two
534 // assignment expressions as a parameter, but the lhs of the assignment
535 // must be named get or put.
537 BalancedDelimiterTracker T(*this, tok::l_paren);
538 T.expectAndConsume(diag::err_expected_lparen_after,
539 AttrName->getNameStart(), tok::r_paren);
544 AK_Get = 1 // indices into AccessorNames
546 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
547 bool HasInvalidAccessor = false;
549 // Parse the accessor specifications.
551 // Stop if this doesn't look like an accessor spec.
552 if (!Tok.is(tok::identifier)) {
553 // If the user wrote a completely empty list, use a special diagnostic.
554 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
555 AccessorNames[AK_Put] == nullptr &&
556 AccessorNames[AK_Get] == nullptr) {
557 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
561 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
566 SourceLocation KindLoc = Tok.getLocation();
567 StringRef KindStr = Tok.getIdentifierInfo()->getName();
568 if (KindStr == "get") {
570 } else if (KindStr == "put") {
573 // Recover from the common mistake of using 'set' instead of 'put'.
574 } else if (KindStr == "set") {
575 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
576 << FixItHint::CreateReplacement(KindLoc, "put");
579 // Handle the mistake of forgetting the accessor kind by skipping
581 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
582 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
584 HasInvalidAccessor = true;
585 goto next_property_accessor;
587 // Otherwise, complain about the unknown accessor kind.
589 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
590 HasInvalidAccessor = true;
593 // Try to keep parsing unless it doesn't look like an accessor spec.
594 if (!NextToken().is(tok::equal))
598 // Consume the identifier.
602 if (!TryConsumeToken(tok::equal)) {
603 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
608 // Expect the method name.
609 if (!Tok.is(tok::identifier)) {
610 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
614 if (Kind == AK_Invalid) {
615 // Just drop invalid accessors.
616 } else if (AccessorNames[Kind] != nullptr) {
617 // Complain about the repeated accessor, ignore it, and keep parsing.
618 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
620 AccessorNames[Kind] = Tok.getIdentifierInfo();
624 next_property_accessor:
625 // Keep processing accessors until we run out.
626 if (TryConsumeToken(tok::comma))
629 // If we run into the ')', stop without consuming it.
630 if (Tok.is(tok::r_paren))
633 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
637 // Only add the property attribute if it was well-formed.
638 if (!HasInvalidAccessor)
639 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
640 AccessorNames[AK_Get], AccessorNames[AK_Put],
641 ParsedAttr::AS_Declspec);
643 return !HasInvalidAccessor;
647 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
648 SourceLocation(), ParsedAttr::AS_Declspec);
650 // If this attribute's args were parsed, and it was expected to have
651 // arguments but none were provided, emit a diagnostic.
652 if (!Attrs.empty() && Attrs.begin()->getMaxArgs() && !NumArgs) {
653 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
659 /// [MS] decl-specifier:
660 /// __declspec ( extended-decl-modifier-seq )
662 /// [MS] extended-decl-modifier-seq:
663 /// extended-decl-modifier[opt]
664 /// extended-decl-modifier extended-decl-modifier-seq
665 void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
666 SourceLocation *End) {
667 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
668 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
670 while (Tok.is(tok::kw___declspec)) {
672 BalancedDelimiterTracker T(*this, tok::l_paren);
673 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
677 // An empty declspec is perfectly legal and should not warn. Additionally,
678 // you can specify multiple attributes per declspec.
679 while (Tok.isNot(tok::r_paren)) {
680 // Attribute not present.
681 if (TryConsumeToken(tok::comma))
684 // We expect either a well-known identifier or a generic string. Anything
685 // else is a malformed declspec.
686 bool IsString = Tok.getKind() == tok::string_literal;
687 if (!IsString && Tok.getKind() != tok::identifier &&
688 Tok.getKind() != tok::kw_restrict) {
689 Diag(Tok, diag::err_ms_declspec_type);
694 IdentifierInfo *AttrName;
695 SourceLocation AttrNameLoc;
697 SmallString<8> StrBuffer;
698 bool Invalid = false;
699 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
704 AttrName = PP.getIdentifierInfo(Str);
705 AttrNameLoc = ConsumeStringToken();
707 AttrName = Tok.getIdentifierInfo();
708 AttrNameLoc = ConsumeToken();
711 bool AttrHandled = false;
713 // Parse attribute arguments.
714 if (Tok.is(tok::l_paren))
715 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
716 else if (AttrName->getName() == "property")
717 // The property attribute must have an argument list.
718 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
719 << AttrName->getName();
722 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
723 ParsedAttr::AS_Declspec);
727 *End = T.getCloseLocation();
731 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
732 // Treat these like attributes
734 switch (Tok.getKind()) {
735 case tok::kw___fastcall:
736 case tok::kw___stdcall:
737 case tok::kw___thiscall:
738 case tok::kw___regcall:
739 case tok::kw___cdecl:
740 case tok::kw___vectorcall:
741 case tok::kw___ptr64:
743 case tok::kw___ptr32:
745 case tok::kw___uptr: {
746 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
747 SourceLocation AttrNameLoc = ConsumeToken();
748 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
749 ParsedAttr::AS_Keyword);
758 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
759 SourceLocation StartLoc = Tok.getLocation();
760 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
762 if (EndLoc.isValid()) {
763 SourceRange Range(StartLoc, EndLoc);
764 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
768 SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
769 SourceLocation EndLoc;
772 switch (Tok.getKind()) {
774 case tok::kw_volatile:
775 case tok::kw___fastcall:
776 case tok::kw___stdcall:
777 case tok::kw___thiscall:
778 case tok::kw___cdecl:
779 case tok::kw___vectorcall:
780 case tok::kw___ptr32:
781 case tok::kw___ptr64:
783 case tok::kw___unaligned:
786 EndLoc = ConsumeToken();
794 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
795 // Treat these like attributes
796 while (Tok.is(tok::kw___pascal)) {
797 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
798 SourceLocation AttrNameLoc = ConsumeToken();
799 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
800 ParsedAttr::AS_Keyword);
804 void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
805 // Treat these like attributes
806 while (Tok.is(tok::kw___kernel)) {
807 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
808 SourceLocation AttrNameLoc = ConsumeToken();
809 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
810 ParsedAttr::AS_Keyword);
814 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
815 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
816 SourceLocation AttrNameLoc = Tok.getLocation();
817 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
818 ParsedAttr::AS_Keyword);
821 void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
822 // Treat these like attributes, even though they're type specifiers.
824 switch (Tok.getKind()) {
825 case tok::kw__Nonnull:
826 case tok::kw__Nullable:
827 case tok::kw__Null_unspecified: {
828 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
829 SourceLocation AttrNameLoc = ConsumeToken();
830 if (!getLangOpts().ObjC)
831 Diag(AttrNameLoc, diag::ext_nullability)
833 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
834 ParsedAttr::AS_Keyword);
843 static bool VersionNumberSeparator(const char Separator) {
844 return (Separator == '.' || Separator == '_');
847 /// Parse a version number.
851 /// simple-integer '.' simple-integer
852 /// simple-integer '_' simple-integer
853 /// simple-integer '.' simple-integer '.' simple-integer
854 /// simple-integer '_' simple-integer '_' simple-integer
855 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
856 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
858 if (!Tok.is(tok::numeric_constant)) {
859 Diag(Tok, diag::err_expected_version);
860 SkipUntil(tok::comma, tok::r_paren,
861 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
862 return VersionTuple();
865 // Parse the major (and possibly minor and subminor) versions, which
866 // are stored in the numeric constant. We utilize a quirk of the
867 // lexer, which is that it handles something like 1.2.3 as a single
868 // numeric constant, rather than two separate tokens.
869 SmallString<512> Buffer;
870 Buffer.resize(Tok.getLength()+1);
871 const char *ThisTokBegin = &Buffer[0];
873 // Get the spelling of the token, which eliminates trigraphs, etc.
874 bool Invalid = false;
875 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
877 return VersionTuple();
879 // Parse the major version.
880 unsigned AfterMajor = 0;
882 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
883 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
887 if (AfterMajor == 0) {
888 Diag(Tok, diag::err_expected_version);
889 SkipUntil(tok::comma, tok::r_paren,
890 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
891 return VersionTuple();
894 if (AfterMajor == ActualLength) {
897 // We only had a single version component.
899 Diag(Tok, diag::err_zero_version);
900 return VersionTuple();
903 return VersionTuple(Major);
906 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
907 if (!VersionNumberSeparator(AfterMajorSeparator)
908 || (AfterMajor + 1 == ActualLength)) {
909 Diag(Tok, diag::err_expected_version);
910 SkipUntil(tok::comma, tok::r_paren,
911 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
912 return VersionTuple();
915 // Parse the minor version.
916 unsigned AfterMinor = AfterMajor + 1;
918 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
919 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
923 if (AfterMinor == ActualLength) {
926 // We had major.minor.
927 if (Major == 0 && Minor == 0) {
928 Diag(Tok, diag::err_zero_version);
929 return VersionTuple();
932 return VersionTuple(Major, Minor);
935 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
936 // If what follows is not a '.' or '_', we have a problem.
937 if (!VersionNumberSeparator(AfterMinorSeparator)) {
938 Diag(Tok, diag::err_expected_version);
939 SkipUntil(tok::comma, tok::r_paren,
940 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
941 return VersionTuple();
944 // Warn if separators, be it '.' or '_', do not match.
945 if (AfterMajorSeparator != AfterMinorSeparator)
946 Diag(Tok, diag::warn_expected_consistent_version_separator);
948 // Parse the subminor version.
949 unsigned AfterSubminor = AfterMinor + 1;
950 unsigned Subminor = 0;
951 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
952 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
956 if (AfterSubminor != ActualLength) {
957 Diag(Tok, diag::err_expected_version);
958 SkipUntil(tok::comma, tok::r_paren,
959 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
960 return VersionTuple();
963 return VersionTuple(Major, Minor, Subminor);
966 /// Parse the contents of the "availability" attribute.
968 /// availability-attribute:
969 /// 'availability' '(' platform ',' opt-strict version-arg-list,
970 /// opt-replacement, opt-message')'
978 /// version-arg-list:
980 /// version-arg ',' version-arg-list
983 /// 'introduced' '=' version
984 /// 'deprecated' '=' version
985 /// 'obsoleted' = version
988 /// 'replacement' '=' <string>
990 /// 'message' '=' <string>
991 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
992 SourceLocation AvailabilityLoc,
993 ParsedAttributes &attrs,
994 SourceLocation *endLoc,
995 IdentifierInfo *ScopeName,
996 SourceLocation ScopeLoc,
997 ParsedAttr::Syntax Syntax) {
998 enum { Introduced, Deprecated, Obsoleted, Unknown };
999 AvailabilityChange Changes[Unknown];
1000 ExprResult MessageExpr, ReplacementExpr;
1003 BalancedDelimiterTracker T(*this, tok::l_paren);
1004 if (T.consumeOpen()) {
1005 Diag(Tok, diag::err_expected) << tok::l_paren;
1009 // Parse the platform name.
1010 if (Tok.isNot(tok::identifier)) {
1011 Diag(Tok, diag::err_availability_expected_platform);
1012 SkipUntil(tok::r_paren, StopAtSemi);
1015 IdentifierLoc *Platform = ParseIdentifierLoc();
1016 if (const IdentifierInfo *const Ident = Platform->Ident) {
1017 // Canonicalize platform name from "macosx" to "macos".
1018 if (Ident->getName() == "macosx")
1019 Platform->Ident = PP.getIdentifierInfo("macos");
1020 // Canonicalize platform name from "macosx_app_extension" to
1021 // "macos_app_extension".
1022 else if (Ident->getName() == "macosx_app_extension")
1023 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1025 Platform->Ident = PP.getIdentifierInfo(
1026 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1029 // Parse the ',' following the platform name.
1030 if (ExpectAndConsume(tok::comma)) {
1031 SkipUntil(tok::r_paren, StopAtSemi);
1035 // If we haven't grabbed the pointers for the identifiers
1036 // "introduced", "deprecated", and "obsoleted", do so now.
1037 if (!Ident_introduced) {
1038 Ident_introduced = PP.getIdentifierInfo("introduced");
1039 Ident_deprecated = PP.getIdentifierInfo("deprecated");
1040 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
1041 Ident_unavailable = PP.getIdentifierInfo("unavailable");
1042 Ident_message = PP.getIdentifierInfo("message");
1043 Ident_strict = PP.getIdentifierInfo("strict");
1044 Ident_replacement = PP.getIdentifierInfo("replacement");
1047 // Parse the optional "strict", the optional "replacement" and the set of
1048 // introductions/deprecations/removals.
1049 SourceLocation UnavailableLoc, StrictLoc;
1051 if (Tok.isNot(tok::identifier)) {
1052 Diag(Tok, diag::err_availability_expected_change);
1053 SkipUntil(tok::r_paren, StopAtSemi);
1056 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1057 SourceLocation KeywordLoc = ConsumeToken();
1059 if (Keyword == Ident_strict) {
1060 if (StrictLoc.isValid()) {
1061 Diag(KeywordLoc, diag::err_availability_redundant)
1062 << Keyword << SourceRange(StrictLoc);
1064 StrictLoc = KeywordLoc;
1068 if (Keyword == Ident_unavailable) {
1069 if (UnavailableLoc.isValid()) {
1070 Diag(KeywordLoc, diag::err_availability_redundant)
1071 << Keyword << SourceRange(UnavailableLoc);
1073 UnavailableLoc = KeywordLoc;
1077 if (Keyword == Ident_deprecated && Platform->Ident &&
1078 Platform->Ident->isStr("swift")) {
1079 // For swift, we deprecate for all versions.
1080 if (Changes[Deprecated].KeywordLoc.isValid()) {
1081 Diag(KeywordLoc, diag::err_availability_redundant)
1083 << SourceRange(Changes[Deprecated].KeywordLoc);
1086 Changes[Deprecated].KeywordLoc = KeywordLoc;
1087 // Use a fake version here.
1088 Changes[Deprecated].Version = VersionTuple(1);
1092 if (Tok.isNot(tok::equal)) {
1093 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1094 SkipUntil(tok::r_paren, StopAtSemi);
1098 if (Keyword == Ident_message || Keyword == Ident_replacement) {
1099 if (Tok.isNot(tok::string_literal)) {
1100 Diag(Tok, diag::err_expected_string_literal)
1101 << /*Source='availability attribute'*/2;
1102 SkipUntil(tok::r_paren, StopAtSemi);
1105 if (Keyword == Ident_message)
1106 MessageExpr = ParseStringLiteralExpression();
1108 ReplacementExpr = ParseStringLiteralExpression();
1109 // Also reject wide string literals.
1110 if (StringLiteral *MessageStringLiteral =
1111 cast_or_null<StringLiteral>(MessageExpr.get())) {
1112 if (MessageStringLiteral->getCharByteWidth() != 1) {
1113 Diag(MessageStringLiteral->getSourceRange().getBegin(),
1114 diag::err_expected_string_literal)
1115 << /*Source='availability attribute'*/ 2;
1116 SkipUntil(tok::r_paren, StopAtSemi);
1120 if (Keyword == Ident_message)
1126 // Special handling of 'NA' only when applied to introduced or
1128 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1129 Tok.is(tok::identifier)) {
1130 IdentifierInfo *NA = Tok.getIdentifierInfo();
1131 if (NA->getName() == "NA") {
1133 if (Keyword == Ident_introduced)
1134 UnavailableLoc = KeywordLoc;
1139 SourceRange VersionRange;
1140 VersionTuple Version = ParseVersionTuple(VersionRange);
1142 if (Version.empty()) {
1143 SkipUntil(tok::r_paren, StopAtSemi);
1148 if (Keyword == Ident_introduced)
1150 else if (Keyword == Ident_deprecated)
1152 else if (Keyword == Ident_obsoleted)
1157 if (Index < Unknown) {
1158 if (!Changes[Index].KeywordLoc.isInvalid()) {
1159 Diag(KeywordLoc, diag::err_availability_redundant)
1161 << SourceRange(Changes[Index].KeywordLoc,
1162 Changes[Index].VersionRange.getEnd());
1165 Changes[Index].KeywordLoc = KeywordLoc;
1166 Changes[Index].Version = Version;
1167 Changes[Index].VersionRange = VersionRange;
1169 Diag(KeywordLoc, diag::err_availability_unknown_change)
1170 << Keyword << VersionRange;
1173 } while (TryConsumeToken(tok::comma));
1176 if (T.consumeClose())
1180 *endLoc = T.getCloseLocation();
1182 // The 'unavailable' availability cannot be combined with any other
1183 // availability changes. Make sure that hasn't happened.
1184 if (UnavailableLoc.isValid()) {
1185 bool Complained = false;
1186 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1187 if (Changes[Index].KeywordLoc.isValid()) {
1189 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1190 << SourceRange(Changes[Index].KeywordLoc,
1191 Changes[Index].VersionRange.getEnd());
1195 // Clear out the availability.
1196 Changes[Index] = AvailabilityChange();
1201 // Record this attribute
1202 attrs.addNew(&Availability,
1203 SourceRange(AvailabilityLoc, T.getCloseLocation()),
1204 ScopeName, ScopeLoc,
1206 Changes[Introduced],
1207 Changes[Deprecated],
1209 UnavailableLoc, MessageExpr.get(),
1210 Syntax, StrictLoc, ReplacementExpr.get());
1213 /// Parse the contents of the "external_source_symbol" attribute.
1215 /// external-source-symbol-attribute:
1216 /// 'external_source_symbol' '(' keyword-arg-list ')'
1218 /// keyword-arg-list:
1220 /// keyword-arg ',' keyword-arg-list
1223 /// 'language' '=' <string>
1224 /// 'defined_in' '=' <string>
1225 /// 'generated_declaration'
1226 void Parser::ParseExternalSourceSymbolAttribute(
1227 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1228 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1229 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1231 BalancedDelimiterTracker T(*this, tok::l_paren);
1232 if (T.expectAndConsume())
1235 // Initialize the pointers for the keyword identifiers when required.
1236 if (!Ident_language) {
1237 Ident_language = PP.getIdentifierInfo("language");
1238 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1239 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1242 ExprResult Language;
1243 bool HasLanguage = false;
1244 ExprResult DefinedInExpr;
1245 bool HasDefinedIn = false;
1246 IdentifierLoc *GeneratedDeclaration = nullptr;
1248 // Parse the language/defined_in/generated_declaration keywords
1250 if (Tok.isNot(tok::identifier)) {
1251 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1252 SkipUntil(tok::r_paren, StopAtSemi);
1256 SourceLocation KeywordLoc = Tok.getLocation();
1257 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1258 if (Keyword == Ident_generated_declaration) {
1259 if (GeneratedDeclaration) {
1260 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1261 SkipUntil(tok::r_paren, StopAtSemi);
1264 GeneratedDeclaration = ParseIdentifierLoc();
1268 if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1269 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1270 SkipUntil(tok::r_paren, StopAtSemi);
1275 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1276 Keyword->getName())) {
1277 SkipUntil(tok::r_paren, StopAtSemi);
1281 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1282 if (Keyword == Ident_language)
1285 HasDefinedIn = true;
1287 if (Tok.isNot(tok::string_literal)) {
1288 Diag(Tok, diag::err_expected_string_literal)
1289 << /*Source='external_source_symbol attribute'*/ 3
1290 << /*language | source container*/ (Keyword != Ident_language);
1291 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1294 if (Keyword == Ident_language) {
1296 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1298 ParseStringLiteralExpression();
1301 Language = ParseStringLiteralExpression();
1303 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1305 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1307 ParseStringLiteralExpression();
1310 DefinedInExpr = ParseStringLiteralExpression();
1312 } while (TryConsumeToken(tok::comma));
1315 if (T.consumeClose())
1318 *EndLoc = T.getCloseLocation();
1320 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1321 GeneratedDeclaration};
1322 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1323 ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1326 /// Parse the contents of the "objc_bridge_related" attribute.
1327 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1331 /// opt-class_method:
1332 /// Identifier: | <empty>
1334 /// opt-instance_method:
1335 /// Identifier | <empty>
1337 void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1338 SourceLocation ObjCBridgeRelatedLoc,
1339 ParsedAttributes &attrs,
1340 SourceLocation *endLoc,
1341 IdentifierInfo *ScopeName,
1342 SourceLocation ScopeLoc,
1343 ParsedAttr::Syntax Syntax) {
1345 BalancedDelimiterTracker T(*this, tok::l_paren);
1346 if (T.consumeOpen()) {
1347 Diag(Tok, diag::err_expected) << tok::l_paren;
1351 // Parse the related class name.
1352 if (Tok.isNot(tok::identifier)) {
1353 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1354 SkipUntil(tok::r_paren, StopAtSemi);
1357 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1358 if (ExpectAndConsume(tok::comma)) {
1359 SkipUntil(tok::r_paren, StopAtSemi);
1363 // Parse class method name. It's non-optional in the sense that a trailing
1364 // comma is required, but it can be the empty string, and then we record a
1366 IdentifierLoc *ClassMethod = nullptr;
1367 if (Tok.is(tok::identifier)) {
1368 ClassMethod = ParseIdentifierLoc();
1369 if (!TryConsumeToken(tok::colon)) {
1370 Diag(Tok, diag::err_objcbridge_related_selector_name);
1371 SkipUntil(tok::r_paren, StopAtSemi);
1375 if (!TryConsumeToken(tok::comma)) {
1376 if (Tok.is(tok::colon))
1377 Diag(Tok, diag::err_objcbridge_related_selector_name);
1379 Diag(Tok, diag::err_expected) << tok::comma;
1380 SkipUntil(tok::r_paren, StopAtSemi);
1384 // Parse instance method name. Also non-optional but empty string is
1386 IdentifierLoc *InstanceMethod = nullptr;
1387 if (Tok.is(tok::identifier))
1388 InstanceMethod = ParseIdentifierLoc();
1389 else if (Tok.isNot(tok::r_paren)) {
1390 Diag(Tok, diag::err_expected) << tok::r_paren;
1391 SkipUntil(tok::r_paren, StopAtSemi);
1396 if (T.consumeClose())
1400 *endLoc = T.getCloseLocation();
1402 // Record this attribute
1403 attrs.addNew(&ObjCBridgeRelated,
1404 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1405 ScopeName, ScopeLoc,
1412 // Late Parsed Attributes:
1413 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1415 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1417 void Parser::LateParsedClass::ParseLexedAttributes() {
1418 Self->ParseLexedAttributes(*Class);
1421 void Parser::LateParsedAttribute::ParseLexedAttributes() {
1422 Self->ParseLexedAttribute(*this, true, false);
1425 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1426 /// scope appropriately.
1427 void Parser::ParseLexedAttributes(ParsingClass &Class) {
1428 // Deal with templates
1429 // FIXME: Test cases to make sure this does the right thing for templates.
1430 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1431 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1433 if (HasTemplateScope)
1434 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1436 // Set or update the scope flags.
1437 bool AlreadyHasClassScope = Class.TopLevelClass;
1438 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
1439 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1440 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1442 // Enter the scope of nested classes
1443 if (!AlreadyHasClassScope)
1444 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1445 Class.TagOrTemplate);
1446 if (!Class.LateParsedDeclarations.empty()) {
1447 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1448 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1452 if (!AlreadyHasClassScope)
1453 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1454 Class.TagOrTemplate);
1457 /// Parse all attributes in LAs, and attach them to Decl D.
1458 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1459 bool EnterScope, bool OnDefinition) {
1460 assert(LAs.parseSoon() &&
1461 "Attribute list should be marked for immediate parsing.");
1462 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1465 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1471 /// Finish parsing an attribute for which parsing was delayed.
1472 /// This will be called at the end of parsing a class declaration
1473 /// for each LateParsedAttribute. We consume the saved tokens and
1474 /// create an attribute with the arguments filled in. We add this
1475 /// to the Attribute list for the decl.
1476 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1477 bool EnterScope, bool OnDefinition) {
1478 // Create a fake EOF so that attribute parsing won't go off the end of the
1481 AttrEnd.startToken();
1482 AttrEnd.setKind(tok::eof);
1483 AttrEnd.setLocation(Tok.getLocation());
1484 AttrEnd.setEofData(LA.Toks.data());
1485 LA.Toks.push_back(AttrEnd);
1487 // Append the current token at the end of the new token stream so that it
1488 // doesn't get lost.
1489 LA.Toks.push_back(Tok);
1490 PP.EnterTokenStream(LA.Toks, true, /*IsReinject=*/true);
1491 // Consume the previously pushed token.
1492 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1494 ParsedAttributes Attrs(AttrFactory);
1495 SourceLocation endLoc;
1497 if (LA.Decls.size() > 0) {
1498 Decl *D = LA.Decls[0];
1499 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1500 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1502 // Allow 'this' within late-parsed attributes.
1503 Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
1504 ND && ND->isCXXInstanceMember());
1506 if (LA.Decls.size() == 1) {
1507 // If the Decl is templatized, add template parameters to scope.
1508 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1509 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1510 if (HasTemplateScope)
1511 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1513 // If the Decl is on a function, add function parameters to the scope.
1514 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1516 this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope,
1519 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1521 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1522 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
1526 Actions.ActOnExitFunctionContext();
1527 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1529 if (HasTemplateScope) {
1533 // If there are multiple decls, then the decl cannot be within the
1535 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1536 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
1540 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1543 if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
1544 Attrs.begin()->isKnownToGCC())
1545 Diag(Tok, diag::warn_attribute_on_function_definition)
1548 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
1549 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1551 // Due to a parsing error, we either went over the cached tokens or
1552 // there are still cached tokens left, so we skip the leftover tokens.
1553 while (Tok.isNot(tok::eof))
1556 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1560 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1561 SourceLocation AttrNameLoc,
1562 ParsedAttributes &Attrs,
1563 SourceLocation *EndLoc,
1564 IdentifierInfo *ScopeName,
1565 SourceLocation ScopeLoc,
1566 ParsedAttr::Syntax Syntax) {
1567 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1569 BalancedDelimiterTracker T(*this, tok::l_paren);
1572 if (Tok.isNot(tok::identifier)) {
1573 Diag(Tok, diag::err_expected) << tok::identifier;
1577 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1579 if (ExpectAndConsume(tok::comma)) {
1584 SourceRange MatchingCTypeRange;
1585 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1586 if (MatchingCType.isInvalid()) {
1591 bool LayoutCompatible = false;
1592 bool MustBeNull = false;
1593 while (TryConsumeToken(tok::comma)) {
1594 if (Tok.isNot(tok::identifier)) {
1595 Diag(Tok, diag::err_expected) << tok::identifier;
1599 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1600 if (Flag->isStr("layout_compatible"))
1601 LayoutCompatible = true;
1602 else if (Flag->isStr("must_be_null"))
1605 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1609 ConsumeToken(); // consume flag
1612 if (!T.consumeClose()) {
1613 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1614 ArgumentKind, MatchingCType.get(),
1615 LayoutCompatible, MustBeNull, Syntax);
1619 *EndLoc = T.getCloseLocation();
1622 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1623 /// of a C++11 attribute-specifier in a location where an attribute is not
1624 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1627 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1628 /// this doesn't appear to actually be an attribute-specifier, and the caller
1629 /// should try to parse it.
1630 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1631 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1633 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1634 case CAK_NotAttributeSpecifier:
1635 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1638 case CAK_InvalidAttributeSpecifier:
1639 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1642 case CAK_AttributeSpecifier:
1643 // Parse and discard the attributes.
1644 SourceLocation BeginLoc = ConsumeBracket();
1646 SkipUntil(tok::r_square);
1647 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1648 SourceLocation EndLoc = ConsumeBracket();
1649 Diag(BeginLoc, diag::err_attributes_not_allowed)
1650 << SourceRange(BeginLoc, EndLoc);
1653 llvm_unreachable("All cases handled above.");
1656 /// We have found the opening square brackets of a C++11
1657 /// attribute-specifier in a location where an attribute is not permitted, but
1658 /// we know where the attributes ought to be written. Parse them anyway, and
1659 /// provide a fixit moving them to the right place.
1660 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1661 SourceLocation CorrectLocation) {
1662 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1663 Tok.is(tok::kw_alignas));
1665 // Consume the attributes.
1666 SourceLocation Loc = Tok.getLocation();
1667 ParseCXX11Attributes(Attrs);
1668 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1669 // FIXME: use err_attributes_misplaced
1670 Diag(Loc, diag::err_attributes_not_allowed)
1671 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1672 << FixItHint::CreateRemoval(AttrRange);
1675 void Parser::DiagnoseProhibitedAttributes(
1676 const SourceRange &Range, const SourceLocation CorrectLocation) {
1677 if (CorrectLocation.isValid()) {
1678 CharSourceRange AttrRange(Range, true);
1679 Diag(CorrectLocation, diag::err_attributes_misplaced)
1680 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1681 << FixItHint::CreateRemoval(AttrRange);
1683 Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
1686 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1688 for (const ParsedAttr &AL : Attrs) {
1689 if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
1691 if (AL.getKind() == ParsedAttr::UnknownAttribute)
1692 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL;
1694 Diag(AL.getLoc(), DiagID) << AL;
1700 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1701 // applies to var, not the type Foo.
1702 // As an exception to the rule, __declspec(align(...)) before the
1703 // class-key affects the type instead of the variable.
1704 // Also, Microsoft-style [attributes] seem to affect the type instead of the
1706 // This function moves attributes that should apply to the type off DS to Attrs.
1707 void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1709 Sema::TagUseKind TUK) {
1710 if (TUK == Sema::TUK_Reference)
1713 llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
1715 for (ParsedAttr &AL : DS.getAttributes()) {
1716 if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1717 AL.isDeclspecAttribute()) ||
1718 AL.isMicrosoftAttribute())
1719 ToBeMoved.push_back(&AL);
1722 for (ParsedAttr *AL : ToBeMoved) {
1723 DS.getAttributes().remove(AL);
1728 /// ParseDeclaration - Parse a full 'declaration', which consists of
1729 /// declaration-specifiers, some number of declarators, and a semicolon.
1730 /// 'Context' should be a DeclaratorContext value. This returns the
1731 /// location of the semicolon in DeclEnd.
1733 /// declaration: [C99 6.7]
1734 /// block-declaration ->
1735 /// simple-declaration
1737 /// [C++] template-declaration
1738 /// [C++] namespace-definition
1739 /// [C++] using-directive
1740 /// [C++] using-declaration
1741 /// [C++11/C11] static_assert-declaration
1742 /// others... [FIXME]
1744 Parser::DeclGroupPtrTy
1745 Parser::ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
1746 ParsedAttributesWithRange &attrs,
1747 SourceLocation *DeclSpecStart) {
1748 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1749 // Must temporarily exit the objective-c container scope for
1750 // parsing c none objective-c decls.
1751 ObjCDeclContextSwitch ObjCDC(*this);
1753 Decl *SingleDecl = nullptr;
1754 switch (Tok.getKind()) {
1755 case tok::kw_template:
1756 case tok::kw_export:
1757 ProhibitAttributes(attrs);
1758 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
1760 case tok::kw_inline:
1761 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1762 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1763 ProhibitAttributes(attrs);
1764 SourceLocation InlineLoc = ConsumeToken();
1765 return ParseNamespace(Context, DeclEnd, InlineLoc);
1767 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true, nullptr,
1769 case tok::kw_namespace:
1770 ProhibitAttributes(attrs);
1771 return ParseNamespace(Context, DeclEnd);
1773 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1775 case tok::kw_static_assert:
1776 case tok::kw__Static_assert:
1777 ProhibitAttributes(attrs);
1778 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1781 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true, nullptr,
1785 // This routine returns a DeclGroup, if the thing we parsed only contains a
1786 // single decl, convert it now.
1787 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1790 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1791 /// declaration-specifiers init-declarator-list[opt] ';'
1792 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1793 /// init-declarator-list ';'
1794 ///[C90/C++]init-declarator-list ';' [TODO]
1795 /// [OMP] threadprivate-directive
1796 /// [OMP] allocate-directive [TODO]
1798 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1799 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1801 /// If RequireSemi is false, this does not check for a ';' at the end of the
1802 /// declaration. If it is true, it checks for and eats it.
1804 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1805 /// of a simple-declaration. If we find that we are, we also parse the
1806 /// for-range-initializer, and place it here.
1808 /// DeclSpecStart is used when decl-specifiers are parsed before parsing
1809 /// the Declaration. The SourceLocation for this Decl is set to
1810 /// DeclSpecStart if DeclSpecStart is non-null.
1811 Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(
1812 DeclaratorContext Context, SourceLocation &DeclEnd,
1813 ParsedAttributesWithRange &Attrs, bool RequireSemi, ForRangeInit *FRI,
1814 SourceLocation *DeclSpecStart) {
1815 // Parse the common declaration-specifiers piece.
1816 ParsingDeclSpec DS(*this);
1818 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1819 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1821 // If we had a free-standing type definition with a missing semicolon, we
1822 // may get this far before the problem becomes obvious.
1823 if (DS.hasTagDefinition() &&
1824 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1827 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1828 // declaration-specifiers init-declarator-list[opt] ';'
1829 if (Tok.is(tok::semi)) {
1830 ProhibitAttributes(Attrs);
1831 DeclEnd = Tok.getLocation();
1832 if (RequireSemi) ConsumeToken();
1833 RecordDecl *AnonRecord = nullptr;
1834 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1836 DS.complete(TheDecl);
1838 Decl* decls[] = {AnonRecord, TheDecl};
1839 return Actions.BuildDeclaratorGroup(decls);
1841 return Actions.ConvertDeclToDeclGroup(TheDecl);
1845 DS.SetRangeStart(*DeclSpecStart);
1847 DS.takeAttributesFrom(Attrs);
1848 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1851 /// Returns true if this might be the start of a declarator, or a common typo
1852 /// for a declarator.
1853 bool Parser::MightBeDeclarator(DeclaratorContext Context) {
1854 switch (Tok.getKind()) {
1855 case tok::annot_cxxscope:
1856 case tok::annot_template_id:
1858 case tok::code_completion:
1859 case tok::coloncolon:
1861 case tok::kw___attribute:
1862 case tok::kw_operator:
1869 return getLangOpts().CPlusPlus;
1871 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1872 return Context == DeclaratorContext::MemberContext &&
1873 getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
1875 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1876 return Context == DeclaratorContext::MemberContext ||
1877 getLangOpts().CPlusPlus;
1879 case tok::identifier:
1880 switch (NextToken().getKind()) {
1881 case tok::code_completion:
1882 case tok::coloncolon:
1885 case tok::equalequal: // Might be a typo for '='.
1886 case tok::kw_alignas:
1888 case tok::kw___attribute:
1900 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1901 // and in block scope it's probably a label. Inside a class definition,
1902 // this is a bit-field.
1903 return Context == DeclaratorContext::MemberContext ||
1904 (getLangOpts().CPlusPlus &&
1905 Context == DeclaratorContext::FileContext);
1907 case tok::identifier: // Possible virt-specifier.
1908 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1919 /// Skip until we reach something which seems like a sensible place to pick
1920 /// up parsing after a malformed declaration. This will sometimes stop sooner
1921 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1922 void Parser::SkipMalformedDecl() {
1924 switch (Tok.getKind()) {
1926 // Skip until matching }, then stop. We've probably skipped over
1927 // a malformed class or function definition or similar.
1929 SkipUntil(tok::r_brace);
1930 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1931 // This declaration isn't over yet. Keep skipping.
1934 TryConsumeToken(tok::semi);
1939 SkipUntil(tok::r_square);
1944 SkipUntil(tok::r_paren);
1954 case tok::kw_inline:
1955 // 'inline namespace' at the start of a line is almost certainly
1956 // a good place to pick back up parsing, except in an Objective-C
1957 // @interface context.
1958 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1959 (!ParsingInObjCContainer || CurParsedObjCImpl))
1963 case tok::kw_namespace:
1964 // 'namespace' at the start of a line is almost certainly a good
1965 // place to pick back up parsing, except in an Objective-C
1966 // @interface context.
1967 if (Tok.isAtStartOfLine() &&
1968 (!ParsingInObjCContainer || CurParsedObjCImpl))
1973 // @end is very much like } in Objective-C contexts.
1974 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1975 ParsingInObjCContainer)
1981 // - and + probably start new method declarations in Objective-C contexts.
1982 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1987 case tok::annot_module_begin:
1988 case tok::annot_module_end:
1989 case tok::annot_module_include:
2000 /// ParseDeclGroup - Having concluded that this is either a function
2001 /// definition or a group of object declarations, actually parse the
2003 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
2004 DeclaratorContext Context,
2005 SourceLocation *DeclEnd,
2006 ForRangeInit *FRI) {
2007 // Parse the first declarator.
2008 ParsingDeclarator D(*this, DS, Context);
2011 // Bail out if the first declarator didn't seem well-formed.
2012 if (!D.hasName() && !D.mayOmitIdentifier()) {
2013 SkipMalformedDecl();
2017 if (Tok.is(tok::kw_requires))
2018 ParseTrailingRequiresClause(D);
2020 // Save late-parsed attributes for now; they need to be parsed in the
2021 // appropriate function scope after the function Decl has been constructed.
2022 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
2023 LateParsedAttrList LateParsedAttrs(true);
2024 if (D.isFunctionDeclarator()) {
2025 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2027 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
2028 // attribute. If we find the keyword here, tell the user to put it
2029 // at the start instead.
2030 if (Tok.is(tok::kw__Noreturn)) {
2031 SourceLocation Loc = ConsumeToken();
2032 const char *PrevSpec;
2035 // We can offer a fixit if it's valid to mark this function as _Noreturn
2036 // and we don't have any other declarators in this declaration.
2037 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2038 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2039 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
2041 Diag(Loc, diag::err_c11_noreturn_misplaced)
2042 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
2043 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
2048 // Check to see if we have a function *definition* which must have a body.
2049 if (D.isFunctionDeclarator() &&
2050 // Look at the next token to make sure that this isn't a function
2051 // declaration. We have to check this because __attribute__ might be the
2052 // start of a function definition in GCC-extended K&R C.
2053 !isDeclarationAfterDeclarator()) {
2055 // Function definitions are only allowed at file scope and in C++ classes.
2056 // The C++ inline method definition case is handled elsewhere, so we only
2057 // need to handle the file scope definition case.
2058 if (Context == DeclaratorContext::FileContext) {
2059 if (isStartOfFunctionDefinition(D)) {
2060 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2061 Diag(Tok, diag::err_function_declared_typedef);
2063 // Recover by treating the 'typedef' as spurious.
2064 DS.ClearStorageClassSpecs();
2068 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
2069 return Actions.ConvertDeclToDeclGroup(TheDecl);
2072 if (isDeclarationSpecifier()) {
2073 // If there is an invalid declaration specifier right after the
2074 // function prototype, then we must be in a missing semicolon case
2075 // where this isn't actually a body. Just fall through into the code
2076 // that handles it as a prototype, and let the top-level code handle
2077 // the erroneous declspec where it would otherwise expect a comma or
2080 Diag(Tok, diag::err_expected_fn_body);
2081 SkipUntil(tok::semi);
2085 if (Tok.is(tok::l_brace)) {
2086 Diag(Tok, diag::err_function_definition_not_allowed);
2087 SkipMalformedDecl();
2093 if (ParseAsmAttributesAfterDeclarator(D))
2096 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2097 // must parse and analyze the for-range-initializer before the declaration is
2100 // Handle the Objective-C for-in loop variable similarly, although we
2101 // don't need to parse the container in advance.
2102 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2103 bool IsForRangeLoop = false;
2104 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2105 IsForRangeLoop = true;
2106 if (getLangOpts().OpenMP)
2107 Actions.startOpenMPCXXRangeFor();
2108 if (Tok.is(tok::l_brace))
2109 FRI->RangeExpr = ParseBraceInitializer();
2111 FRI->RangeExpr = ParseExpression();
2114 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2115 if (IsForRangeLoop) {
2116 Actions.ActOnCXXForRangeDecl(ThisDecl);
2119 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2120 VD->setObjCForDecl(true);
2122 Actions.FinalizeDeclaration(ThisDecl);
2123 D.complete(ThisDecl);
2124 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2127 SmallVector<Decl *, 8> DeclsInGroup;
2128 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2129 D, ParsedTemplateInfo(), FRI);
2130 if (LateParsedAttrs.size() > 0)
2131 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2132 D.complete(FirstDecl);
2134 DeclsInGroup.push_back(FirstDecl);
2136 bool ExpectSemi = Context != DeclaratorContext::ForContext;
2138 // If we don't have a comma, it is either the end of the list (a ';') or an
2140 SourceLocation CommaLoc;
2141 while (TryConsumeToken(tok::comma, CommaLoc)) {
2142 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2143 // This comma was followed by a line-break and something which can't be
2144 // the start of a declarator. The comma was probably a typo for a
2146 Diag(CommaLoc, diag::err_expected_semi_declaration)
2147 << FixItHint::CreateReplacement(CommaLoc, ";");
2152 // Parse the next declarator.
2154 D.setCommaLoc(CommaLoc);
2156 // Accept attributes in an init-declarator. In the first declarator in a
2157 // declaration, these would be part of the declspec. In subsequent
2158 // declarators, they become part of the declarator itself, so that they
2159 // don't apply to declarators after *this* one. Examples:
2160 // short __attribute__((common)) var; -> declspec
2161 // short var __attribute__((common)); -> declarator
2162 // short x, __attribute__((common)) var; -> declarator
2163 MaybeParseGNUAttributes(D);
2165 // MSVC parses but ignores qualifiers after the comma as an extension.
2166 if (getLangOpts().MicrosoftExt)
2167 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2170 if (!D.isInvalidType()) {
2171 // C++2a [dcl.decl]p1
2173 // declarator initializer[opt]
2174 // declarator requires-clause
2175 if (Tok.is(tok::kw_requires))
2176 ParseTrailingRequiresClause(D);
2177 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2178 D.complete(ThisDecl);
2180 DeclsInGroup.push_back(ThisDecl);
2185 *DeclEnd = Tok.getLocation();
2188 ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
2189 ? diag::err_invalid_token_after_toplevel_declarator
2190 : diag::err_expected_semi_declaration)) {
2191 // Okay, there was no semicolon and one was expected. If we see a
2192 // declaration specifier, just assume it was missing and continue parsing.
2193 // Otherwise things are very confused and we skip to recover.
2194 if (!isDeclarationSpecifier()) {
2195 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2196 TryConsumeToken(tok::semi);
2200 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2203 /// Parse an optional simple-asm-expr and attributes, and attach them to a
2204 /// declarator. Returns true on an error.
2205 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2206 // If a simple-asm-expr is present, parse it.
2207 if (Tok.is(tok::kw_asm)) {
2209 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2210 if (AsmLabel.isInvalid()) {
2211 SkipUntil(tok::semi, StopBeforeMatch);
2215 D.setAsmLabel(AsmLabel.get());
2219 MaybeParseGNUAttributes(D);
2223 /// Parse 'declaration' after parsing 'declaration-specifiers
2224 /// declarator'. This method parses the remainder of the declaration
2225 /// (including any attributes or initializer, among other things) and
2226 /// finalizes the declaration.
2228 /// init-declarator: [C99 6.7]
2230 /// declarator '=' initializer
2231 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2232 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2233 /// [C++] declarator initializer[opt]
2235 /// [C++] initializer:
2236 /// [C++] '=' initializer-clause
2237 /// [C++] '(' expression-list ')'
2238 /// [C++0x] '=' 'default' [TODO]
2239 /// [C++0x] '=' 'delete'
2240 /// [C++0x] braced-init-list
2242 /// According to the standard grammar, =default and =delete are function
2243 /// definitions, but that definitely doesn't fit with the parser here.
2245 Decl *Parser::ParseDeclarationAfterDeclarator(
2246 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2247 if (ParseAsmAttributesAfterDeclarator(D))
2250 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2253 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2254 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2255 // RAII type used to track whether we're inside an initializer.
2256 struct InitializerScopeRAII {
2261 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2262 : P(P), D(D), ThisDecl(ThisDecl) {
2263 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2265 if (D.getCXXScopeSpec().isSet()) {
2267 S = P.getCurScope();
2269 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2272 ~InitializerScopeRAII() { pop(); }
2274 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2276 if (D.getCXXScopeSpec().isSet())
2277 S = P.getCurScope();
2278 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2286 // Inform the current actions module that we just parsed this declarator.
2287 Decl *ThisDecl = nullptr;
2288 switch (TemplateInfo.Kind) {
2289 case ParsedTemplateInfo::NonTemplate:
2290 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2293 case ParsedTemplateInfo::Template:
2294 case ParsedTemplateInfo::ExplicitSpecialization: {
2295 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2296 *TemplateInfo.TemplateParams,
2298 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
2299 // Re-direct this decl to refer to the templated decl so that we can
2301 ThisDecl = VT->getTemplatedDecl();
2304 case ParsedTemplateInfo::ExplicitInstantiation: {
2305 if (Tok.is(tok::semi)) {
2306 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2307 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2308 if (ThisRes.isInvalid()) {
2309 SkipUntil(tok::semi, StopBeforeMatch);
2312 ThisDecl = ThisRes.get();
2314 // FIXME: This check should be for a variable template instantiation only.
2316 // Check that this is a valid instantiation
2317 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
2318 // If the declarator-id is not a template-id, issue a diagnostic and
2319 // recover by ignoring the 'template' keyword.
2320 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2321 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2322 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2324 SourceLocation LAngleLoc =
2325 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2326 Diag(D.getIdentifierLoc(),
2327 diag::err_explicit_instantiation_with_definition)
2328 << SourceRange(TemplateInfo.TemplateLoc)
2329 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2331 // Recover as if it were an explicit specialization.
2332 TemplateParameterLists FakedParamLists;
2333 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2334 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
2335 LAngleLoc, nullptr));
2338 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2345 // Parse declarator '=' initializer.
2346 // If a '==' or '+=' is found, suggest a fixit to '='.
2347 if (isTokenEqualOrEqualTypo()) {
2348 SourceLocation EqualLoc = ConsumeToken();
2350 if (Tok.is(tok::kw_delete)) {
2351 if (D.isFunctionDeclarator())
2352 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2355 Diag(ConsumeToken(), diag::err_deleted_non_function);
2356 } else if (Tok.is(tok::kw_default)) {
2357 if (D.isFunctionDeclarator())
2358 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2361 Diag(ConsumeToken(), diag::err_default_special_members)
2362 << getLangOpts().CPlusPlus2a;
2364 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2366 if (Tok.is(tok::code_completion)) {
2367 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2368 Actions.FinalizeDeclaration(ThisDecl);
2373 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2374 ExprResult Init = ParseInitializer();
2376 // If this is the only decl in (possibly) range based for statement,
2377 // our best guess is that the user meant ':' instead of '='.
2378 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2379 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2380 << FixItHint::CreateReplacement(EqualLoc, ":");
2381 // We are trying to stop parser from looking for ';' in this for
2382 // statement, therefore preventing spurious errors to be issued.
2383 FRI->ColonLoc = EqualLoc;
2385 FRI->RangeExpr = Init;
2390 if (Init.isInvalid()) {
2391 SmallVector<tok::TokenKind, 2> StopTokens;
2392 StopTokens.push_back(tok::comma);
2393 if (D.getContext() == DeclaratorContext::ForContext ||
2394 D.getContext() == DeclaratorContext::InitStmtContext)
2395 StopTokens.push_back(tok::r_paren);
2396 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2397 Actions.ActOnInitializerError(ThisDecl);
2399 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2400 /*DirectInit=*/false);
2402 } else if (Tok.is(tok::l_paren)) {
2403 // Parse C++ direct initializer: '(' expression-list ')'
2404 BalancedDelimiterTracker T(*this, tok::l_paren);
2408 CommaLocsTy CommaLocs;
2410 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2412 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2413 auto RunSignatureHelp = [&]() {
2414 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2415 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2416 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2417 CalledSignatureHelp = true;
2418 return PreferredType;
2420 auto SetPreferredType = [&] {
2421 PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2424 llvm::function_ref<void()> ExpressionStarts;
2426 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2427 // VarDecl. This is an error and it is reported in a call to
2428 // Actions.ActOnInitializerError(). However, we call
2429 // ProduceConstructorSignatureHelp only on VarDecls.
2430 ExpressionStarts = SetPreferredType;
2432 if (ParseExpressionList(Exprs, CommaLocs, ExpressionStarts)) {
2433 if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2434 Actions.ProduceConstructorSignatureHelp(
2435 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2436 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2437 CalledSignatureHelp = true;
2439 Actions.ActOnInitializerError(ThisDecl);
2440 SkipUntil(tok::r_paren, StopAtSemi);
2445 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2446 "Unexpected number of commas!");
2450 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2451 T.getCloseLocation(),
2453 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2454 /*DirectInit=*/true);
2456 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2457 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
2458 // Parse C++0x braced-init-list.
2459 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2461 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2463 ExprResult Init(ParseBraceInitializer());
2467 if (Init.isInvalid()) {
2468 Actions.ActOnInitializerError(ThisDecl);
2470 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2473 Actions.ActOnUninitializedDecl(ThisDecl);
2476 Actions.FinalizeDeclaration(ThisDecl);
2481 /// ParseSpecifierQualifierList
2482 /// specifier-qualifier-list:
2483 /// type-specifier specifier-qualifier-list[opt]
2484 /// type-qualifier specifier-qualifier-list[opt]
2485 /// [GNU] attributes specifier-qualifier-list[opt]
2487 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2488 DeclSpecContext DSC) {
2489 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2490 /// parse declaration-specifiers and complain about extra stuff.
2491 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2492 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2494 // Validate declspec for type-name.
2495 unsigned Specs = DS.getParsedSpecifiers();
2496 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2497 Diag(Tok, diag::err_expected_type);
2498 DS.SetTypeSpecError();
2499 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2500 Diag(Tok, diag::err_typename_requires_specqual);
2501 if (!DS.hasTypeSpecifier())
2502 DS.SetTypeSpecError();
2505 // Issue diagnostic and remove storage class if present.
2506 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2507 if (DS.getStorageClassSpecLoc().isValid())
2508 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2510 Diag(DS.getThreadStorageClassSpecLoc(),
2511 diag::err_typename_invalid_storageclass);
2512 DS.ClearStorageClassSpecs();
2515 // Issue diagnostic and remove function specifier if present.
2516 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2517 if (DS.isInlineSpecified())
2518 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2519 if (DS.isVirtualSpecified())
2520 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2521 if (DS.hasExplicitSpecifier())
2522 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2523 DS.ClearFunctionSpecs();
2526 // Issue diagnostic and remove constexpr specifier if present.
2527 if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2528 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2529 << DS.getConstexprSpecifier();
2530 DS.ClearConstexprSpec();
2534 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2535 /// specified token is valid after the identifier in a declarator which
2536 /// immediately follows the declspec. For example, these things are valid:
2538 /// int x [ 4]; // direct-declarator
2539 /// int x ( int y); // direct-declarator
2540 /// int(int x ) // direct-declarator
2541 /// int x ; // simple-declaration
2542 /// int x = 17; // init-declarator-list
2543 /// int x , y; // init-declarator-list
2544 /// int x __asm__ ("foo"); // init-declarator-list
2545 /// int x : 4; // struct-declarator
2546 /// int x { 5}; // C++'0x unified initializers
2548 /// This is not, because 'x' does not immediately follow the declspec (though
2549 /// ')' happens to be valid anyway).
2552 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2553 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2554 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2558 /// ParseImplicitInt - This method is called when we have an non-typename
2559 /// identifier in a declspec (which normally terminates the decl spec) when
2560 /// the declspec has no type specifier. In this case, the declspec is either
2561 /// malformed or is "implicit int" (in K&R and C89).
2563 /// This method handles diagnosing this prettily and returns false if the
2564 /// declspec is done being processed. If it recovers and thinks there may be
2565 /// other pieces of declspec after it, it returns true.
2567 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2568 const ParsedTemplateInfo &TemplateInfo,
2569 AccessSpecifier AS, DeclSpecContext DSC,
2570 ParsedAttributesWithRange &Attrs) {
2571 assert(Tok.is(tok::identifier) && "should have identifier");
2573 SourceLocation Loc = Tok.getLocation();
2574 // If we see an identifier that is not a type name, we normally would
2575 // parse it as the identifier being declared. However, when a typename
2576 // is typo'd or the definition is not included, this will incorrectly
2577 // parse the typename as the identifier name and fall over misparsing
2578 // later parts of the diagnostic.
2580 // As such, we try to do some look-ahead in cases where this would
2581 // otherwise be an "implicit-int" case to see if this is invalid. For
2582 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2583 // an identifier with implicit int, we'd get a parse error because the
2584 // next token is obviously invalid for a type. Parse these as a case
2585 // with an invalid type specifier.
2586 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2588 // Since we know that this either implicit int (which is rare) or an
2589 // error, do lookahead to try to do better recovery. This never applies
2590 // within a type specifier. Outside of C++, we allow this even if the
2591 // language doesn't "officially" support implicit int -- we support
2592 // implicit int as an extension in C99 and C11.
2593 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2594 isValidAfterIdentifierInDeclarator(NextToken())) {
2595 // If this token is valid for implicit int, e.g. "static x = 4", then
2596 // we just avoid eating the identifier, so it will be parsed as the
2597 // identifier in the declarator.
2601 // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2602 // for incomplete declarations such as `pipe p`.
2603 if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
2606 if (getLangOpts().CPlusPlus &&
2607 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2608 // Don't require a type specifier if we have the 'auto' storage class
2609 // specifier in C++98 -- we'll promote it to a type specifier.
2611 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2615 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2616 getLangOpts().MSVCCompat) {
2617 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2618 // Give Sema a chance to recover if we are in a template with dependent base
2620 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2621 *Tok.getIdentifierInfo(), Tok.getLocation(),
2622 DSC == DeclSpecContext::DSC_template_type_arg)) {
2623 const char *PrevSpec;
2625 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2626 Actions.getASTContext().getPrintingPolicy());
2627 DS.SetRangeEnd(Tok.getLocation());
2633 // Otherwise, if we don't consume this token, we are going to emit an
2634 // error anyway. Try to recover from various common problems. Check
2635 // to see if this was a reference to a tag name without a tag specified.
2636 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2638 // C++ doesn't need this, and isTagName doesn't take SS.
2639 if (SS == nullptr) {
2640 const char *TagName = nullptr, *FixitTagName = nullptr;
2641 tok::TokenKind TagKind = tok::unknown;
2643 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2645 case DeclSpec::TST_enum:
2646 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2647 case DeclSpec::TST_union:
2648 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2649 case DeclSpec::TST_struct:
2650 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2651 case DeclSpec::TST_interface:
2652 TagName="__interface"; FixitTagName = "__interface ";
2653 TagKind=tok::kw___interface;break;
2654 case DeclSpec::TST_class:
2655 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2659 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2660 LookupResult R(Actions, TokenName, SourceLocation(),
2661 Sema::LookupOrdinaryName);
2663 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2664 << TokenName << TagName << getLangOpts().CPlusPlus
2665 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2667 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2668 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2670 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2671 << TokenName << TagName;
2674 // Parse this as a tag as if the missing tag were present.
2675 if (TagKind == tok::kw_enum)
2676 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2677 DeclSpecContext::DSC_normal);
2679 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2680 /*EnteringContext*/ false,
2681 DeclSpecContext::DSC_normal, Attrs);
2686 // Determine whether this identifier could plausibly be the name of something
2687 // being declared (with a missing type).
2688 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2689 DSC == DeclSpecContext::DSC_class)) {
2690 // Look ahead to the next token to try to figure out what this declaration
2691 // was supposed to be.
2692 switch (NextToken().getKind()) {
2693 case tok::l_paren: {
2694 // static x(4); // 'x' is not a type
2695 // x(int n); // 'x' is not a type
2696 // x (*p)[]; // 'x' is a type
2698 // Since we're in an error case, we can afford to perform a tentative
2699 // parse to determine which case we're in.
2700 TentativeParsingAction PA(*this);
2702 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2705 if (TPR != TPResult::False) {
2706 // The identifier is followed by a parenthesized declarator.
2707 // It's supposed to be a type.
2711 // If we're in a context where we could be declaring a constructor,
2712 // check whether this is a constructor declaration with a bogus name.
2713 if (DSC == DeclSpecContext::DSC_class ||
2714 (DSC == DeclSpecContext::DSC_top_level && SS)) {
2715 IdentifierInfo *II = Tok.getIdentifierInfo();
2716 if (Actions.isCurrentClassNameTypo(II, SS)) {
2717 Diag(Loc, diag::err_constructor_bad_name)
2718 << Tok.getIdentifierInfo() << II
2719 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2720 Tok.setIdentifierInfo(II);
2732 // This looks like a variable or function declaration. The type is
2733 // probably missing. We're done parsing decl-specifiers.
2734 // But only if we are not in a function prototype scope.
2735 if (getCurScope()->isFunctionPrototypeScope())
2738 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2742 // This is probably supposed to be a type. This includes cases like:
2744 // struct S { unsinged : 4; };
2749 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2750 // and attempt to recover.
2752 IdentifierInfo *II = Tok.getIdentifierInfo();
2753 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2754 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2757 // The action has suggested that the type T could be used. Set that as
2758 // the type in the declaration specifiers, consume the would-be type
2759 // name token, and we're done.
2760 const char *PrevSpec;
2762 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2763 Actions.getASTContext().getPrintingPolicy());
2764 DS.SetRangeEnd(Tok.getLocation());
2766 // There may be other declaration specifiers after this.
2768 } else if (II != Tok.getIdentifierInfo()) {
2769 // If no type was suggested, the correction is to a keyword
2770 Tok.setKind(II->getTokenID());
2771 // There may be other declaration specifiers after this.
2775 // Otherwise, the action had no suggestion for us. Mark this as an error.
2776 DS.SetTypeSpecError();
2777 DS.SetRangeEnd(Tok.getLocation());
2780 // Eat any following template arguments.
2781 if (IsTemplateName) {
2782 SourceLocation LAngle, RAngle;
2783 TemplateArgList Args;
2784 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2787 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2788 // avoid rippling error messages on subsequent uses of the same type,
2789 // could be useful if #include was forgotten.
2793 /// Determine the declaration specifier context from the declarator
2796 /// \param Context the declarator context, which is one of the
2797 /// DeclaratorContext enumerator values.
2798 Parser::DeclSpecContext
2799 Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2800 if (Context == DeclaratorContext::MemberContext)
2801 return DeclSpecContext::DSC_class;
2802 if (Context == DeclaratorContext::FileContext)
2803 return DeclSpecContext::DSC_top_level;
2804 if (Context == DeclaratorContext::TemplateParamContext)
2805 return DeclSpecContext::DSC_template_param;
2806 if (Context == DeclaratorContext::TemplateArgContext ||
2807 Context == DeclaratorContext::TemplateTypeArgContext)
2808 return DeclSpecContext::DSC_template_type_arg;
2809 if (Context == DeclaratorContext::TrailingReturnContext ||
2810 Context == DeclaratorContext::TrailingReturnVarContext)
2811 return DeclSpecContext::DSC_trailing;
2812 if (Context == DeclaratorContext::AliasDeclContext ||
2813 Context == DeclaratorContext::AliasTemplateContext)
2814 return DeclSpecContext::DSC_alias_declaration;
2815 return DeclSpecContext::DSC_normal;
2818 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2820 /// FIXME: Simply returns an alignof() expression if the argument is a
2821 /// type. Ideally, the type should be propagated directly into Sema.
2824 /// [C11] constant-expression
2825 /// [C++0x] type-id ...[opt]
2826 /// [C++0x] assignment-expression ...[opt]
2827 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2828 SourceLocation &EllipsisLoc) {
2830 if (isTypeIdInParens()) {
2831 SourceLocation TypeLoc = Tok.getLocation();
2832 ParsedType Ty = ParseTypeName().get();
2833 SourceRange TypeRange(Start, Tok.getLocation());
2834 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2835 Ty.getAsOpaquePtr(), TypeRange);
2837 ER = ParseConstantExpression();
2839 if (getLangOpts().CPlusPlus11)
2840 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2845 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2846 /// attribute to Attrs.
2848 /// alignment-specifier:
2849 /// [C11] '_Alignas' '(' type-id ')'
2850 /// [C11] '_Alignas' '(' constant-expression ')'
2851 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2852 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2853 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2854 SourceLocation *EndLoc) {
2855 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2856 "Not an alignment-specifier!");
2858 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2859 SourceLocation KWLoc = ConsumeToken();
2861 BalancedDelimiterTracker T(*this, tok::l_paren);
2862 if (T.expectAndConsume())
2865 SourceLocation EllipsisLoc;
2866 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2867 if (ArgExpr.isInvalid()) {
2874 *EndLoc = T.getCloseLocation();
2876 ArgsVector ArgExprs;
2877 ArgExprs.push_back(ArgExpr.get());
2878 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2879 ParsedAttr::AS_Keyword, EllipsisLoc);
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
2887 /// \return \c true if an error occurred and this can't be any kind of
2890 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2891 DeclSpecContext DSContext,
2892 LateParsedAttrList *LateAttrs) {
2893 assert(DS.hasTagDefinition() && "shouldn't call this");
2895 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2896 DSContext == DeclSpecContext::DSC_top_level);
2898 if (getLangOpts().CPlusPlus &&
2899 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2900 tok::annot_template_id) &&
2901 TryAnnotateCXXScopeToken(EnteringContext)) {
2902 SkipMalformedDecl();
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;
2910 // Determine whether the following tokens could possibly be a
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();
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.
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,
2943 switch (Classification.getKind()) {
2944 case Sema::NC_Error:
2945 SkipMalformedDecl();
2948 case Sema::NC_Keyword:
2949 llvm_unreachable("typo correction is not possible here");
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;
2959 case Sema::NC_Unknown:
2960 case Sema::NC_NonType:
2961 case Sema::NC_DependentNonType:
2962 case Sema::NC_ContextIndependentExpr:
2963 case Sema::NC_VarTemplate:
2964 case Sema::NC_FunctionTemplate:
2965 case Sema::NC_Concept:
2966 // Might be a redeclaration of a prior entity.
2972 if (MightBeDeclarator)
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;
2980 // Try to recover from the typo, by dropping the tag definition and parsing
2981 // the problematic tokens as a type.
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);
2993 // Choose the apprpriate diagnostic error for why fixed point types are
2994 // disabled, set the previous specifier, and mark as invalid.
2995 static void SetupFixedPointError(const LangOptions &LangOpts,
2996 const char *&PrevSpec, unsigned &DiagID,
2998 assert(!LangOpts.FixedPoint);
2999 DiagID = diag::err_fixed_point_not_enabled;
3000 PrevSpec = ""; // Not used by diagnostic
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]
3014 /// storage-class-specifier: [C99 6.7.1]
3021 /// [C++11] 'thread_local'
3022 /// [C11] '_Thread_local'
3023 /// [GNU] '__thread'
3024 /// function-specifier: [C99 6.7.4]
3027 /// [C++] 'explicit'
3028 /// [OpenCL] '__kernel'
3029 /// 'friend': [C++ dcl.friend]
3030 /// 'constexpr': [C++0x dcl.constexpr]
3031 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
3032 const ParsedTemplateInfo &TemplateInfo,
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
3040 DS.SetRangeStart(Tok.getLocation());
3041 DS.SetRangeEnd(SourceLocation());
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();
3051 bool isInvalid = false;
3052 bool isStorageClass = false;
3053 const char *PrevSpec = nullptr;
3054 unsigned DiagID = 0;
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;
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>.
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);
3072 SourceLocation Loc = Tok.getLocation();
3074 switch (Tok.getKind()) {
3078 ProhibitAttributes(attrs);
3080 // Reject C++11 attributes that appertain to decl specifiers as
3081 // we don't support any C++11 attributes that appertain to decl
3082 // specifiers. This also conforms to what g++ 4.8 is doing.
3083 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
3085 DS.takeAttributesFrom(attrs);
3088 // If this is not a declaration specifier token, we're done reading decl
3089 // specifiers. First verify that DeclSpec's are consistent.
3090 DS.Finish(Actions, Policy);
3094 case tok::kw_alignas:
3095 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
3096 goto DoneWithDeclSpec;
3098 ProhibitAttributes(attrs);
3099 // FIXME: It would be good to recover by accepting the attributes,
3100 // but attempting to do that now would cause serious
3101 // madness in terms of diagnostics.
3103 attrs.Range = SourceRange();
3105 ParseCXX11Attributes(attrs);
3106 AttrsLastTime = true;
3109 case tok::code_completion: {
3110 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
3111 if (DS.hasTypeSpecifier()) {
3112 bool AllowNonIdentifiers
3113 = (getCurScope()->getFlags() & (Scope::ControlScope |
3115 Scope::TemplateParamScope |
3116 Scope::FunctionPrototypeScope |
3117 Scope::AtCatchScope)) == 0;
3118 bool AllowNestedNameSpecifiers
3119 = DSContext == DeclSpecContext::DSC_top_level ||
3120 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3122 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3123 AllowNonIdentifiers,
3124 AllowNestedNameSpecifiers);
3125 return cutOffParsing();
3128 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3129 CCC = Sema::PCC_LocalDeclarationSpecifiers;
3130 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3131 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3132 : Sema::PCC_Template;
3133 else if (DSContext == DeclSpecContext::DSC_class)
3134 CCC = Sema::PCC_Class;
3135 else if (CurParsedObjCImpl)
3136 CCC = Sema::PCC_ObjCImplementation;
3138 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3139 return cutOffParsing();
3142 case tok::coloncolon: // ::foo::bar
3143 // C++ scope specifier. Annotate and loop, or bail out on error.
3144 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3145 if (!DS.hasTypeSpecifier())
3146 DS.SetTypeSpecError();
3147 goto DoneWithDeclSpec;
3149 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3150 goto DoneWithDeclSpec;
3153 case tok::annot_cxxscope: {
3154 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3155 goto DoneWithDeclSpec;
3158 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3159 Tok.getAnnotationRange(),
3162 // We are looking for a qualified typename.
3163 Token Next = NextToken();
3164 if (Next.is(tok::annot_template_id) &&
3165 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3166 ->Kind == TNK_Type_template) {
3167 // We have a qualified template-id, e.g., N::A<int>
3169 // If this would be a valid constructor declaration with template
3170 // arguments, we will reject the attempt to form an invalid type-id
3171 // referring to the injected-class-name when we annotate the token,
3172 // per C++ [class.qual]p2.
3174 // To improve diagnostics for this case, parse the declaration as a
3175 // constructor (and reject the extra template arguments later).
3176 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
3177 if ((DSContext == DeclSpecContext::DSC_top_level ||
3178 DSContext == DeclSpecContext::DSC_class) &&
3180 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3181 isConstructorDeclarator(/*Unqualified=*/false)) {
3182 // The user meant this to be an out-of-line constructor
3183 // definition, but template arguments are not allowed
3184 // there. Just allow this as a constructor; we'll
3185 // complain about it later.
3186 goto DoneWithDeclSpec;
3189 DS.getTypeSpecScope() = SS;
3190 ConsumeAnnotationToken(); // The C++ scope.
3191 assert(Tok.is(tok::annot_template_id) &&
3192 "ParseOptionalCXXScopeSpecifier not working");
3193 AnnotateTemplateIdTokenAsType(SS);
3197 if (Next.is(tok::annot_template_id) &&
3198 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3199 ->Kind == TNK_Concept_template &&
3200 GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype)) {
3201 DS.getTypeSpecScope() = SS;
3202 // This is a qualified placeholder-specifier, e.g., ::C<int> auto ...
3203 // Consume the scope annotation and continue to consume the template-id
3204 // as a placeholder-specifier.
3205 ConsumeAnnotationToken();
3209 if (Next.is(tok::annot_typename)) {
3210 DS.getTypeSpecScope() = SS;
3211 ConsumeAnnotationToken(); // The C++ scope.
3212 if (Tok.getAnnotationValue()) {
3213 ParsedType T = getTypeAnnotation(Tok);
3214 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3215 Tok.getAnnotationEndLoc(),
3216 PrevSpec, DiagID, T, Policy);
3221 DS.SetTypeSpecError();
3222 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3223 ConsumeAnnotationToken(); // The typename
3226 if (Next.isNot(tok::identifier))
3227 goto DoneWithDeclSpec;
3229 // Check whether this is a constructor declaration. If we're in a
3230 // context where the identifier could be a class name, and it has the
3231 // shape of a constructor declaration, process it as one.
3232 if ((DSContext == DeclSpecContext::DSC_top_level ||
3233 DSContext == DeclSpecContext::DSC_class) &&
3234 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3236 isConstructorDeclarator(/*Unqualified*/ false))
3237 goto DoneWithDeclSpec;
3239 ParsedType TypeRep =
3240 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3241 getCurScope(), &SS, false, false, nullptr,
3242 /*IsCtorOrDtorName=*/false,
3243 /*WantNontrivialTypeSourceInfo=*/true,
3244 isClassTemplateDeductionContext(DSContext));
3246 // If the referenced identifier is not a type, then this declspec is
3247 // erroneous: We already checked about that it has no type specifier, and
3248 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3251 if (TryAnnotateTypeConstraint())
3252 goto DoneWithDeclSpec;
3253 if (isTypeConstraintAnnotation())
3255 // Eat the scope spec so the identifier is current.
3256 ConsumeAnnotationToken();
3257 ParsedAttributesWithRange Attrs(AttrFactory);
3258 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3259 if (!Attrs.empty()) {
3260 AttrsLastTime = true;
3261 attrs.takeAllFrom(Attrs);
3265 goto DoneWithDeclSpec;
3268 DS.getTypeSpecScope() = SS;
3269 ConsumeAnnotationToken(); // The C++ scope.
3271 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3272 DiagID, TypeRep, Policy);
3276 DS.SetRangeEnd(Tok.getLocation());
3277 ConsumeToken(); // The typename.
3282 case tok::annot_typename: {
3283 // If we've previously seen a tag definition, we were almost surely
3284 // missing a semicolon after it.
3285 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3286 goto DoneWithDeclSpec;
3288 if (Tok.getAnnotationValue()) {
3289 ParsedType T = getTypeAnnotation(Tok);
3290 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3293 DS.SetTypeSpecError();
3298 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3299 ConsumeAnnotationToken(); // The typename
3304 case tok::kw___is_signed:
3305 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3306 // typically treats it as a trait. If we see __is_signed as it appears
3307 // in libstdc++, e.g.,
3309 // static const bool __is_signed;
3311 // then treat __is_signed as an identifier rather than as a keyword.
3312 if (DS.getTypeSpecType() == TST_bool &&
3313 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3314 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3315 TryKeywordIdentFallback(true);
3317 // We're done with the declaration-specifiers.
3318 goto DoneWithDeclSpec;
3321 case tok::kw___super:
3322 case tok::kw_decltype:
3323 case tok::identifier: {
3324 // This identifier can only be a typedef name if we haven't already seen
3325 // a type-specifier. Without this check we misparse:
3326 // typedef int X; struct Y { short X; }; as 'short int'.
3327 if (DS.hasTypeSpecifier())
3328 goto DoneWithDeclSpec;
3330 // If the token is an identifier named "__declspec" and Microsoft
3331 // extensions are not enabled, it is likely that there will be cascading
3332 // parse errors if this really is a __declspec attribute. Attempt to
3333 // recognize that scenario and recover gracefully.
3334 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3335 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3336 Diag(Loc, diag::err_ms_attributes_not_enabled);
3338 // The next token should be an open paren. If it is, eat the entire
3339 // attribute declaration and continue.
3340 if (NextToken().is(tok::l_paren)) {
3341 // Consume the __declspec identifier.
3344 // Eat the parens and everything between them.
3345 BalancedDelimiterTracker T(*this, tok::l_paren);
3346 if (T.consumeOpen()) {
3347 assert(false && "Not a left paren?");
3355 // In C++, check to see if this is a scope specifier like foo::bar::, if
3356 // so handle it as such. This is important for ctor parsing.
3357 if (getLangOpts().CPlusPlus) {
3358 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3359 DS.SetTypeSpecError();
3360 goto DoneWithDeclSpec;
3362 if (!Tok.is(tok::identifier))
3366 // Check for need to substitute AltiVec keyword tokens.
3367 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3370 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3371 // allow the use of a typedef name as a type specifier.
3372 if (DS.isTypeAltiVecVector())
3373 goto DoneWithDeclSpec;
3375 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3376 isObjCInstancetype()) {
3377 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3379 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3380 DiagID, TypeRep, Policy);
3384 DS.SetRangeEnd(Loc);
3389 // If we're in a context where the identifier could be a class name,
3390 // check whether this is a constructor declaration.
3391 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3392 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3393 isConstructorDeclarator(/*Unqualified*/true))
3394 goto DoneWithDeclSpec;
3396 ParsedType TypeRep = Actions.getTypeName(
3397 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3398 false, false, nullptr, false, false,
3399 isClassTemplateDeductionContext(DSContext));
3401 // If this is not a typedef name, don't parse it as part of the declspec,
3402 // it must be an implicit int or an error.
3404 if (TryAnnotateTypeConstraint())
3405 goto DoneWithDeclSpec;
3406 if (isTypeConstraintAnnotation())
3408 ParsedAttributesWithRange Attrs(AttrFactory);
3409 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3410 if (!Attrs.empty()) {
3411 AttrsLastTime = true;
3412 attrs.takeAllFrom(Attrs);
3416 goto DoneWithDeclSpec;
3419 // Likewise, if this is a context where the identifier could be a template
3420 // name, check whether this is a deduction guide declaration.
3421 if (getLangOpts().CPlusPlus17 &&
3422 (DSContext == DeclSpecContext::DSC_class ||
3423 DSContext == DeclSpecContext::DSC_top_level) &&
3424 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3425 Tok.getLocation()) &&
3426 isConstructorDeclarator(/*Unqualified*/ true,
3427 /*DeductionGuide*/ true))
3428 goto DoneWithDeclSpec;
3430 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3431 DiagID, TypeRep, Policy);
3435 DS.SetRangeEnd(Tok.getLocation());
3436 ConsumeToken(); // The identifier
3438 // Objective-C supports type arguments and protocol references
3439 // following an Objective-C object or object pointer
3440 // type. Handle either one of them.
3441 if (Tok.is(tok::less) && getLangOpts().ObjC) {
3442 SourceLocation NewEndLoc;
3443 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3444 Loc, TypeRep, /*consumeLastToken=*/true,
3446 if (NewTypeRep.isUsable()) {
3447 DS.UpdateTypeRep(NewTypeRep.get());
3448 DS.SetRangeEnd(NewEndLoc);
3452 // Need to support trailing type qualifiers (e.g. "id<p> const").
3453 // If a type specifier follows, it will be diagnosed elsewhere.
3457 // type-name or placeholder-specifier
3458 case tok::annot_template_id: {
3459 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3460 if (TemplateId->Kind == TNK_Concept_template) {
3461 if (NextToken().is(tok::identifier)) {
3462 Diag(Loc, diag::err_placeholder_expected_auto_or_decltype_auto)
3463 << FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
3464 // Attempt to continue as if 'auto' was placed here.
3465 isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3466 TemplateId, Policy);
3469 if (!NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
3470 goto DoneWithDeclSpec;
3471 ConsumeAnnotationToken();
3472 SourceLocation AutoLoc = Tok.getLocation();
3473 if (TryConsumeToken(tok::kw_decltype)) {
3474 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3475 if (Tracker.consumeOpen()) {
3476 // Something like `void foo(Iterator decltype i)`
3477 Diag(Tok, diag::err_expected) << tok::l_paren;
3479 if (!TryConsumeToken(tok::kw_auto)) {
3480 // Something like `void foo(Iterator decltype(int) i)`
3481 Tracker.skipToEnd();
3482 Diag(Tok, diag::err_placeholder_expected_auto_or_decltype_auto)
3483 << FixItHint::CreateReplacement(SourceRange(AutoLoc,
3487 Tracker.consumeClose();
3490 ConsumedEnd = Tok.getLocation();
3491 // Even if something went wrong above, continue as if we've seen
3492 // `decltype(auto)`.
3493 isInvalid = DS.SetTypeSpecType(TST_decltype_auto, Loc, PrevSpec,
3494 DiagID, TemplateId, Policy);
3496 isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3497 TemplateId, Policy);
3502 if (TemplateId->Kind != TNK_Type_template &&
3503 TemplateId->Kind != TNK_Undeclared_template) {
3504 // This template-id does not refer to a type name, so we're
3505 // done with the type-specifiers.
3506 goto DoneWithDeclSpec;
3509 // If we're in a context where the template-id could be a
3510 // constructor name or specialization, check whether this is a
3511 // constructor declaration.
3512 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3513 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3514 isConstructorDeclarator(/*Unqualified=*/true))
3515 goto DoneWithDeclSpec;
3517 // Turn the template-id annotation token into a type annotation
3518 // token, then try again to parse it as a type-specifier.
3520 AnnotateTemplateIdTokenAsType(SS);
3524 // GNU attributes support.
3525 case tok::kw___attribute:
3526 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3529 // Microsoft declspec support.
3530 case tok::kw___declspec:
3531 ParseMicrosoftDeclSpecs(DS.getAttributes());
3534 // Microsoft single token adornments.
3535 case tok::kw___forceinline: {
3536 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3537 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3538 SourceLocation AttrNameLoc = Tok.getLocation();
3539 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3540 nullptr, 0, ParsedAttr::AS_Keyword);
3544 case tok::kw___unaligned:
3545 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3549 case tok::kw___sptr:
3550 case tok::kw___uptr:
3551 case tok::kw___ptr64:
3552 case tok::kw___ptr32:
3554 case tok::kw___cdecl:
3555 case tok::kw___stdcall:
3556 case tok::kw___fastcall:
3557 case tok::kw___thiscall:
3558 case tok::kw___regcall:
3559 case tok::kw___vectorcall:
3560 ParseMicrosoftTypeAttributes(DS.getAttributes());
3563 // Borland single token adornments.
3564 case tok::kw___pascal:
3565 ParseBorlandTypeAttributes(DS.getAttributes());
3568 // OpenCL single token adornments.
3569 case tok::kw___kernel:
3570 ParseOpenCLKernelAttributes(DS.getAttributes());
3573 // Nullability type specifiers.
3574 case tok::kw__Nonnull:
3575 case tok::kw__Nullable:
3576 case tok::kw__Null_unspecified:
3577 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3580 // Objective-C 'kindof' types.
3581 case tok::kw___kindof:
3582 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3583 nullptr, 0, ParsedAttr::AS_Keyword);
3584 (void)ConsumeToken();
3587 // storage-class-specifier
3588 case tok::kw_typedef:
3589 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3590 PrevSpec, DiagID, Policy);
3591 isStorageClass = true;
3593 case tok::kw_extern:
3594 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3595 Diag(Tok, diag::ext_thread_before) << "extern";
3596 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3597 PrevSpec, DiagID, Policy);
3598 isStorageClass = true;
3600 case tok::kw___private_extern__:
3601 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3602 Loc, PrevSpec, DiagID, Policy);
3603 isStorageClass = true;
3605 case tok::kw_static:
3606 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3607 Diag(Tok, diag::ext_thread_before) << "static";
3608 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3609 PrevSpec, DiagID, Policy);
3610 isStorageClass = true;
3613 if (getLangOpts().CPlusPlus11) {
3614 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3615 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3616 PrevSpec, DiagID, Policy);
3618 Diag(Tok, diag::ext_auto_storage_class)
3619 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3621 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3624 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3625 PrevSpec, DiagID, Policy);
3626 isStorageClass = true;
3628 case tok::kw___auto_type:
3629 Diag(Tok, diag::ext_auto_type);
3630 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3633 case tok::kw_register:
3634 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3635 PrevSpec, DiagID, Policy);
3636 isStorageClass = true;
3638 case tok::kw_mutable:
3639 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3640 PrevSpec, DiagID, Policy);
3641 isStorageClass = true;
3643 case tok::kw___thread:
3644 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3646 isStorageClass = true;
3648 case tok::kw_thread_local:
3649 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3651 isStorageClass = true;
3653 case tok::kw__Thread_local:
3654 if (!getLangOpts().C11)
3655 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3656 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3657 Loc, PrevSpec, DiagID);
3658 isStorageClass = true;
3661 // function-specifier
3662 case tok::kw_inline:
3663 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3665 case tok::kw_virtual:
3666 // C++ for OpenCL does not allow virtual function qualifier, to avoid
3667 // function pointers restricted in OpenCL v2.0 s6.9.a.
3668 if (getLangOpts().OpenCLCPlusPlus) {
3669 DiagID = diag::err_openclcxx_virtual_function;
3670 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3674 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3677 case tok::kw_explicit: {
3678 SourceLocation ExplicitLoc = Loc;
3679 SourceLocation CloseParenLoc;
3680 ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
3681 ConsumedEnd = ExplicitLoc;
3682 ConsumeToken(); // kw_explicit
3683 if (Tok.is(tok::l_paren)) {
3684 if (getLangOpts().CPlusPlus2a || isExplicitBool() == TPResult::True) {
3685 Diag(Tok.getLocation(), getLangOpts().CPlusPlus2a
3686 ? diag::warn_cxx17_compat_explicit_bool
3687 : diag::ext_explicit_bool);
3689 ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
3690 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3691 Tracker.consumeOpen();
3692 ExplicitExpr = ParseConstantExpression();
3693 ConsumedEnd = Tok.getLocation();
3694 if (ExplicitExpr.isUsable()) {
3695 CloseParenLoc = Tok.getLocation();
3696 Tracker.consumeClose();
3698 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
3700 Tracker.skipToEnd();
3702 Diag(Tok.getLocation(), diag::warn_cxx2a_compat_explicit_bool);
3705 isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
3706 ExplicitSpec, CloseParenLoc);
3709 case tok::kw__Noreturn:
3710 if (!getLangOpts().C11)
3711 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3712 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3715 // alignment-specifier
3716 case tok::kw__Alignas:
3717 if (!getLangOpts().C11)
3718 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3719 ParseAlignmentSpecifier(DS.getAttributes());
3723 case tok::kw_friend:
3724 if (DSContext == DeclSpecContext::DSC_class)
3725 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3727 PrevSpec = ""; // not actually used by the diagnostic
3728 DiagID = diag::err_friend_invalid_in_context;
3734 case tok::kw___module_private__:
3735 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3738 // constexpr, consteval, constinit specifiers
3739 case tok::kw_constexpr:
3740 isInvalid = DS.SetConstexprSpec(CSK_constexpr, Loc, PrevSpec, DiagID);
3742 case tok::kw_consteval:
3743 isInvalid = DS.SetConstexprSpec(CSK_consteval, Loc, PrevSpec, DiagID);
3745 case tok::kw_constinit:
3746 isInvalid = DS.SetConstexprSpec(CSK_constinit, Loc, PrevSpec, DiagID);
3751 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3755 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
3756 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3759 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3762 case tok::kw___int64:
3763 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3766 case tok::kw_signed:
3767 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3770 case tok::kw_unsigned:
3771 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3774 case tok::kw__Complex:
3775 if (!getLangOpts().C99)
3776 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3777 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3780 case tok::kw__Imaginary:
3781 if (!getLangOpts().C99)
3782 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3783 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3787 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3791 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3795 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3798 case tok::kw___int128:
3799 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3803 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3807 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3810 case tok::kw_double:
3811 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3814 case tok::kw__Float16:
3815 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3818 case tok::kw__Accum:
3819 if (!getLangOpts().FixedPoint) {
3820 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3822 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3826 case tok::kw__Fract:
3827 if (!getLangOpts().FixedPoint) {
3828 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3830 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3835 if (!getLangOpts().FixedPoint) {
3836 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3838 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3841 case tok::kw___float128:
3842 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3845 case tok::kw_wchar_t:
3846 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3849 case tok::kw_char8_t:
3850 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3853 case tok::kw_char16_t:
3854 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3857 case tok::kw_char32_t:
3858 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3863 if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
3864 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3866 if (Tok.is(tok::kw_bool) &&
3867 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3868 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3869 PrevSpec = ""; // Not used by the diagnostic.
3870 DiagID = diag::err_bool_redeclaration;
3871 // For better error recovery.
3872 Tok.setKind(tok::identifier);
3875 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3879 case tok::kw__Decimal32:
3880 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3883 case tok::kw__Decimal64:
3884 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3887 case tok::kw__Decimal128:
3888 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3891 case tok::kw___vector:
3892 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3894 case tok::kw___pixel:
3895 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3897 case tok::kw___bool:
3898 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3901 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200 &&
3902 !getLangOpts().OpenCLCPlusPlus)) {
3903 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3904 // support the "pipe" word as identifier.
3905 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3906 goto DoneWithDeclSpec;
3908 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3910 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
3911 case tok::kw_##ImgType##_t: \
3912 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3915 #include "clang/Basic/OpenCLImageTypes.def"
3916 case tok::kw___unknown_anytype:
3917 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3918 PrevSpec, DiagID, Policy);
3923 case tok::kw_struct:
3924 case tok::kw___interface:
3925 case tok::kw_union: {
3926 tok::TokenKind Kind = Tok.getKind();
3929 // These are attributes following class specifiers.
3930 // To produce better diagnostic, we parse them when
3931 // parsing class specifier.
3932 ParsedAttributesWithRange Attributes(AttrFactory);
3933 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3934 EnteringContext, DSContext, Attributes);
3936 // If there are attributes following class specifier,
3937 // take them over and handle them here.
3938 if (!Attributes.empty()) {
3939 AttrsLastTime = true;
3940 attrs.takeAllFrom(Attributes);
3948 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3953 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3956 case tok::kw_volatile:
3957 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3960 case tok::kw_restrict:
3961 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3965 // C++ typename-specifier:
3966 case tok::kw_typename:
3967 if (TryAnnotateTypeOrScopeToken()) {
3968 DS.SetTypeSpecError();
3969 goto DoneWithDeclSpec;
3971 if (!Tok.is(tok::kw_typename))
3975 // GNU typeof support.
3976 case tok::kw_typeof:
3977 ParseTypeofSpecifier(DS);
3980 case tok::annot_decltype:
3981 ParseDecltypeSpecifier(DS);
3984 case tok::annot_pragma_pack:
3988 case tok::annot_pragma_ms_pragma:
3989 HandlePragmaMSPragma();
3992 case tok::annot_pragma_ms_vtordisp:
3993 HandlePragmaMSVtorDisp();
3996 case tok::annot_pragma_ms_pointers_to_members:
3997 HandlePragmaMSPointersToMembers();
4000 case tok::kw___underlying_type:
4001 ParseUnderlyingTypeSpecifier(DS);
4004 case tok::kw__Atomic:
4006 // If the _Atomic keyword is immediately followed by a left parenthesis,
4007 // it is interpreted as a type specifier (with a type name), not as a
4009 if (!getLangOpts().C11)
4010 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4012 if (NextToken().is(tok::l_paren)) {
4013 ParseAtomicSpecifier(DS);
4016 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4020 // OpenCL address space qualifiers:
4021 case tok::kw___generic:
4022 // generic address space is introduced only in OpenCL v2.0
4023 // see OpenCL C Spec v2.0 s6.5.5
4024 if (Actions.getLangOpts().OpenCLVersion < 200 &&
4025 !Actions.getLangOpts().OpenCLCPlusPlus) {
4026 DiagID = diag::err_opencl_unknown_type_specifier;
4027 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4032 case tok::kw_private:
4033 // It's fine (but redundant) to check this for __generic on the
4034 // fallthrough path; we only form the __generic token in OpenCL mode.
4035 if (!getLangOpts().OpenCL)
4036 goto DoneWithDeclSpec;
4038 case tok::kw___private:
4039 case tok::kw___global:
4040 case tok::kw___local:
4041 case tok::kw___constant:
4042 // OpenCL access qualifiers:
4043 case tok::kw___read_only:
4044 case tok::kw___write_only:
4045 case tok::kw___read_write:
4046 ParseOpenCLQualifiers(DS.getAttributes());
4050 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
4051 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
4052 // but we support it.
4053 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
4054 goto DoneWithDeclSpec;
4056 SourceLocation StartLoc = Tok.getLocation();
4057 SourceLocation EndLoc;
4058 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
4059 if (Type.isUsable()) {
4060 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
4061 PrevSpec, DiagID, Type.get(),
4062 Actions.getASTContext().getPrintingPolicy()))
4063 Diag(StartLoc, DiagID) << PrevSpec;
4065 DS.SetRangeEnd(EndLoc);
4067 DS.SetTypeSpecError();
4070 // Need to support trailing type qualifiers (e.g. "id<p> const").
4071 // If a type specifier follows, it will be diagnosed elsewhere.
4075 DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
4077 // If the specifier wasn't legal, issue a diagnostic.
4079 assert(PrevSpec && "Method did not return previous specifier!");
4082 if (DiagID == diag::ext_duplicate_declspec ||
4083 DiagID == diag::ext_warn_duplicate_declspec ||
4084 DiagID == diag::err_duplicate_declspec)
4085 Diag(Loc, DiagID) << PrevSpec
4086 << FixItHint::CreateRemoval(
4087 SourceRange(Loc, DS.getEndLoc()));
4088 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4089 Diag(Loc, DiagID) << getLangOpts().OpenCLCPlusPlus
4090 << getLangOpts().getOpenCLVersionTuple().getAsString()
4091 << PrevSpec << isStorageClass;
4093 Diag(Loc, DiagID) << PrevSpec;
4096 if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
4097 // After an error the next token can be an annotation token.
4100 AttrsLastTime = false;
4104 /// ParseStructDeclaration - Parse a struct declaration without the terminating
4107 /// Note that a struct declaration refers to a declaration in a struct,
4108 /// not to the declaration of a struct.
4110 /// struct-declaration:
4111 /// [C2x] attributes-specifier-seq[opt]
4112 /// specifier-qualifier-list struct-declarator-list
4113 /// [GNU] __extension__ struct-declaration
4114 /// [GNU] specifier-qualifier-list
4115 /// struct-declarator-list:
4116 /// struct-declarator
4117 /// struct-declarator-list ',' struct-declarator
4118 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
4119 /// struct-declarator:
4121 /// [GNU] declarator attributes[opt]
4122 /// declarator[opt] ':' constant-expression
4123 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
4125 void Parser::ParseStructDeclaration(
4126 ParsingDeclSpec &DS,
4127 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4129 if (Tok.is(tok::kw___extension__)) {
4130 // __extension__ silences extension warnings in the subexpression.
4131 ExtensionRAIIObject O(Diags); // Use RAII to do this.
4133 return ParseStructDeclaration(DS, FieldsCallback);
4136 // Parse leading attributes.
4137 ParsedAttributesWithRange Attrs(AttrFactory);
4138 MaybeParseCXX11Attributes(Attrs);
4139 DS.takeAttributesFrom(Attrs);
4141 // Parse the common specifier-qualifiers-list piece.
4142 ParseSpecifierQualifierList(DS);
4144 // If there are no declarators, this is a free-standing declaration
4145 // specifier. Let the actions module cope with it.
4146 if (Tok.is(tok::semi)) {
4147 RecordDecl *AnonRecord = nullptr;
4148 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
4150 assert(!AnonRecord && "Did not expect anonymous struct or union here");
4151 DS.complete(TheDecl);
4155 // Read struct-declarators until we find the semicolon.
4156 bool FirstDeclarator = true;
4157 SourceLocation CommaLoc;
4159 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
4160 DeclaratorInfo.D.setCommaLoc(CommaLoc);
4162 // Attributes are only allowed here on successive declarators.
4163 if (!FirstDeclarator)
4164 MaybeParseGNUAttributes(DeclaratorInfo.D);
4166 /// struct-declarator: declarator
4167 /// struct-declarator: declarator[opt] ':' constant-expression
4168 if (Tok.isNot(tok::colon)) {
4169 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4170 ColonProtectionRAIIObject X(*this);
4171 ParseDeclarator(DeclaratorInfo.D);
4173 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4175 if (TryConsumeToken(tok::colon)) {
4176 ExprResult Res(ParseConstantExpression());
4177 if (Res.isInvalid())
4178 SkipUntil(tok::semi, StopBeforeMatch);
4180 DeclaratorInfo.BitfieldSize = Res.get();
4183 // If attributes exist after the declarator, parse them.
4184 MaybeParseGNUAttributes(DeclaratorInfo.D);
4186 // We're done with this declarator; invoke the callback.
4187 FieldsCallback(DeclaratorInfo);
4189 // If we don't have a comma, it is either the end of the list (a ';')
4190 // or an error, bail out.
4191 if (!TryConsumeToken(tok::comma, CommaLoc))
4194 FirstDeclarator = false;
4198 /// ParseStructUnionBody
4199 /// struct-contents:
4200 /// struct-declaration-list
4202 /// [GNU] "struct-declaration-list" without terminatoring ';'
4203 /// struct-declaration-list:
4204 /// struct-declaration
4205 /// struct-declaration-list struct-declaration
4206 /// [OBC] '@' 'defs' '(' class-name ')'
4208 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4209 DeclSpec::TST TagType, Decl *TagDecl) {
4210 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4211 "parsing struct/union body");
4212 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4214 BalancedDelimiterTracker T(*this, tok::l_brace);
4215 if (T.consumeOpen())
4218 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4219 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
4221 SmallVector<Decl *, 32> FieldDecls;
4223 // While we still have something to read, read the declarations in the struct.
4224 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4225 Tok.isNot(tok::eof)) {
4226 // Each iteration of this loop reads one struct-declaration.
4228 // Check for extraneous top-level semicolon.
4229 if (Tok.is(tok::semi)) {
4230 ConsumeExtraSemi(InsideStruct, TagType);
4234 // Parse _Static_assert declaration.
4235 if (Tok.is(tok::kw__Static_assert)) {
4236 SourceLocation DeclEnd;
4237 ParseStaticAssertDeclaration(DeclEnd);
4241 if (Tok.is(tok::annot_pragma_pack)) {
4246 if (Tok.is(tok::annot_pragma_align)) {
4247 HandlePragmaAlign();
4251 if (Tok.is(tok::annot_pragma_openmp)) {
4252 // Result can be ignored, because it must be always empty.
4253 AccessSpecifier AS = AS_none;
4254 ParsedAttributesWithRange Attrs(AttrFactory);
4255 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4259 if (tok::isPragmaAnnotation(Tok.getKind())) {
4260 Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4261 << DeclSpec::getSpecifierName(
4262 TagType, Actions.getASTContext().getPrintingPolicy());
4263 ConsumeAnnotationToken();
4267 if (!Tok.is(tok::at)) {
4268 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4269 // Install the declarator into the current TagDecl.
4271 Actions.ActOnField(getCurScope(), TagDecl,
4272 FD.D.getDeclSpec().getSourceRange().getBegin(),
4273 FD.D, FD.BitfieldSize);
4274 FieldDecls.push_back(Field);
4278 // Parse all the comma separated declarators.
4279 ParsingDeclSpec DS(*this);
4280 ParseStructDeclaration(DS, CFieldCallback);
4281 } else { // Handle @defs
4283 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4284 Diag(Tok, diag::err_unexpected_at);
4285 SkipUntil(tok::semi);
4289 ExpectAndConsume(tok::l_paren);
4290 if (!Tok.is(tok::identifier)) {
4291 Diag(Tok, diag::err_expected) << tok::identifier;
4292 SkipUntil(tok::semi);
4295 SmallVector<Decl *, 16> Fields;
4296 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4297 Tok.getIdentifierInfo(), Fields);
4298 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4300 ExpectAndConsume(tok::r_paren);
4303 if (TryConsumeToken(tok::semi))
4306 if (Tok.is(tok::r_brace)) {
4307 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4311 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4312 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4313 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4314 // If we stopped at a ';', eat it.
4315 TryConsumeToken(tok::semi);
4320 ParsedAttributes attrs(AttrFactory);
4321 // If attributes exist after struct contents, parse them.
4322 MaybeParseGNUAttributes(attrs);
4324 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4325 T.getOpenLocation(), T.getCloseLocation(), attrs);
4327 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4330 /// ParseEnumSpecifier
4331 /// enum-specifier: [C99 6.7.2.2]
4332 /// 'enum' identifier[opt] '{' enumerator-list '}'
4333 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4334 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4335 /// '}' attributes[opt]
4336 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4338 /// 'enum' identifier
4339 /// [GNU] 'enum' attributes[opt] identifier
4341 /// [C++11] enum-head '{' enumerator-list[opt] '}'
4342 /// [C++11] enum-head '{' enumerator-list ',' '}'
4344 /// enum-head: [C++11]
4345 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4346 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
4347 /// identifier enum-base[opt]
4349 /// enum-key: [C++11]
4354 /// enum-base: [C++11]
4355 /// ':' type-specifier-seq
4357 /// [C++] elaborated-type-specifier:
4358 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4360 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4361 const ParsedTemplateInfo &TemplateInfo,
4362 AccessSpecifier AS, DeclSpecContext DSC) {
4363 // Parse the tag portion of this.
4364 if (Tok.is(tok::code_completion)) {
4365 // Code completion for an enum name.
4366 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
4367 return cutOffParsing();
4370 // If attributes exist after tag, parse them.
4371 ParsedAttributesWithRange attrs(AttrFactory);
4372 MaybeParseGNUAttributes(attrs);
4373 MaybeParseCXX11Attributes(attrs);
4374 MaybeParseMicrosoftDeclSpecs(attrs);
4376 SourceLocation ScopedEnumKWLoc;
4377 bool IsScopedUsingClassTag = false;
4379 // In C++11, recognize 'enum class' and 'enum struct'.
4380 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4381 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4382 : diag::ext_scoped_enum);
4383 IsScopedUsingClassTag = Tok.is(tok::kw_class);
4384 ScopedEnumKWLoc = ConsumeToken();
4386 // Attributes are not allowed between these keywords. Diagnose,
4387 // but then just treat them like they appeared in the right place.
4388 ProhibitAttributes(attrs);
4390 // They are allowed afterwards, though.
4391 MaybeParseGNUAttributes(attrs);
4392 MaybeParseCXX11Attributes(attrs);
4393 MaybeParseMicrosoftDeclSpecs(attrs);
4396 // C++11 [temp.explicit]p12:
4397 // The usual access controls do not apply to names used to specify
4398 // explicit instantiations.
4399 // We extend this to also cover explicit specializations. Note that
4400 // we don't suppress if this turns out to be an elaborated type
4402 bool shouldDelayDiagsInTag =
4403 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4404 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4405 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4407 // Enum definitions should not be parsed in a trailing-return-type.
4408 bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
4410 CXXScopeSpec &SS = DS.getTypeSpecScope();
4411 if (getLangOpts().CPlusPlus) {
4412 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4413 // if a fixed underlying type is allowed.
4414 ColonProtectionRAIIObject X(*this, AllowDeclaration);
4417 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
4418 /*EnteringContext=*/true))
4421 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4422 Diag(Tok, diag::err_expected) << tok::identifier;
4423 if (Tok.isNot(tok::l_brace)) {
4424 // Has no name and is not a definition.
4425 // Skip the rest of this declarator, up until the comma or semicolon.
4426 SkipUntil(tok::comma, StopAtSemi);
4434 // Must have either 'enum name' or 'enum {...}'.
4435 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4436 !(AllowDeclaration && Tok.is(tok::colon))) {
4437 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4439 // Skip the rest of this declarator, up until the comma or semicolon.
4440 SkipUntil(tok::comma, StopAtSemi);
4444 // If an identifier is present, consume and remember it.
4445 IdentifierInfo *Name = nullptr;
4446 SourceLocation NameLoc;
4447 if (Tok.is(tok::identifier)) {
4448 Name = Tok.getIdentifierInfo();
4449 NameLoc = ConsumeToken();
4452 if (!Name && ScopedEnumKWLoc.isValid()) {
4453 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4454 // declaration of a scoped enumeration.
4455 Diag(Tok, diag::err_scoped_enum_missing_identifier);
4456 ScopedEnumKWLoc = SourceLocation();
4457 IsScopedUsingClassTag = false;
4460 // Okay, end the suppression area. We'll decide whether to emit the
4461 // diagnostics in a second.
4462 if (shouldDelayDiagsInTag)
4463 diagsFromTag.done();
4465 TypeResult BaseType;
4467 // Parse the fixed underlying type.
4468 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4469 if (AllowDeclaration && Tok.is(tok::colon)) {
4470 bool PossibleBitfield = false;
4471 if (CanBeBitfield) {
4472 // If we're in class scope, this can either be an enum declaration with
4473 // an underlying type, or a declaration of a bitfield member. We try to
4474 // use a simple disambiguation scheme first to catch the common cases
4475 // (integer literal, sizeof); if it's still ambiguous, we then consider
4476 // anything that's a simple-type-specifier followed by '(' as an
4477 // expression. This suffices because function types are not valid
4478 // underlying types anyway.
4479 EnterExpressionEvaluationContext Unevaluated(
4480 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4481 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
4482 // If the next token starts an expression, we know we're parsing a
4483 // bit-field. This is the common case.
4484 if (TPR == TPResult::True)
4485 PossibleBitfield = true;
4486 // If the next token starts a type-specifier-seq, it may be either a
4487 // a fixed underlying type or the start of a function-style cast in C++;
4488 // lookahead one more token to see if it's obvious that we have a
4489 // fixed underlying type.
4490 else if (TPR == TPResult::False &&
4491 GetLookAheadToken(2).getKind() == tok::semi) {
4495 // We have the start of a type-specifier-seq, so we have to perform
4496 // tentative parsing to determine whether we have an expression or a
4498 TentativeParsingAction TPA(*this);
4503 // If we see a type specifier followed by an open-brace, we have an
4504 // ambiguity between an underlying type and a C++11 braced
4505 // function-style cast. Resolve this by always treating it as an
4507 // FIXME: The standard is not entirely clear on how to disambiguate in
4509 if ((getLangOpts().CPlusPlus &&
4510 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
4511 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
4512 // We'll parse this as a bitfield later.
4513 PossibleBitfield = true;
4516 // We have a type-specifier-seq.
4525 if (!PossibleBitfield) {
4527 BaseType = ParseTypeName(&Range);
4529 if (!getLangOpts().ObjC) {
4530 if (getLangOpts().CPlusPlus11)
4531 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4532 else if (getLangOpts().CPlusPlus)
4533 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type);
4534 else if (getLangOpts().MicrosoftExt)
4535 Diag(StartLoc, diag::ext_ms_c_enum_fixed_underlying_type);
4537 Diag(StartLoc, diag::ext_clang_c_enum_fixed_underlying_type);
4542 // There are four options here. If we have 'friend enum foo;' then this is a
4543 // friend declaration, and cannot have an accompanying definition. If we have
4544 // 'enum foo;', then this is a forward declaration. If we have
4545 // 'enum foo {...' then this is a definition. Otherwise we have something
4546 // like 'enum foo xyz', a reference.
4548 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4549 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4550 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4552 Sema::TagUseKind TUK;
4553 if (!AllowDeclaration) {
4554 TUK = Sema::TUK_Reference;
4555 } else if (Tok.is(tok::l_brace)) {
4556 if (DS.isFriendSpecified()) {
4557 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4558 << SourceRange(DS.getFriendSpecLoc());
4560 SkipUntil(tok::r_brace, StopAtSemi);
4561 TUK = Sema::TUK_Friend;
4563 TUK = Sema::TUK_Definition;
4565 } else if (!isTypeSpecifier(DSC) &&
4566 (Tok.is(tok::semi) ||
4567 (Tok.isAtStartOfLine() &&
4568 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4569 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4570 if (Tok.isNot(tok::semi)) {
4571 // A semicolon was missing after this declaration. Diagnose and recover.
4572 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4573 PP.EnterToken(Tok, /*IsReinject=*/true);
4574 Tok.setKind(tok::semi);
4577 TUK = Sema::TUK_Reference;
4580 // If this is an elaborated type specifier, and we delayed
4581 // diagnostics before, just merge them into the current pool.
4582 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4583 diagsFromTag.redelay();
4586 MultiTemplateParamsArg TParams;
4587 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4588 TUK != Sema::TUK_Reference) {
4589 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4590 // Skip the rest of this declarator, up until the comma or semicolon.
4591 Diag(Tok, diag::err_enum_template);
4592 SkipUntil(tok::comma, StopAtSemi);
4596 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4597 // Enumerations can't be explicitly instantiated.
4598 DS.SetTypeSpecError();
4599 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4603 assert(TemplateInfo.TemplateParams && "no template parameters");
4604 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4605 TemplateInfo.TemplateParams->size());
4608 if (TUK == Sema::TUK_Reference)
4609 ProhibitAttributes(attrs);
4611 if (!Name && TUK != Sema::TUK_Definition) {
4612 Diag(Tok, diag::err_enumerator_unnamed_no_def);
4614 // Skip the rest of this declarator, up until the comma or semicolon.
4615 SkipUntil(tok::comma, StopAtSemi);
4619 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4621 Sema::SkipBodyInfo SkipBody;
4622 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4623 NextToken().is(tok::identifier))
4624 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4625 NextToken().getIdentifierInfo(),
4626 NextToken().getLocation());
4629 bool IsDependent = false;
4630 const char *PrevSpec = nullptr;
4632 Decl *TagDecl = Actions.ActOnTag(
4633 getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
4634 attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4635 ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
4636 DSC == DeclSpecContext::DSC_type_specifier,
4637 DSC == DeclSpecContext::DSC_template_param ||
4638 DSC == DeclSpecContext::DSC_template_type_arg,
4641 if (SkipBody.ShouldSkip) {
4642 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4644 BalancedDelimiterTracker T(*this, tok::l_brace);
4648 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4649 NameLoc.isValid() ? NameLoc : StartLoc,
4650 PrevSpec, DiagID, TagDecl, Owned,
4651 Actions.getASTContext().getPrintingPolicy()))
4652 Diag(StartLoc, DiagID) << PrevSpec;
4657 // This enum has a dependent nested-name-specifier. Handle it as a
4660 DS.SetTypeSpecError();
4661 Diag(Tok, diag::err_expected_type_name_after_typename);
4665 TypeResult Type = Actions.ActOnDependentTag(
4666 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4667 if (Type.isInvalid()) {
4668 DS.SetTypeSpecError();
4672 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4673 NameLoc.isValid() ? NameLoc : StartLoc,
4674 PrevSpec, DiagID, Type.get(),
4675 Actions.getASTContext().getPrintingPolicy()))
4676 Diag(StartLoc, DiagID) << PrevSpec;
4682 // The action failed to produce an enumeration tag. If this is a
4683 // definition, consume the entire definition.
4684 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4686 SkipUntil(tok::r_brace, StopAtSemi);
4689 DS.SetTypeSpecError();
4693 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4694 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4695 ParseEnumBody(StartLoc, D);
4696 if (SkipBody.CheckSameAsPrevious &&
4697 !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4698 DS.SetTypeSpecError();
4703 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4704 NameLoc.isValid() ? NameLoc : StartLoc,
4705 PrevSpec, DiagID, TagDecl, Owned,
4706 Actions.getASTContext().getPrintingPolicy()))
4707 Diag(StartLoc, DiagID) << PrevSpec;
4710 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4711 /// enumerator-list:
4713 /// enumerator-list ',' enumerator
4715 /// enumeration-constant attributes[opt]
4716 /// enumeration-constant attributes[opt] '=' constant-expression
4717 /// enumeration-constant:
4720 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4721 // Enter the scope of the enum body and start the definition.
4722 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4723 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4725 BalancedDelimiterTracker T(*this, tok::l_brace);
4728 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4729 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4730 Diag(Tok, diag::err_empty_enum);
4732 SmallVector<Decl *, 32> EnumConstantDecls;
4733 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4735 Decl *LastEnumConstDecl = nullptr;
4737 // Parse the enumerator-list.
4738 while (Tok.isNot(tok::r_brace)) {
4739 // Parse enumerator. If failed, try skipping till the start of the next
4740 // enumerator definition.
4741 if (Tok.isNot(tok::identifier)) {
4742 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4743 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4744 TryConsumeToken(tok::comma))
4748 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4749 SourceLocation IdentLoc = ConsumeToken();
4751 // If attributes exist after the enumerator, parse them.
4752 ParsedAttributesWithRange attrs(AttrFactory);
4753 MaybeParseGNUAttributes(attrs);
4754 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4755 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4756 if (getLangOpts().CPlusPlus)
4757 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4758 ? diag::warn_cxx14_compat_ns_enum_attribute
4759 : diag::ext_ns_enum_attribute)
4760 << 1 /*enumerator*/;
4761 ParseCXX11Attributes(attrs);
4764 SourceLocation EqualLoc;
4765 ExprResult AssignedVal;
4766 EnumAvailabilityDiags.emplace_back(*this);
4768 EnterExpressionEvaluationContext ConstantEvaluated(
4769 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4770 if (TryConsumeToken(tok::equal, EqualLoc)) {
4771 AssignedVal = ParseConstantExpressionInExprEvalContext();
4772 if (AssignedVal.isInvalid())
4773 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4776 // Install the enumerator constant into EnumDecl.
4777 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
4778 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4779 EqualLoc, AssignedVal.get());
4780 EnumAvailabilityDiags.back().done();
4782 EnumConstantDecls.push_back(EnumConstDecl);
4783 LastEnumConstDecl = EnumConstDecl;
4785 if (Tok.is(tok::identifier)) {
4786 // We're missing a comma between enumerators.
4787 SourceLocation Loc = getEndOfPreviousToken();
4788 Diag(Loc, diag::err_enumerator_list_missing_comma)
4789 << FixItHint::CreateInsertion(Loc, ", ");
4793 // Emumerator definition must be finished, only comma or r_brace are
4795 SourceLocation CommaLoc;
4796 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4797 if (EqualLoc.isValid())
4798 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4801 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4802 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4803 if (TryConsumeToken(tok::comma, CommaLoc))
4810 // If comma is followed by r_brace, emit appropriate warning.
4811 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4812 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4813 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4814 diag::ext_enumerator_list_comma_cxx :
4815 diag::ext_enumerator_list_comma_c)
4816 << FixItHint::CreateRemoval(CommaLoc);
4817 else if (getLangOpts().CPlusPlus11)
4818 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4819 << FixItHint::CreateRemoval(CommaLoc);
4827 // If attributes exist after the identifier list, parse them.
4828 ParsedAttributes attrs(AttrFactory);
4829 MaybeParseGNUAttributes(attrs);
4831 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4832 getCurScope(), attrs);
4834 // Now handle enum constant availability diagnostics.
4835 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4836 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4837 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4838 EnumAvailabilityDiags[i].redelay();
4839 PD.complete(EnumConstantDecls[i]);
4843 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4845 // The next token must be valid after an enum definition. If not, a ';'
4846 // was probably forgotten.
4847 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4848 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4849 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4850 // Push this token back into the preprocessor and change our current token
4851 // to ';' so that the rest of the code recovers as though there were an
4852 // ';' after the definition.
4853 PP.EnterToken(Tok, /*IsReinject=*/true);
4854 Tok.setKind(tok::semi);
4858 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4859 /// is definitely a type-specifier. Return false if it isn't part of a type
4860 /// specifier or if we're not sure.
4861 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4862 switch (Tok.getKind()) {
4863 default: return false;
4867 case tok::kw___int64:
4868 case tok::kw___int128:
4869 case tok::kw_signed:
4870 case tok::kw_unsigned:
4871 case tok::kw__Complex:
4872 case tok::kw__Imaginary:
4875 case tok::kw_wchar_t:
4876 case tok::kw_char8_t:
4877 case tok::kw_char16_t:
4878 case tok::kw_char32_t:
4882 case tok::kw_double:
4883 case tok::kw__Accum:
4884 case tok::kw__Fract:
4885 case tok::kw__Float16:
4886 case tok::kw___float128:
4889 case tok::kw__Decimal32:
4890 case tok::kw__Decimal64:
4891 case tok::kw__Decimal128:
4892 case tok::kw___vector:
4893 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4894 #include "clang/Basic/OpenCLImageTypes.def"
4896 // struct-or-union-specifier (C99) or class-specifier (C++)
4898 case tok::kw_struct:
4899 case tok::kw___interface:
4905 case tok::annot_typename:
4910 /// isTypeSpecifierQualifier - Return true if the current token could be the
4911 /// start of a specifier-qualifier-list.
4912 bool Parser::isTypeSpecifierQualifier() {
4913 switch (Tok.getKind()) {
4914 default: return false;
4916 case tok::identifier: // foo::bar
4917 if (TryAltiVecVectorToken())
4920 case tok::kw_typename: // typename T::type
4921 // Annotate typenames and C++ scope specifiers. If we get one, just
4922 // recurse to handle whatever we get.
4923 if (TryAnnotateTypeOrScopeToken())
4925 if (Tok.is(tok::identifier))
4927 return isTypeSpecifierQualifier();
4929 case tok::coloncolon: // ::foo::bar
4930 if (NextToken().is(tok::kw_new) || // ::new
4931 NextToken().is(tok::kw_delete)) // ::delete
4934 if (TryAnnotateTypeOrScopeToken())
4936 return isTypeSpecifierQualifier();
4938 // GNU attributes support.
4939 case tok::kw___attribute:
4940 // GNU typeof support.
4941 case tok::kw_typeof:
4946 case tok::kw___int64:
4947 case tok::kw___int128:
4948 case tok::kw_signed:
4949 case tok::kw_unsigned:
4950 case tok::kw__Complex:
4951 case tok::kw__Imaginary:
4954 case tok::kw_wchar_t:
4955 case tok::kw_char8_t:
4956 case tok::kw_char16_t:
4957 case tok::kw_char32_t:
4961 case tok::kw_double:
4962 case tok::kw__Accum:
4963 case tok::kw__Fract:
4964 case tok::kw__Float16:
4965 case tok::kw___float128:
4968 case tok::kw__Decimal32:
4969 case tok::kw__Decimal64:
4970 case tok::kw__Decimal128:
4971 case tok::kw___vector:
4972 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4973 #include "clang/Basic/OpenCLImageTypes.def"
4975 // struct-or-union-specifier (C99) or class-specifier (C++)
4977 case tok::kw_struct:
4978 case tok::kw___interface:
4985 case tok::kw_volatile:
4986 case tok::kw_restrict:
4989 // Debugger support.
4990 case tok::kw___unknown_anytype:
4993 case tok::annot_typename:
4996 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4998 return getLangOpts().ObjC;
5000 case tok::kw___cdecl:
5001 case tok::kw___stdcall:
5002 case tok::kw___fastcall:
5003 case tok::kw___thiscall:
5004 case tok::kw___regcall:
5005 case tok::kw___vectorcall:
5007 case tok::kw___ptr64:
5008 case tok::kw___ptr32:
5009 case tok::kw___pascal:
5010 case tok::kw___unaligned:
5012 case tok::kw__Nonnull:
5013 case tok::kw__Nullable:
5014 case tok::kw__Null_unspecified:
5016 case tok::kw___kindof:
5018 case tok::kw___private:
5019 case tok::kw___local:
5020 case tok::kw___global:
5021 case tok::kw___constant:
5022 case tok::kw___generic:
5023 case tok::kw___read_only:
5024 case tok::kw___read_write:
5025 case tok::kw___write_only:
5028 case tok::kw_private:
5029 return getLangOpts().OpenCL;
5032 case tok::kw__Atomic:
5037 /// isDeclarationSpecifier() - Return true if the current token is part of a
5038 /// declaration specifier.
5040 /// \param DisambiguatingWithExpression True to indicate that the purpose of
5041 /// this check is to disambiguate between an expression and a declaration.
5042 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
5043 switch (Tok.getKind()) {
5044 default: return false;
5047 return (getLangOpts().OpenCL && getLangOpts().OpenCLVersion >= 200) ||
5048 getLangOpts().OpenCLCPlusPlus;
5050 case tok::identifier: // foo::bar
5051 // Unfortunate hack to support "Class.factoryMethod" notation.
5052 if (getLangOpts().ObjC && NextToken().is(tok::period))
5054 if (TryAltiVecVectorToken())
5057 case tok::kw_decltype: // decltype(T())::type
5058 case tok::kw_typename: // typename T::type
5059 // Annotate typenames and C++ scope specifiers. If we get one, just
5060 // recurse to handle whatever we get.
5061 if (TryAnnotateTypeOrScopeToken())
5063 if (Tok.is(tok::identifier))
5066 // If we're in Objective-C and we have an Objective-C class type followed
5067 // by an identifier and then either ':' or ']', in a place where an
5068 // expression is permitted, then this is probably a class message send
5069 // missing the initial '['. In this case, we won't consider this to be
5070 // the start of a declaration.
5071 if (DisambiguatingWithExpression &&
5072 isStartOfObjCClassMessageMissingOpenBracket())
5075 return isDeclarationSpecifier();
5077 case tok::coloncolon: // ::foo::bar
5078 if (NextToken().is(tok::kw_new) || // ::new
5079 NextToken().is(tok::kw_delete)) // ::delete
5082 // Annotate typenames and C++ scope specifiers. If we get one, just
5083 // recurse to handle whatever we get.
5084 if (TryAnnotateTypeOrScopeToken())
5086 return isDeclarationSpecifier();
5088 // storage-class-specifier
5089 case tok::kw_typedef:
5090 case tok::kw_extern:
5091 case tok::kw___private_extern__:
5092 case tok::kw_static:
5094 case tok::kw___auto_type:
5095 case tok::kw_register:
5096 case tok::kw___thread:
5097 case tok::kw_thread_local:
5098 case tok::kw__Thread_local:
5101 case tok::kw___module_private__:
5104 case tok::kw___unknown_anytype:
5109 case tok::kw___int64:
5110 case tok::kw___int128:
5111 case tok::kw_signed:
5112 case tok::kw_unsigned:
5113 case tok::kw__Complex:
5114 case tok::kw__Imaginary:
5117 case tok::kw_wchar_t:
5118 case tok::kw_char8_t:
5119 case tok::kw_char16_t:
5120 case tok::kw_char32_t:
5125 case tok::kw_double:
5126 case tok::kw__Accum:
5127 case tok::kw__Fract:
5128 case tok::kw__Float16:
5129 case tok::kw___float128:
5132 case tok::kw__Decimal32:
5133 case tok::kw__Decimal64:
5134 case tok::kw__Decimal128:
5135 case tok::kw___vector:
5137 // struct-or-union-specifier (C99) or class-specifier (C++)
5139 case tok::kw_struct:
5141 case tok::kw___interface:
5147 case tok::kw_volatile:
5148 case tok::kw_restrict:
5151 // function-specifier
5152 case tok::kw_inline:
5153 case tok::kw_virtual:
5154 case tok::kw_explicit:
5155 case tok::kw__Noreturn:
5157 // alignment-specifier
5158 case tok::kw__Alignas:
5161 case tok::kw_friend:
5163 // static_assert-declaration
5164 case tok::kw__Static_assert:
5166 // GNU typeof support.
5167 case tok::kw_typeof:
5170 case tok::kw___attribute:
5172 // C++11 decltype and constexpr.
5173 case tok::annot_decltype:
5174 case tok::kw_constexpr:
5176 // C++20 consteval and constinit.
5177 case tok::kw_consteval:
5178 case tok::kw_constinit:
5181 case tok::kw__Atomic:
5184 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5186 return getLangOpts().ObjC;
5189 case tok::annot_typename:
5190 return !DisambiguatingWithExpression ||
5191 !isStartOfObjCClassMessageMissingOpenBracket();
5193 // placeholder-type-specifier
5194 case tok::annot_template_id: {
5195 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
5196 return TemplateId->Kind == TNK_Concept_template &&
5197 (NextToken().is(tok::kw_auto) || NextToken().is(tok::kw_decltype));
5200 case tok::kw___declspec:
5201 case tok::kw___cdecl:
5202 case tok::kw___stdcall:
5203 case tok::kw___fastcall:
5204 case tok::kw___thiscall:
5205 case tok::kw___regcall:
5206 case tok::kw___vectorcall:
5208 case tok::kw___sptr:
5209 case tok::kw___uptr:
5210 case tok::kw___ptr64:
5211 case tok::kw___ptr32:
5212 case tok::kw___forceinline:
5213 case tok::kw___pascal:
5214 case tok::kw___unaligned:
5216 case tok::kw__Nonnull:
5217 case tok::kw__Nullable:
5218 case tok::kw__Null_unspecified:
5220 case tok::kw___kindof:
5222 case tok::kw___private:
5223 case tok::kw___local:
5224 case tok::kw___global:
5225 case tok::kw___constant:
5226 case tok::kw___generic:
5227 case tok::kw___read_only:
5228 case tok::kw___read_write:
5229 case tok::kw___write_only:
5230 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5231 #include "clang/Basic/OpenCLImageTypes.def"
5235 case tok::kw_private:
5236 return getLangOpts().OpenCL;
5240 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
5241 TentativeParsingAction TPA(*this);
5243 // Parse the C++ scope specifier.
5245 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
5246 /*EnteringContext=*/true)) {
5251 // Parse the constructor name.
5252 if (Tok.is(tok::identifier)) {
5253 // We already know that we have a constructor name; just consume
5256 } else if (Tok.is(tok::annot_template_id)) {
5257 ConsumeAnnotationToken();
5263 // There may be attributes here, appertaining to the constructor name or type
5264 // we just stepped past.
5265 SkipCXX11Attributes();
5267 // Current class name must be followed by a left parenthesis.
5268 if (Tok.isNot(tok::l_paren)) {
5274 // A right parenthesis, or ellipsis followed by a right parenthesis signals
5275 // that we have a constructor.
5276 if (Tok.is(tok::r_paren) ||
5277 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
5282 // A C++11 attribute here signals that we have a constructor, and is an
5283 // attribute on the first constructor parameter.
5284 if (getLangOpts().CPlusPlus11 &&
5285 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5286 /*OuterMightBeMessageSend*/ true)) {
5291 // If we need to, enter the specified scope.
5292 DeclaratorScopeObj DeclScopeObj(*this, SS);
5293 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
5294 DeclScopeObj.EnterDeclaratorScope();
5296 // Optionally skip Microsoft attributes.
5297 ParsedAttributes Attrs(AttrFactory);
5298 MaybeParseMicrosoftAttributes(Attrs);
5300 // Check whether the next token(s) are part of a declaration
5301 // specifier, in which case we have the start of a parameter and,
5302 // therefore, we know that this is a constructor.
5303 bool IsConstructor = false;
5304 if (isDeclarationSpecifier())
5305 IsConstructor = true;
5306 else if (Tok.is(tok::identifier) ||
5307 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5308 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5309 // This might be a parenthesized member name, but is more likely to
5310 // be a constructor declaration with an invalid argument type. Keep
5312 if (Tok.is(tok::annot_cxxscope))
5313 ConsumeAnnotationToken();
5316 // If this is not a constructor, we must be parsing a declarator,
5317 // which must have one of the following syntactic forms (see the
5318 // grammar extract at the start of ParseDirectDeclarator):
5319 switch (Tok.getKind()) {
5324 // C(X [ [attribute]]);
5325 case tok::coloncolon:
5328 // Assume this isn't a constructor, rather than assuming it's a
5329 // constructor with an unnamed parameter of an ill-formed type.
5335 // Skip past the right-paren and any following attributes to get to
5336 // the function body or trailing-return-type.
5338 SkipCXX11Attributes();
5340 if (DeductionGuide) {
5341 // C(X) -> ... is a deduction guide.
5342 IsConstructor = Tok.is(tok::arrow);
5345 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
5346 // Assume these were meant to be constructors:
5347 // C(X) : (the name of a bit-field cannot be parenthesized).
5348 // C(X) try (this is otherwise ill-formed).
5349 IsConstructor = true;
5351 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
5352 // If we have a constructor name within the class definition,
5353 // assume these were meant to be constructors:
5356 // ... because otherwise we would be declaring a non-static data
5357 // member that is ill-formed because it's of the same type as its
5358 // surrounding class.
5360 // FIXME: We can actually do this whether or not the name is qualified,
5361 // because if it is qualified in this context it must be being used as
5362 // a constructor name.
5363 // currently, so we're somewhat conservative here.
5364 IsConstructor = IsUnqualified;
5369 IsConstructor = true;
5375 return IsConstructor;
5378 /// ParseTypeQualifierListOpt
5379 /// type-qualifier-list: [C99 6.7.5]
5381 /// [vendor] attributes
5382 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5383 /// type-qualifier-list type-qualifier
5384 /// [vendor] type-qualifier-list attributes
5385 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5386 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
5387 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
5388 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5389 /// AttrRequirements bitmask values.
5390 void Parser::ParseTypeQualifierListOpt(
5391 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5392 bool IdentifierRequired,
5393 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
5394 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
5395 isCXX11AttributeSpecifier()) {
5396 ParsedAttributesWithRange attrs(AttrFactory);
5397 ParseCXX11Attributes(attrs);
5398 DS.takeAttributesFrom(attrs);
5401 SourceLocation EndLoc;
5404 bool isInvalid = false;
5405 const char *PrevSpec = nullptr;
5406 unsigned DiagID = 0;
5407 SourceLocation Loc = Tok.getLocation();
5409 switch (Tok.getKind()) {
5410 case tok::code_completion:
5411 if (CodeCompletionHandler)
5412 (*CodeCompletionHandler)();
5414 Actions.CodeCompleteTypeQualifiers(DS);
5415 return cutOffParsing();
5418 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
5421 case tok::kw_volatile:
5422 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5425 case tok::kw_restrict:
5426 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5429 case tok::kw__Atomic:
5431 goto DoneWithTypeQuals;
5432 if (!getLangOpts().C11)
5433 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
5434 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5438 // OpenCL qualifiers:
5439 case tok::kw_private:
5440 if (!getLangOpts().OpenCL)
5441 goto DoneWithTypeQuals;
5443 case tok::kw___private:
5444 case tok::kw___global:
5445 case tok::kw___local:
5446 case tok::kw___constant:
5447 case tok::kw___generic:
5448 case tok::kw___read_only:
5449 case tok::kw___write_only:
5450 case tok::kw___read_write:
5451 ParseOpenCLQualifiers(DS.getAttributes());
5454 case tok::kw___unaligned:
5455 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5458 case tok::kw___uptr:
5459 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
5460 // with the MS modifier keyword.
5461 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
5462 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5463 if (TryKeywordIdentFallback(false))
5467 case tok::kw___sptr:
5469 case tok::kw___ptr64:
5470 case tok::kw___ptr32:
5471 case tok::kw___cdecl:
5472 case tok::kw___stdcall:
5473 case tok::kw___fastcall:
5474 case tok::kw___thiscall:
5475 case tok::kw___regcall:
5476 case tok::kw___vectorcall:
5477 if (AttrReqs & AR_DeclspecAttributesParsed) {
5478 ParseMicrosoftTypeAttributes(DS.getAttributes());
5481 goto DoneWithTypeQuals;
5482 case tok::kw___pascal:
5483 if (AttrReqs & AR_VendorAttributesParsed) {
5484 ParseBorlandTypeAttributes(DS.getAttributes());
5487 goto DoneWithTypeQuals;
5489 // Nullability type specifiers.
5490 case tok::kw__Nonnull:
5491 case tok::kw__Nullable:
5492 case tok::kw__Null_unspecified:
5493 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5496 // Objective-C 'kindof' types.
5497 case tok::kw___kindof:
5498 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
5499 nullptr, 0, ParsedAttr::AS_Keyword);
5500 (void)ConsumeToken();
5503 case tok::kw___attribute:
5504 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5505 // When GNU attributes are expressly forbidden, diagnose their usage.
5506 Diag(Tok, diag::err_attributes_not_allowed);
5508 // Parse the attributes even if they are rejected to ensure that error
5509 // recovery is graceful.
5510 if (AttrReqs & AR_GNUAttributesParsed ||
5511 AttrReqs & AR_GNUAttributesParsedAndRejected) {
5512 ParseGNUAttributes(DS.getAttributes());
5513 continue; // do *not* consume the next token!
5515 // otherwise, FALL THROUGH!
5519 // If this is not a type-qualifier token, we're done reading type
5520 // qualifiers. First verify that DeclSpec's are consistent.
5521 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
5522 if (EndLoc.isValid())
5523 DS.SetRangeEnd(EndLoc);
5527 // If the specifier combination wasn't legal, issue a diagnostic.
5529 assert(PrevSpec && "Method did not return previous specifier!");
5530 Diag(Tok, DiagID) << PrevSpec;
5532 EndLoc = ConsumeToken();
5536 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
5538 void Parser::ParseDeclarator(Declarator &D) {
5539 /// This implements the 'declarator' production in the C grammar, then checks
5540 /// for well-formedness and issues diagnostics.
5541 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5544 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
5545 DeclaratorContext TheContext) {
5546 if (Kind == tok::star || Kind == tok::caret)
5549 if (Kind == tok::kw_pipe &&
5550 ((Lang.OpenCL && Lang.OpenCLVersion >= 200) || Lang.OpenCLCPlusPlus))
5553 if (!Lang.CPlusPlus)
5556 if (Kind == tok::amp)
5559 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5560 // But we must not parse them in conversion-type-ids and new-type-ids, since
5561 // those can be legitimately followed by a && operator.
5562 // (The same thing can in theory happen after a trailing-return-type, but
5563 // since those are a C++11 feature, there is no rejects-valid issue there.)
5564 if (Kind == tok::ampamp)
5565 return Lang.CPlusPlus11 ||
5566 (TheContext != DeclaratorContext::ConversionIdContext &&
5567 TheContext != DeclaratorContext::CXXNewContext);
5572 // Indicates whether the given declarator is a pipe declarator.
5573 static bool isPipeDeclerator(const Declarator &D) {
5574 const unsigned NumTypes = D.getNumTypeObjects();
5576 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5577 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5583 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5584 /// is parsed by the function passed to it. Pass null, and the direct-declarator
5585 /// isn't parsed at all, making this function effectively parse the C++
5586 /// ptr-operator production.
5588 /// If the grammar of this construct is extended, matching changes must also be
5589 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5590 /// isConstructorDeclarator.
5592 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5593 /// [C] pointer[opt] direct-declarator
5594 /// [C++] direct-declarator
5595 /// [C++] ptr-operator declarator
5597 /// pointer: [C99 6.7.5]
5598 /// '*' type-qualifier-list[opt]
5599 /// '*' type-qualifier-list[opt] pointer
5602 /// '*' cv-qualifier-seq[opt]
5605 /// [GNU] '&' restrict[opt] attributes[opt]
5606 /// [GNU?] '&&' restrict[opt] attributes[opt]
5607 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
5608 void Parser::ParseDeclaratorInternal(Declarator &D,
5609 DirectDeclParseFunction DirectDeclParser) {
5610 if (Diags.hasAllExtensionsSilenced())
5613 // C++ member pointers start with a '::' or a nested-name.
5614 // Member pointers get special handling, since there's no place for the
5615 // scope spec in the generic path below.
5616 if (getLangOpts().CPlusPlus &&
5617 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
5618 (Tok.is(tok::identifier) &&
5619 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
5620 Tok.is(tok::annot_cxxscope))) {
5621 bool EnteringContext =
5622 D.getContext() == DeclaratorContext::FileContext ||
5623 D.getContext() == DeclaratorContext::MemberContext;
5625 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
5627 if (SS.isNotEmpty()) {
5628 if (Tok.isNot(tok::star)) {
5629 // The scope spec really belongs to the direct-declarator.
5630 if (D.mayHaveIdentifier())
5631 D.getCXXScopeSpec() = SS;
5633 AnnotateScopeToken(SS, true);
5635 if (DirectDeclParser)
5636 (this->*DirectDeclParser)(D);
5640 SourceLocation Loc = ConsumeToken();
5642 DeclSpec DS(AttrFactory);
5643 ParseTypeQualifierListOpt(DS);
5644 D.ExtendWithDeclSpec(DS);
5646 // Recurse to parse whatever is left.
5647 ParseDeclaratorInternal(D, DirectDeclParser);
5649 // Sema will have to catch (syntactically invalid) pointers into global
5650 // scope. It has to catch pointers into namespace scope anyway.
5651 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
5652 SS, DS.getTypeQualifiers(), DS.getEndLoc()),
5653 std::move(DS.getAttributes()),
5654 /* Don't replace range end. */ SourceLocation());
5659 tok::TokenKind Kind = Tok.getKind();
5661 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
5662 DeclSpec DS(AttrFactory);
5663 ParseTypeQualifierListOpt(DS);
5666 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
5667 std::move(DS.getAttributes()), SourceLocation());
5670 // Not a pointer, C++ reference, or block.
5671 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
5672 if (DirectDeclParser)
5673 (this->*DirectDeclParser)(D);
5677 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5678 // '&&' -> rvalue reference
5679 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
5682 if (Kind == tok::star || Kind == tok::caret) {
5684 DeclSpec DS(AttrFactory);
5686 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5687 // C++11 attributes are allowed.
5688 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
5689 ((D.getContext() != DeclaratorContext::CXXNewContext)
5690 ? AR_GNUAttributesParsed
5691 : AR_GNUAttributesParsedAndRejected);
5692 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
5693 D.ExtendWithDeclSpec(DS);
5695 // Recursively parse the declarator.
5696 ParseDeclaratorInternal(D, DirectDeclParser);
5697 if (Kind == tok::star)
5698 // Remember that we parsed a pointer type, and remember the type-quals.
5699 D.AddTypeInfo(DeclaratorChunk::getPointer(
5700 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5701 DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
5702 DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
5703 std::move(DS.getAttributes()), SourceLocation());
5705 // Remember that we parsed a Block type, and remember the type-quals.
5707 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
5708 std::move(DS.getAttributes()), SourceLocation());
5711 DeclSpec DS(AttrFactory);
5713 // Complain about rvalue references in C++03, but then go on and build
5715 if (Kind == tok::ampamp)
5716 Diag(Loc, getLangOpts().CPlusPlus11 ?
5717 diag::warn_cxx98_compat_rvalue_reference :
5718 diag::ext_rvalue_reference);
5720 // GNU-style and C++11 attributes are allowed here, as is restrict.
5721 ParseTypeQualifierListOpt(DS);
5722 D.ExtendWithDeclSpec(DS);
5724 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5725 // cv-qualifiers are introduced through the use of a typedef or of a
5726 // template type argument, in which case the cv-qualifiers are ignored.
5727 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5728 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5729 Diag(DS.getConstSpecLoc(),
5730 diag::err_invalid_reference_qualifier_application) << "const";
5731 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5732 Diag(DS.getVolatileSpecLoc(),
5733 diag::err_invalid_reference_qualifier_application) << "volatile";
5734 // 'restrict' is permitted as an extension.
5735 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5736 Diag(DS.getAtomicSpecLoc(),
5737 diag::err_invalid_reference_qualifier_application) << "_Atomic";
5740 // Recursively parse the declarator.
5741 ParseDeclaratorInternal(D, DirectDeclParser);
5743 if (D.getNumTypeObjects() > 0) {
5744 // C++ [dcl.ref]p4: There shall be no references to references.
5745 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5746 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5747 if (const IdentifierInfo *II = D.getIdentifier())
5748 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5751 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5754 // Once we've complained about the reference-to-reference, we
5755 // can go ahead and build the (technically ill-formed)
5756 // declarator: reference collapsing will take care of it.
5760 // Remember that we parsed a reference type.
5761 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
5763 std::move(DS.getAttributes()), SourceLocation());
5767 // When correcting from misplaced brackets before the identifier, the location
5768 // is saved inside the declarator so that other diagnostic messages can use
5769 // them. This extracts and returns that location, or returns the provided
5770 // location if a stored location does not exist.
5771 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5772 SourceLocation Loc) {
5773 if (D.getName().StartLocation.isInvalid() &&
5774 D.getName().EndLocation.isValid())
5775 return D.getName().EndLocation;
5780 /// ParseDirectDeclarator
5781 /// direct-declarator: [C99 6.7.5]
5782 /// [C99] identifier
5783 /// '(' declarator ')'
5784 /// [GNU] '(' attributes declarator ')'
5785 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5786 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5787 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5788 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5789 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5790 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5791 /// attribute-specifier-seq[opt]
5792 /// direct-declarator '(' parameter-type-list ')'
5793 /// direct-declarator '(' identifier-list[opt] ')'
5794 /// [GNU] direct-declarator '(' parameter-forward-declarations
5795 /// parameter-type-list[opt] ')'
5796 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
5797 /// cv-qualifier-seq[opt] exception-specification[opt]
5798 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5799 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5800 /// ref-qualifier[opt] exception-specification[opt]
5801 /// [C++] declarator-id
5802 /// [C++11] declarator-id attribute-specifier-seq[opt]
5804 /// declarator-id: [C++ 8]
5805 /// '...'[opt] id-expression
5806 /// '::'[opt] nested-name-specifier[opt] type-name
5808 /// id-expression: [C++ 5.1]
5812 /// unqualified-id: [C++ 5.1]
5814 /// operator-function-id
5815 /// conversion-function-id
5819 /// C++17 adds the following, which we also handle here:
5821 /// simple-declaration:
5822 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5824 /// Note, any additional constructs added here may need corresponding changes
5825 /// in isConstructorDeclarator.
5826 void Parser::ParseDirectDeclarator(Declarator &D) {
5827 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
5829 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
5830 // This might be a C++17 structured binding.
5831 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5832 D.getCXXScopeSpec().isEmpty())
5833 return ParseDecompositionDeclarator(D);
5835 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5836 // this context it is a bitfield. Also in range-based for statement colon
5837 // may delimit for-range-declaration.
5838 ColonProtectionRAIIObject X(
5839 *this, D.getContext() == DeclaratorContext::MemberContext ||
5840 (D.getContext() == DeclaratorContext::ForContext &&
5841 getLangOpts().CPlusPlus11));
5843 // ParseDeclaratorInternal might already have parsed the scope.
5844 if (D.getCXXScopeSpec().isEmpty()) {
5845 bool EnteringContext =
5846 D.getContext() == DeclaratorContext::FileContext ||
5847 D.getContext() == DeclaratorContext::MemberContext;
5848 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
5852 if (D.getCXXScopeSpec().isValid()) {
5853 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5854 D.getCXXScopeSpec()))
5855 // Change the declaration context for name lookup, until this function
5856 // is exited (and the declarator has been parsed).
5857 DeclScopeObj.EnterDeclaratorScope();
5858 else if (getObjCDeclContext()) {
5859 // Ensure that we don't interpret the next token as an identifier when
5860 // dealing with declarations in an Objective-C container.
5861 D.SetIdentifier(nullptr, Tok.getLocation());
5862 D.setInvalidType(true);
5864 goto PastIdentifier;
5868 // C++0x [dcl.fct]p14:
5869 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5870 // parameter-declaration-clause without a preceding comma. In this case,
5871 // the ellipsis is parsed as part of the abstract-declarator if the type
5872 // of the parameter either names a template parameter pack that has not
5873 // been expanded or contains auto; otherwise, it is parsed as part of the
5874 // parameter-declaration-clause.
5875 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
5876 !((D.getContext() == DeclaratorContext::PrototypeContext ||
5877 D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5878 D.getContext() == DeclaratorContext::BlockLiteralContext) &&
5879 NextToken().is(tok::r_paren) &&
5880 !D.hasGroupingParens() &&
5881 !Actions.containsUnexpandedParameterPacks(D) &&
5882 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
5883 SourceLocation EllipsisLoc = ConsumeToken();
5884 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
5885 // The ellipsis was put in the wrong place. Recover, and explain to
5886 // the user what they should have done.
5888 if (EllipsisLoc.isValid())
5889 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5892 D.setEllipsisLoc(EllipsisLoc);
5894 // The ellipsis can't be followed by a parenthesized declarator. We
5895 // check for that in ParseParenDeclarator, after we have disambiguated
5896 // the l_paren token.
5899 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5901 // We found something that indicates the start of an unqualified-id.
5902 // Parse that unqualified-id.
5903 bool AllowConstructorName;
5904 bool AllowDeductionGuide;
5905 if (D.getDeclSpec().hasTypeSpecifier()) {
5906 AllowConstructorName = false;
5907 AllowDeductionGuide = false;
5908 } else if (D.getCXXScopeSpec().isSet()) {
5909 AllowConstructorName =
5910 (D.getContext() == DeclaratorContext::FileContext ||
5911 D.getContext() == DeclaratorContext::MemberContext);
5912 AllowDeductionGuide = false;
5914 AllowConstructorName =
5915 (D.getContext() == DeclaratorContext::MemberContext);
5916 AllowDeductionGuide =
5917 (D.getContext() == DeclaratorContext::FileContext ||
5918 D.getContext() == DeclaratorContext::MemberContext);
5921 bool HadScope = D.getCXXScopeSpec().isValid();
5922 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5923 /*EnteringContext=*/true,
5924 /*AllowDestructorName=*/true, AllowConstructorName,
5925 AllowDeductionGuide, nullptr, nullptr,
5927 // Once we're past the identifier, if the scope was bad, mark the
5928 // whole declarator bad.
5929 D.getCXXScopeSpec().isInvalid()) {
5930 D.SetIdentifier(nullptr, Tok.getLocation());
5931 D.setInvalidType(true);
5933 // ParseUnqualifiedId might have parsed a scope specifier during error
5934 // recovery. If it did so, enter that scope.
5935 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5936 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5937 D.getCXXScopeSpec()))
5938 DeclScopeObj.EnterDeclaratorScope();
5940 // Parsed the unqualified-id; update range information and move along.
5941 if (D.getSourceRange().getBegin().isInvalid())
5942 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5943 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
5945 goto PastIdentifier;
5948 if (D.getCXXScopeSpec().isNotEmpty()) {
5949 // We have a scope specifier but no following unqualified-id.
5950 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5951 diag::err_expected_unqualified_id)
5953 D.SetIdentifier(nullptr, Tok.getLocation());
5954 goto PastIdentifier;
5956 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
5957 assert(!getLangOpts().CPlusPlus &&
5958 "There's a C++-specific check for tok::identifier above");
5959 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5960 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5961 D.SetRangeEnd(Tok.getLocation());
5963 goto PastIdentifier;
5964 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5965 // We're not allowed an identifier here, but we got one. Try to figure out
5966 // if the user was trying to attach a name to the type, or whether the name
5967 // is some unrelated trailing syntax.
5968 bool DiagnoseIdentifier = false;
5969 if (D.hasGroupingParens())
5970 // An identifier within parens is unlikely to be intended to be anything
5971 // other than a name being "declared".
5972 DiagnoseIdentifier = true;
5973 else if (D.getContext() == DeclaratorContext::TemplateArgContext)
5974 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5975 DiagnoseIdentifier =
5976 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
5977 else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5978 D.getContext() == DeclaratorContext::AliasTemplateContext)
5979 // The most likely error is that the ';' was forgotten.
5980 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
5981 else if ((D.getContext() == DeclaratorContext::TrailingReturnContext ||
5982 D.getContext() == DeclaratorContext::TrailingReturnVarContext) &&
5983 !isCXX11VirtSpecifier(Tok))
5984 DiagnoseIdentifier = NextToken().isOneOf(
5985 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5986 if (DiagnoseIdentifier) {
5987 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5988 << FixItHint::CreateRemoval(Tok.getLocation());
5989 D.SetIdentifier(nullptr, Tok.getLocation());
5991 goto PastIdentifier;
5995 if (Tok.is(tok::l_paren)) {
5996 // If this might be an abstract-declarator followed by a direct-initializer,
5997 // check whether this is a valid declarator chunk. If it can't be, assume
5998 // that it's an initializer instead.
5999 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
6000 RevertingTentativeParsingAction PA(*this);
6001 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
6003 D.SetIdentifier(nullptr, Tok.getLocation());
6004 goto PastIdentifier;
6008 // direct-declarator: '(' declarator ')'
6009 // direct-declarator: '(' attributes declarator ')'
6010 // Example: 'char (*X)' or 'int (*XX)(void)'
6011 ParseParenDeclarator(D);
6013 // If the declarator was parenthesized, we entered the declarator
6014 // scope when parsing the parenthesized declarator, then exited
6015 // the scope already. Re-enter the scope, if we need to.
6016 if (D.getCXXScopeSpec().isSet()) {
6017 // If there was an error parsing parenthesized declarator, declarator
6018 // scope may have been entered before. Don't do it again.
6019 if (!D.isInvalidType() &&
6020 Actions.ShouldEnterDeclaratorScope(getCurScope(),
6021 D.getCXXScopeSpec()))
6022 // Change the declaration context for name lookup, until this function
6023 // is exited (and the declarator has been parsed).
6024 DeclScopeObj.EnterDeclaratorScope();
6026 } else if (D.mayOmitIdentifier()) {
6027 // This could be something simple like "int" (in which case the declarator
6028 // portion is empty), if an abstract-declarator is allowed.
6029 D.SetIdentifier(nullptr, Tok.getLocation());
6031 // The grammar for abstract-pack-declarator does not allow grouping parens.
6032 // FIXME: Revisit this once core issue 1488 is resolved.
6033 if (D.hasEllipsis() && D.hasGroupingParens())
6034 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
6035 diag::ext_abstract_pack_declarator_parens);
6037 if (Tok.getKind() == tok::annot_pragma_parser_crash)
6039 if (Tok.is(tok::l_square))
6040 return ParseMisplacedBracketDeclarator(D);
6041 if (D.getContext() == DeclaratorContext::MemberContext) {
6042 // Objective-C++: Detect C++ keywords and try to prevent further errors by
6043 // treating these keyword as valid member names.
6044 if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
6045 Tok.getIdentifierInfo() &&
6046 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
6047 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6048 diag::err_expected_member_name_or_semi_objcxx_keyword)
6049 << Tok.getIdentifierInfo()
6050 << (D.getDeclSpec().isEmpty() ? SourceRange()
6051 : D.getDeclSpec().getSourceRange());
6052 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
6053 D.SetRangeEnd(Tok.getLocation());
6055 goto PastIdentifier;
6057 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6058 diag::err_expected_member_name_or_semi)
6059 << (D.getDeclSpec().isEmpty() ? SourceRange()
6060 : D.getDeclSpec().getSourceRange());
6061 } else if (getLangOpts().CPlusPlus) {
6062 if (Tok.isOneOf(tok::period, tok::arrow))
6063 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
6065 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
6066 if (Tok.isAtStartOfLine() && Loc.isValid())
6067 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
6068 << getLangOpts().CPlusPlus;
6070 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6071 diag::err_expected_unqualified_id)
6072 << getLangOpts().CPlusPlus;
6075 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6076 diag::err_expected_either)
6077 << tok::identifier << tok::l_paren;
6079 D.SetIdentifier(nullptr, Tok.getLocation());
6080 D.setInvalidType(true);
6084 assert(D.isPastIdentifier() &&
6085 "Haven't past the location of the identifier yet?");
6087 // Don't parse attributes unless we have parsed an unparenthesized name.
6088 if (D.hasName() && !D.getNumTypeObjects())
6089 MaybeParseCXX11Attributes(D);
6092 if (Tok.is(tok::l_paren)) {
6093 bool IsFunctionDeclaration = D.isFunctionDeclaratorAFunctionDeclaration();
6094 // Enter function-declaration scope, limiting any declarators to the
6095 // function prototype scope, including parameter declarators.
6096 ParseScope PrototypeScope(this,
6097 Scope::FunctionPrototypeScope|Scope::DeclScope|
6098 (IsFunctionDeclaration
6099 ? Scope::FunctionDeclarationScope : 0));
6101 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
6102 // In such a case, check if we actually have a function declarator; if it
6103 // is not, the declarator has been fully parsed.
6104 bool IsAmbiguous = false;
6105 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
6106 // The name of the declarator, if any, is tentatively declared within
6107 // a possible direct initializer.
6108 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
6109 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
6110 TentativelyDeclaredIdentifiers.pop_back();
6111 if (!IsFunctionDecl)
6114 ParsedAttributes attrs(AttrFactory);
6115 BalancedDelimiterTracker T(*this, tok::l_paren);
6117 if (IsFunctionDeclaration)
6118 Actions.ActOnStartFunctionDeclarationDeclarator(D,
6119 TemplateParameterDepth);
6120 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
6121 if (IsFunctionDeclaration)
6122 Actions.ActOnFinishFunctionDeclarationDeclarator(D);
6123 PrototypeScope.Exit();
6124 } else if (Tok.is(tok::l_square)) {
6125 ParseBracketDeclarator(D);
6126 } else if (Tok.is(tok::kw_requires) && D.hasGroupingParens()) {
6127 // This declarator is declaring a function, but the requires clause is
6128 // in the wrong place:
6129 // void (f() requires true);
6131 // void f() requires true;
6133 // void (f()) requires true;
6134 Diag(Tok, diag::err_requires_clause_inside_parens);
6136 ExprResult TrailingRequiresClause = Actions.CorrectDelayedTyposInExpr(
6137 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
6138 if (TrailingRequiresClause.isUsable() && D.isFunctionDeclarator() &&
6139 !D.hasTrailingRequiresClause())
6140 // We're already ill-formed if we got here but we'll accept it anyway.
6141 D.setTrailingRequiresClause(TrailingRequiresClause.get());
6148 void Parser::ParseDecompositionDeclarator(Declarator &D) {
6149 assert(Tok.is(tok::l_square));
6151 // If this doesn't look like a structured binding, maybe it's a misplaced
6152 // array declarator.
6153 // FIXME: Consume the l_square first so we don't need extra lookahead for
6155 if (!(NextToken().is(tok::identifier) &&
6156 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
6157 !(NextToken().is(tok::r_square) &&
6158 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
6159 return ParseMisplacedBracketDeclarator(D);
6161 BalancedDelimiterTracker T(*this, tok::l_square);
6164 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
6165 while (Tok.isNot(tok::r_square)) {
6166 if (!Bindings.empty()) {
6167 if (Tok.is(tok::comma))
6170 if (Tok.is(tok::identifier)) {
6171 SourceLocation EndLoc = getEndOfPreviousToken();
6172 Diag(EndLoc, diag::err_expected)
6173 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
6175 Diag(Tok, diag::err_expected_comma_or_rsquare);
6178 SkipUntil(tok::r_square, tok::comma, tok::identifier,
6179 StopAtSemi | StopBeforeMatch);
6180 if (Tok.is(tok::comma))
6182 else if (Tok.isNot(tok::identifier))
6187 if (Tok.isNot(tok::identifier)) {
6188 Diag(Tok, diag::err_expected) << tok::identifier;
6192 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
6196 if (Tok.isNot(tok::r_square))
6197 // We've already diagnosed a problem here.
6200 // C++17 does not allow the identifier-list in a structured binding
6202 if (Bindings.empty())
6203 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
6208 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
6209 T.getCloseLocation());
6212 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
6213 /// only called before the identifier, so these are most likely just grouping
6214 /// parens for precedence. If we find that these are actually function
6215 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
6217 /// direct-declarator:
6218 /// '(' declarator ')'
6219 /// [GNU] '(' attributes declarator ')'
6220 /// direct-declarator '(' parameter-type-list ')'
6221 /// direct-declarator '(' identifier-list[opt] ')'
6222 /// [GNU] direct-declarator '(' parameter-forward-declarations
6223 /// parameter-type-list[opt] ')'
6225 void Parser::ParseParenDeclarator(Declarator &D) {
6226 BalancedDelimiterTracker T(*this, tok::l_paren);
6229 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
6231 // Eat any attributes before we look at whether this is a grouping or function
6232 // declarator paren. If this is a grouping paren, the attribute applies to
6233 // the type being built up, for example:
6234 // int (__attribute__(()) *x)(long y)
6235 // If this ends up not being a grouping paren, the attribute applies to the
6236 // first argument, for example:
6237 // int (__attribute__(()) int x)
6238 // In either case, we need to eat any attributes to be able to determine what
6239 // sort of paren this is.
6241 ParsedAttributes attrs(AttrFactory);
6242 bool RequiresArg = false;
6243 if (Tok.is(tok::kw___attribute)) {
6244 ParseGNUAttributes(attrs);
6246 // We require that the argument list (if this is a non-grouping paren) be
6247 // present even if the attribute list was empty.
6251 // Eat any Microsoft extensions.
6252 ParseMicrosoftTypeAttributes(attrs);
6254 // Eat any Borland extensions.
6255 if (Tok.is(tok::kw___pascal))
6256 ParseBorlandTypeAttributes(attrs);
6258 // If we haven't past the identifier yet (or where the identifier would be
6259 // stored, if this is an abstract declarator), then this is probably just
6260 // grouping parens. However, if this could be an abstract-declarator, then
6261 // this could also be the start of function arguments (consider 'void()').
6264 if (!D.mayOmitIdentifier()) {
6265 // If this can't be an abstract-declarator, this *must* be a grouping
6266 // paren, because we haven't seen the identifier yet.
6268 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
6269 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
6270 NextToken().is(tok::r_paren)) || // C++ int(...)
6271 isDeclarationSpecifier() || // 'int(int)' is a function.
6272 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
6273 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
6274 // considered to be a type, not a K&R identifier-list.
6277 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6281 // If this is a grouping paren, handle:
6282 // direct-declarator: '(' declarator ')'
6283 // direct-declarator: '(' attributes declarator ')'
6285 SourceLocation EllipsisLoc = D.getEllipsisLoc();
6286 D.setEllipsisLoc(SourceLocation());
6288 bool hadGroupingParens = D.hasGroupingParens();
6289 D.setGroupingParens(true);
6290 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6294 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
6295 std::move(attrs), T.getCloseLocation());
6297 D.setGroupingParens(hadGroupingParens);
6299 // An ellipsis cannot be placed outside parentheses.
6300 if (EllipsisLoc.isValid())
6301 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6306 // Okay, if this wasn't a grouping paren, it must be the start of a function
6307 // argument list. Recognize that this declarator will never have an
6308 // identifier (and remember where it would have been), then call into
6309 // ParseFunctionDeclarator to handle of argument list.
6310 D.SetIdentifier(nullptr, Tok.getLocation());
6312 // Enter function-declaration scope, limiting any declarators to the
6313 // function prototype scope, including parameter declarators.
6314 ParseScope PrototypeScope(this,
6315 Scope::FunctionPrototypeScope | Scope::DeclScope |
6316 (D.isFunctionDeclaratorAFunctionDeclaration()
6317 ? Scope::FunctionDeclarationScope : 0));
6318 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
6319 PrototypeScope.Exit();
6322 void Parser::InitCXXThisScopeForDeclaratorIfRelevant(
6323 const Declarator &D, const DeclSpec &DS,
6324 llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope) {
6325 // C++11 [expr.prim.general]p3:
6326 // If a declaration declares a member function or member function
6327 // template of a class X, the expression this is a prvalue of type
6328 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6329 // and the end of the function-definition, member-declarator, or
6331 // FIXME: currently, "static" case isn't handled correctly.
6332 bool IsCXX11MemberFunction = getLangOpts().CPlusPlus11 &&
6333 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6334 (D.getContext() == DeclaratorContext::MemberContext
6335 ? !D.getDeclSpec().isFriendSpecified()
6336 : D.getContext() == DeclaratorContext::FileContext &&
6337 D.getCXXScopeSpec().isValid() &&
6338 Actions.CurContext->isRecord());
6339 if (!IsCXX11MemberFunction)
6342 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
6343 if (D.getDeclSpec().hasConstexprSpecifier() && !getLangOpts().CPlusPlus14)
6345 // FIXME: Collect C++ address spaces.
6346 // If there are multiple different address spaces, the source is invalid.
6347 // Carry on using the first addr space for the qualifiers of 'this'.
6348 // The diagnostic will be given later while creating the function
6349 // prototype for the method.
6350 if (getLangOpts().OpenCLCPlusPlus) {
6351 for (ParsedAttr &attr : DS.getAttributes()) {
6352 LangAS ASIdx = attr.asOpenCLLangAS();
6353 if (ASIdx != LangAS::Default) {
6354 Q.addAddressSpace(ASIdx);
6359 ThisScope.emplace(Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
6360 IsCXX11MemberFunction);
6363 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
6364 /// declarator D up to a paren, which indicates that we are parsing function
6367 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
6368 /// immediately after the open paren - they should be considered to be the
6369 /// first argument of a parameter.
6371 /// If RequiresArg is true, then the first argument of the function is required
6372 /// to be present and required to not be an identifier list.
6374 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6375 /// (C++11) ref-qualifier[opt], exception-specification[opt],
6376 /// (C++11) attribute-specifier-seq[opt], (C++11) trailing-return-type[opt] and
6377 /// (C++2a) the trailing requires-clause.
6379 /// [C++11] exception-specification:
6380 /// dynamic-exception-specification
6381 /// noexcept-specification
6383 void Parser::ParseFunctionDeclarator(Declarator &D,
6384 ParsedAttributes &FirstArgAttrs,
6385 BalancedDelimiterTracker &Tracker,
6388 assert(getCurScope()->isFunctionPrototypeScope() &&
6389 "Should call from a Function scope");
6390 // lparen is already consumed!
6391 assert(D.isPastIdentifier() && "Should not call before identifier!");
6393 // This should be true when the function has typed arguments.
6394 // Otherwise, it is treated as a K&R-style function.
6395 bool HasProto = false;
6396 // Build up an array of information about the parsed arguments.
6397 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
6398 // Remember where we see an ellipsis, if any.
6399 SourceLocation EllipsisLoc;
6401 DeclSpec DS(AttrFactory);
6402 bool RefQualifierIsLValueRef = true;
6403 SourceLocation RefQualifierLoc;
6404 ExceptionSpecificationType ESpecType = EST_None;
6405 SourceRange ESpecRange;
6406 SmallVector<ParsedType, 2> DynamicExceptions;
6407 SmallVector<SourceRange, 2> DynamicExceptionRanges;
6408 ExprResult NoexceptExpr;
6409 CachedTokens *ExceptionSpecTokens = nullptr;
6410 ParsedAttributesWithRange FnAttrs(AttrFactory);
6411 TypeResult TrailingReturnType;
6413 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6414 EndLoc is the end location for the function declarator.
6415 They differ for trailing return types. */
6416 SourceLocation StartLoc, LocalEndLoc, EndLoc;
6417 SourceLocation LParenLoc, RParenLoc;
6418 LParenLoc = Tracker.getOpenLocation();
6419 StartLoc = LParenLoc;
6421 if (isFunctionDeclaratorIdentifierList()) {
6423 Diag(Tok, diag::err_argument_required_after_attribute);
6425 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6427 Tracker.consumeClose();
6428 RParenLoc = Tracker.getCloseLocation();
6429 LocalEndLoc = RParenLoc;
6432 // If there are attributes following the identifier list, parse them and
6434 MaybeParseCXX11Attributes(FnAttrs);
6435 ProhibitAttributes(FnAttrs);
6437 if (Tok.isNot(tok::r_paren))
6438 ParseParameterDeclarationClause(D.getContext(), FirstArgAttrs, ParamInfo,
6440 else if (RequiresArg)
6441 Diag(Tok, diag::err_argument_required_after_attribute);
6443 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6444 || getLangOpts().OpenCL;
6446 // If we have the closing ')', eat it.
6447 Tracker.consumeClose();
6448 RParenLoc = Tracker.getCloseLocation();
6449 LocalEndLoc = RParenLoc;
6452 if (getLangOpts().CPlusPlus) {
6453 // FIXME: Accept these components in any order, and produce fixits to
6454 // correct the order if the user gets it wrong. Ideally we should deal
6455 // with the pure-specifier in the same way.
6457 // Parse cv-qualifier-seq[opt].
6458 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
6459 /*AtomicAllowed*/ false,
6460 /*IdentifierRequired=*/false,
6461 llvm::function_ref<void()>([&]() {
6462 Actions.CodeCompleteFunctionQualifiers(DS, D);
6464 if (!DS.getSourceRange().getEnd().isInvalid()) {
6465 EndLoc = DS.getSourceRange().getEnd();
6468 // Parse ref-qualifier[opt].
6469 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
6470 EndLoc = RefQualifierLoc;
6472 llvm::Optional<Sema::CXXThisScopeRAII> ThisScope;
6473 InitCXXThisScopeForDeclaratorIfRelevant(D, DS, ThisScope);
6475 // Parse exception-specification[opt].
6476 bool Delayed = D.isFirstDeclarationOfMember() &&
6477 D.isFunctionDeclaratorAFunctionDeclaration();
6478 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6479 GetLookAheadToken(0).is(tok::kw_noexcept) &&
6480 GetLookAheadToken(1).is(tok::l_paren) &&
6481 GetLookAheadToken(2).is(tok::kw_noexcept) &&
6482 GetLookAheadToken(3).is(tok::l_paren) &&
6483 GetLookAheadToken(4).is(tok::identifier) &&
6484 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6485 // HACK: We've got an exception-specification
6486 // noexcept(noexcept(swap(...)))
6488 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6489 // on a 'swap' member function. This is a libstdc++ bug; the lookup
6490 // for 'swap' will only find the function we're currently declaring,
6491 // whereas it expects to find a non-member swap through ADL. Turn off
6492 // delayed parsing to give it a chance to find what it expects.
6495 ESpecType = tryParseExceptionSpecification(Delayed,
6498 DynamicExceptionRanges,
6500 ExceptionSpecTokens);
6501 if (ESpecType != EST_None)
6502 EndLoc = ESpecRange.getEnd();
6504 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6505 // after the exception-specification.
6506 MaybeParseCXX11Attributes(FnAttrs);
6508 // Parse trailing-return-type[opt].
6509 LocalEndLoc = EndLoc;
6510 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
6511 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
6512 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
6513 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
6514 LocalEndLoc = Tok.getLocation();
6516 TrailingReturnType =
6517 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
6518 EndLoc = Range.getEnd();
6520 } else if (standardAttributesAllowed()) {
6521 MaybeParseCXX11Attributes(FnAttrs);
6525 // Collect non-parameter declarations from the prototype if this is a function
6526 // declaration. They will be moved into the scope of the function. Only do
6527 // this in C and not C++, where the decls will continue to live in the
6528 // surrounding context.
6529 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6530 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6531 !getLangOpts().CPlusPlus) {
6532 for (Decl *D : getCurScope()->decls()) {
6533 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6534 if (!ND || isa<ParmVarDecl>(ND))
6536 DeclsInPrototype.push_back(ND);
6540 // Remember that we parsed a function type, and remember the attributes.
6541 D.AddTypeInfo(DeclaratorChunk::getFunction(
6542 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6543 ParamInfo.size(), EllipsisLoc, RParenLoc,
6544 RefQualifierIsLValueRef, RefQualifierLoc,
6545 /*MutableLoc=*/SourceLocation(),
6546 ESpecType, ESpecRange, DynamicExceptions.data(),
6547 DynamicExceptionRanges.data(), DynamicExceptions.size(),
6548 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6549 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
6550 LocalEndLoc, D, TrailingReturnType, &DS),
6551 std::move(FnAttrs), EndLoc);
6554 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6555 /// true if a ref-qualifier is found.
6556 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6557 SourceLocation &RefQualifierLoc) {
6558 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
6559 Diag(Tok, getLangOpts().CPlusPlus11 ?
6560 diag::warn_cxx98_compat_ref_qualifier :
6561 diag::ext_ref_qualifier);
6563 RefQualifierIsLValueRef = Tok.is(tok::amp);
6564 RefQualifierLoc = ConsumeToken();
6570 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
6571 /// identifier list form for a K&R-style function: void foo(a,b,c)
6573 /// Note that identifier-lists are only allowed for normal declarators, not for
6574 /// abstract-declarators.
6575 bool Parser::isFunctionDeclaratorIdentifierList() {
6576 return !getLangOpts().CPlusPlus
6577 && Tok.is(tok::identifier)
6578 && !TryAltiVecVectorToken()
6579 // K&R identifier lists can't have typedefs as identifiers, per C99
6581 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6582 // Identifier lists follow a really simple grammar: the identifiers can
6583 // be followed *only* by a ", identifier" or ")". However, K&R
6584 // identifier lists are really rare in the brave new modern world, and
6585 // it is very common for someone to typo a type in a non-K&R style
6586 // list. If we are presented with something like: "void foo(intptr x,
6587 // float y)", we don't want to start parsing the function declarator as
6588 // though it is a K&R style declarator just because intptr is an
6591 // To handle this, we check to see if the token after the first
6592 // identifier is a "," or ")". Only then do we parse it as an
6594 && (!Tok.is(tok::eof) &&
6595 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
6598 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6599 /// we found a K&R-style identifier list instead of a typed parameter list.
6601 /// After returning, ParamInfo will hold the parsed parameters.
6603 /// identifier-list: [C99 6.7.5]
6605 /// identifier-list ',' identifier
6607 void Parser::ParseFunctionDeclaratorIdentifierList(
6609 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
6610 // If there was no identifier specified for the declarator, either we are in
6611 // an abstract-declarator, or we are in a parameter declarator which was found
6612 // to be abstract. In abstract-declarators, identifier lists are not valid:
6614 if (!D.getIdentifier())
6615 Diag(Tok, diag::ext_ident_list_in_param);
6617 // Maintain an efficient lookup of params we have seen so far.
6618 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6621 // If this isn't an identifier, report the error and skip until ')'.
6622 if (Tok.isNot(tok::identifier)) {
6623 Diag(Tok, diag::err_expected) << tok::identifier;
6624 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
6625 // Forget we parsed anything.
6630 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6632 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6633 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6634 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6636 // Verify that the argument identifier has not already been mentioned.
6637 if (!ParamsSoFar.insert(ParmII).second) {
6638 Diag(Tok, diag::err_param_redefinition) << ParmII;
6640 // Remember this identifier in ParamInfo.
6641 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6646 // Eat the identifier.
6648 // The list continues if we see a comma.
6649 } while (TryConsumeToken(tok::comma));
6652 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6653 /// after the opening parenthesis. This function will not parse a K&R-style
6654 /// identifier list.
6656 /// DeclContext is the context of the declarator being parsed. If FirstArgAttrs
6657 /// is non-null, then the caller parsed those attributes immediately after the
6658 /// open paren - they should be considered to be part of the first parameter.
6660 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6661 /// be the location of the ellipsis, if any was parsed.
6663 /// parameter-type-list: [C99 6.7.5]
6665 /// parameter-list ',' '...'
6666 /// [C++] parameter-list '...'
6668 /// parameter-list: [C99 6.7.5]
6669 /// parameter-declaration
6670 /// parameter-list ',' parameter-declaration
6672 /// parameter-declaration: [C99 6.7.5]
6673 /// declaration-specifiers declarator
6674 /// [C++] declaration-specifiers declarator '=' assignment-expression
6675 /// [C++11] initializer-clause
6676 /// [GNU] declaration-specifiers declarator attributes
6677 /// declaration-specifiers abstract-declarator[opt]
6678 /// [C++] declaration-specifiers abstract-declarator[opt]
6679 /// '=' assignment-expression
6680 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
6681 /// [C++11] attribute-specifier-seq parameter-declaration
6683 void Parser::ParseParameterDeclarationClause(
6684 DeclaratorContext DeclaratorCtx,
6685 ParsedAttributes &FirstArgAttrs,
6686 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
6687 SourceLocation &EllipsisLoc) {
6689 // Avoid exceeding the maximum function scope depth.
6690 // See https://bugs.llvm.org/show_bug.cgi?id=19607
6691 // Note Sema::ActOnParamDeclarator calls ParmVarDecl::setScopeInfo with
6692 // getFunctionPrototypeDepth() - 1.
6693 if (getCurScope()->getFunctionPrototypeDepth() - 1 >
6694 ParmVarDecl::getMaxFunctionScopeDepth()) {
6695 Diag(Tok.getLocation(), diag::err_function_scope_depth_exceeded)
6696 << ParmVarDecl::getMaxFunctionScopeDepth();
6702 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6703 // before deciding this was a parameter-declaration-clause.
6704 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
6707 // Parse the declaration-specifiers.
6708 // Just use the ParsingDeclaration "scope" of the declarator.
6709 DeclSpec DS(AttrFactory);
6711 // Parse any C++11 attributes.
6712 MaybeParseCXX11Attributes(DS.getAttributes());
6714 // Skip any Microsoft attributes before a param.
6715 MaybeParseMicrosoftAttributes(DS.getAttributes());
6717 SourceLocation DSStart = Tok.getLocation();
6719 // If the caller parsed attributes for the first argument, add them now.
6720 // Take them so that we only apply the attributes to the first parameter.
6721 // FIXME: If we can leave the attributes in the token stream somehow, we can
6722 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6724 DS.takeAttributesFrom(FirstArgAttrs);
6726 ParseDeclarationSpecifiers(DS);
6729 // Parse the declarator. This is "PrototypeContext" or
6730 // "LambdaExprParameterContext", because we must accept either
6731 // 'declarator' or 'abstract-declarator' here.
6732 Declarator ParmDeclarator(
6733 DS, DeclaratorCtx == DeclaratorContext::RequiresExprContext
6734 ? DeclaratorContext::RequiresExprContext
6735 : DeclaratorCtx == DeclaratorContext::LambdaExprContext
6736 ? DeclaratorContext::LambdaExprParameterContext
6737 : DeclaratorContext::PrototypeContext);
6738 ParseDeclarator(ParmDeclarator);
6740 // Parse GNU attributes, if present.
6741 MaybeParseGNUAttributes(ParmDeclarator);
6743 if (Tok.is(tok::kw_requires)) {
6744 // User tried to define a requires clause in a parameter declaration,
6745 // which is surely not a function declaration.
6746 // void f(int (*g)(int, int) requires true);
6748 diag::err_requires_clause_on_declarator_not_declaring_a_function);
6750 Actions.CorrectDelayedTyposInExpr(
6751 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
6754 // Remember this parsed parameter in ParamInfo.
6755 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
6757 // DefArgToks is used when the parsing of default arguments needs
6759 std::unique_ptr<CachedTokens> DefArgToks;
6761 // If no parameter was specified, verify that *something* was specified,
6762 // otherwise we have a missing type and identifier.
6763 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
6764 ParmDeclarator.getNumTypeObjects() == 0) {
6765 // Completely missing, emit error.
6766 Diag(DSStart, diag::err_missing_param);
6768 // Otherwise, we have something. Add it and let semantic analysis try
6769 // to grok it and add the result to the ParamInfo we are building.
6771 // Last chance to recover from a misplaced ellipsis in an attempted
6772 // parameter pack declaration.
6773 if (Tok.is(tok::ellipsis) &&
6774 (NextToken().isNot(tok::r_paren) ||
6775 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6776 !Actions.isUnexpandedParameterPackPermitted())) &&
6777 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6778 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6780 // Inform the actions module about the parameter declarator, so it gets
6781 // added to the current scope.
6782 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
6783 // Parse the default argument, if any. We parse the default
6784 // arguments in all dialects; the semantic analysis in
6785 // ActOnParamDefaultArgument will reject the default argument in
6787 if (Tok.is(tok::equal)) {
6788 SourceLocation EqualLoc = Tok.getLocation();
6790 // Parse the default argument
6791 if (DeclaratorCtx == DeclaratorContext::MemberContext) {
6792 // If we're inside a class definition, cache the tokens
6793 // corresponding to the default argument. We'll actually parse
6794 // them when we see the end of the class definition.
6795 DefArgToks.reset(new CachedTokens);
6797 SourceLocation ArgStartLoc = NextToken().getLocation();
6798 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
6800 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6802 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
6809 // The argument isn't actually potentially evaluated unless it is
6811 EnterExpressionEvaluationContext Eval(
6813 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6816 ExprResult DefArgResult;
6817 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
6818 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
6819 DefArgResult = ParseBraceInitializer();
6821 DefArgResult = ParseAssignmentExpression();
6822 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
6823 if (DefArgResult.isInvalid()) {
6824 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6825 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
6827 // Inform the actions module about the default argument
6828 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
6829 DefArgResult.get());
6834 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6835 ParmDeclarator.getIdentifierLoc(),
6836 Param, std::move(DefArgToks)));
6839 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6840 if (!getLangOpts().CPlusPlus) {
6841 // We have ellipsis without a preceding ',', which is ill-formed
6842 // in C. Complain and provide the fix.
6843 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6844 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6845 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6846 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6847 // It looks like this was supposed to be a parameter pack. Warn and
6848 // point out where the ellipsis should have gone.
6849 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6850 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6851 << ParmEllipsis.isValid() << ParmEllipsis;
6852 if (ParmEllipsis.isValid()) {
6854 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6856 Diag(ParmDeclarator.getIdentifierLoc(),
6857 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6858 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6860 << !ParmDeclarator.hasName();
6862 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
6863 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6866 // We can't have any more parameters after an ellipsis.
6870 // If the next token is a comma, consume it and keep reading arguments.
6871 } while (TryConsumeToken(tok::comma));
6874 /// [C90] direct-declarator '[' constant-expression[opt] ']'
6875 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6876 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6877 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6878 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
6879 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
6880 /// attribute-specifier-seq[opt]
6881 void Parser::ParseBracketDeclarator(Declarator &D) {
6882 if (CheckProhibitedCXX11Attribute())
6885 BalancedDelimiterTracker T(*this, tok::l_square);
6888 // C array syntax has many features, but by-far the most common is [] and [4].
6889 // This code does a fast path to handle some of the most obvious cases.
6890 if (Tok.getKind() == tok::r_square) {
6892 ParsedAttributes attrs(AttrFactory);
6893 MaybeParseCXX11Attributes(attrs);
6895 // Remember that we parsed the empty array type.
6896 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
6897 T.getOpenLocation(),
6898 T.getCloseLocation()),
6899 std::move(attrs), T.getCloseLocation());
6901 } else if (Tok.getKind() == tok::numeric_constant &&
6902 GetLookAheadToken(1).is(tok::r_square)) {
6903 // [4] is very common. Parse the numeric constant expression.
6904 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
6908 ParsedAttributes attrs(AttrFactory);
6909 MaybeParseCXX11Attributes(attrs);
6911 // Remember that we parsed a array type, and remember its features.
6912 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
6913 T.getOpenLocation(),
6914 T.getCloseLocation()),
6915 std::move(attrs), T.getCloseLocation());
6917 } else if (Tok.getKind() == tok::code_completion) {
6918 Actions.CodeCompleteBracketDeclarator(getCurScope());
6919 return cutOffParsing();
6922 // If valid, this location is the position where we read the 'static' keyword.
6923 SourceLocation StaticLoc;
6924 TryConsumeToken(tok::kw_static, StaticLoc);
6926 // If there is a type-qualifier-list, read it now.
6927 // Type qualifiers in an array subscript are a C99 feature.
6928 DeclSpec DS(AttrFactory);
6929 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
6931 // If we haven't already read 'static', check to see if there is one after the
6932 // type-qualifier-list.
6933 if (!StaticLoc.isValid())
6934 TryConsumeToken(tok::kw_static, StaticLoc);
6936 // Handle "direct-declarator [ type-qual-list[opt] * ]".
6937 bool isStar = false;
6938 ExprResult NumElements;
6940 // Handle the case where we have '[*]' as the array size. However, a leading
6941 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
6942 // the token after the star is a ']'. Since stars in arrays are
6943 // infrequent, use of lookahead is not costly here.
6944 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
6945 ConsumeToken(); // Eat the '*'.
6947 if (StaticLoc.isValid()) {
6948 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
6949 StaticLoc = SourceLocation(); // Drop the static.
6952 } else if (Tok.isNot(tok::r_square)) {
6953 // Note, in C89, this production uses the constant-expr production instead
6954 // of assignment-expr. The only difference is that assignment-expr allows
6955 // things like '=' and '*='. Sema rejects these in C89 mode because they
6956 // are not i-c-e's, so we don't need to distinguish between the two here.
6958 // Parse the constant-expression or assignment-expression now (depending
6960 if (getLangOpts().CPlusPlus) {
6961 NumElements = ParseConstantExpression();
6963 EnterExpressionEvaluationContext Unevaluated(
6964 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6966 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
6969 if (StaticLoc.isValid()) {
6970 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6971 StaticLoc = SourceLocation(); // Drop the static.
6975 // If there was an error parsing the assignment-expression, recover.
6976 if (NumElements.isInvalid()) {
6977 D.setInvalidType(true);
6978 // If the expression was invalid, skip it.
6979 SkipUntil(tok::r_square, StopAtSemi);
6985 MaybeParseCXX11Attributes(DS.getAttributes());
6987 // Remember that we parsed a array type, and remember its features.
6989 DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
6990 isStar, NumElements.get(), T.getOpenLocation(),
6991 T.getCloseLocation()),
6992 std::move(DS.getAttributes()), T.getCloseLocation());
6995 /// Diagnose brackets before an identifier.
6996 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6997 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6998 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
7000 SourceLocation StartBracketLoc = Tok.getLocation();
7001 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
7003 while (Tok.is(tok::l_square)) {
7004 ParseBracketDeclarator(TempDeclarator);
7007 // Stuff the location of the start of the brackets into the Declarator.
7008 // The diagnostics from ParseDirectDeclarator will make more sense if
7009 // they use this location instead.
7010 if (Tok.is(tok::semi))
7011 D.getName().EndLocation = StartBracketLoc;
7013 SourceLocation SuggestParenLoc = Tok.getLocation();
7015 // Now that the brackets are removed, try parsing the declarator again.
7016 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
7018 // Something went wrong parsing the brackets, in which case,
7019 // ParseBracketDeclarator has emitted an error, and we don't need to emit
7021 if (TempDeclarator.getNumTypeObjects() == 0)
7024 // Determine if parens will need to be suggested in the diagnostic.
7025 bool NeedParens = false;
7026 if (D.getNumTypeObjects() != 0) {
7027 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
7028 case DeclaratorChunk::Pointer:
7029 case DeclaratorChunk::Reference:
7030 case DeclaratorChunk::BlockPointer:
7031 case DeclaratorChunk::MemberPointer:
7032 case DeclaratorChunk::Pipe:
7035 case DeclaratorChunk::Array:
7036 case DeclaratorChunk::Function:
7037 case DeclaratorChunk::Paren:
7043 // Create a DeclaratorChunk for the inserted parens.
7044 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
7045 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
7049 // Adding back the bracket info to the end of the Declarator.
7050 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
7051 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
7052 D.AddTypeInfo(Chunk, SourceLocation());
7055 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
7056 // If parentheses are required, always suggest them.
7057 if (!D.getIdentifier() && !NeedParens)
7060 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
7062 // Generate the move bracket error message.
7063 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
7064 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
7067 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
7068 << getLangOpts().CPlusPlus
7069 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
7070 << FixItHint::CreateInsertion(EndLoc, ")")
7071 << FixItHint::CreateInsertionFromRange(
7072 EndLoc, CharSourceRange(BracketRange, true))
7073 << FixItHint::CreateRemoval(BracketRange);
7075 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
7076 << getLangOpts().CPlusPlus
7077 << FixItHint::CreateInsertionFromRange(
7078 EndLoc, CharSourceRange(BracketRange, true))
7079 << FixItHint::CreateRemoval(BracketRange);
7083 /// [GNU] typeof-specifier:
7084 /// typeof ( expressions )
7085 /// typeof ( type-name )
7086 /// [GNU/C++] typeof unary-expression
7088 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
7089 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
7091 SourceLocation StartLoc = ConsumeToken();
7093 const bool hasParens = Tok.is(tok::l_paren);
7095 EnterExpressionEvaluationContext Unevaluated(
7096 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
7097 Sema::ReuseLambdaContextDecl);
7101 SourceRange CastRange;
7102 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
7103 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
7105 DS.setTypeofParensRange(CastRange);
7107 if (CastRange.getEnd().isInvalid())
7108 // FIXME: Not accurate, the range gets one token more than it should.
7109 DS.SetRangeEnd(Tok.getLocation());
7111 DS.SetRangeEnd(CastRange.getEnd());
7115 DS.SetTypeSpecError();
7119 const char *PrevSpec = nullptr;
7121 // Check for duplicate type specifiers (e.g. "int typeof(int)").
7122 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
7124 Actions.getASTContext().getPrintingPolicy()))
7125 Diag(StartLoc, DiagID) << PrevSpec;
7129 // If we get here, the operand to the typeof was an expression.
7130 if (Operand.isInvalid()) {
7131 DS.SetTypeSpecError();
7135 // We might need to transform the operand if it is potentially evaluated.
7136 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
7137 if (Operand.isInvalid()) {
7138 DS.SetTypeSpecError();
7142 const char *PrevSpec = nullptr;
7144 // Check for duplicate type specifiers (e.g. "int typeof(int)").
7145 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
7146 DiagID, Operand.get(),
7147 Actions.getASTContext().getPrintingPolicy()))
7148 Diag(StartLoc, DiagID) << PrevSpec;
7151 /// [C11] atomic-specifier:
7152 /// _Atomic ( type-name )
7154 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
7155 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
7156 "Not an atomic specifier");
7158 SourceLocation StartLoc = ConsumeToken();
7159 BalancedDelimiterTracker T(*this, tok::l_paren);
7160 if (T.consumeOpen())
7163 TypeResult Result = ParseTypeName();
7164 if (Result.isInvalid()) {
7165 SkipUntil(tok::r_paren, StopAtSemi);
7172 if (T.getCloseLocation().isInvalid())
7175 DS.setTypeofParensRange(T.getRange());
7176 DS.SetRangeEnd(T.getCloseLocation());
7178 const char *PrevSpec = nullptr;
7180 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
7181 DiagID, Result.get(),
7182 Actions.getASTContext().getPrintingPolicy()))
7183 Diag(StartLoc, DiagID) << PrevSpec;
7186 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
7187 /// from TryAltiVecVectorToken.
7188 bool Parser::TryAltiVecVectorTokenOutOfLine() {
7189 Token Next = NextToken();
7190 switch (Next.getKind()) {
7191 default: return false;
7194 case tok::kw_signed:
7195 case tok::kw_unsigned:
7200 case tok::kw_double:
7202 case tok::kw___bool:
7203 case tok::kw___pixel:
7204 Tok.setKind(tok::kw___vector);
7206 case tok::identifier:
7207 if (Next.getIdentifierInfo() == Ident_pixel) {
7208 Tok.setKind(tok::kw___vector);
7211 if (Next.getIdentifierInfo() == Ident_bool) {
7212 Tok.setKind(tok::kw___vector);
7219 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
7220 const char *&PrevSpec, unsigned &DiagID,
7222 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
7223 if (Tok.getIdentifierInfo() == Ident_vector) {
7224 Token Next = NextToken();
7225 switch (Next.getKind()) {
7228 case tok::kw_signed:
7229 case tok::kw_unsigned:
7234 case tok::kw_double:
7236 case tok::kw___bool:
7237 case tok::kw___pixel:
7238 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
7240 case tok::identifier:
7241 if (Next.getIdentifierInfo() == Ident_pixel) {
7242 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
7245 if (Next.getIdentifierInfo() == Ident_bool) {
7246 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
7253 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
7254 DS.isTypeAltiVecVector()) {
7255 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
7257 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
7258 DS.isTypeAltiVecVector()) {
7259 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);