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 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);
339 // Interpret "kw_this" as an identifier if the attributed requests it.
340 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
341 Tok.setKind(tok::identifier);
344 if (Tok.is(tok::identifier)) {
345 // If this attribute wants an 'identifier' argument, make it so.
346 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName) ||
347 attributeHasVariadicIdentifierArg(*AttrName);
348 ParsedAttr::Kind AttrKind =
349 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
351 // If we don't know how to parse this attribute, but this is the only
352 // token in this argument, assume it's meant to be an identifier.
353 if (AttrKind == ParsedAttr::UnknownAttribute ||
354 AttrKind == ParsedAttr::IgnoredAttribute) {
355 const Token &Next = NextToken();
356 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
360 ArgExprs.push_back(ParseIdentifierLoc());
363 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
365 if (!ArgExprs.empty())
368 // Parse the non-empty comma-separated list of expressions.
370 // Interpret "kw_this" as an identifier if the attributed requests it.
371 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
372 Tok.setKind(tok::identifier);
375 if (Tok.is(tok::identifier) &&
376 attributeHasVariadicIdentifierArg(*AttrName)) {
377 ArgExprs.push_back(ParseIdentifierLoc());
379 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
380 EnterExpressionEvaluationContext Unevaluated(
382 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
383 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
386 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
387 if (ArgExpr.isInvalid()) {
388 SkipUntil(tok::r_paren, StopAtSemi);
391 ArgExprs.push_back(ArgExpr.get());
393 // Eat the comma, move to the next argument
394 } while (TryConsumeToken(tok::comma));
397 SourceLocation RParen = Tok.getLocation();
398 if (!ExpectAndConsume(tok::r_paren)) {
399 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
400 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
401 ArgExprs.data(), ArgExprs.size(), Syntax);
407 return static_cast<unsigned>(ArgExprs.size());
410 /// Parse the arguments to a parameterized GNU attribute or
411 /// a C++11 attribute in "gnu" namespace.
412 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
413 SourceLocation AttrNameLoc,
414 ParsedAttributes &Attrs,
415 SourceLocation *EndLoc,
416 IdentifierInfo *ScopeName,
417 SourceLocation ScopeLoc,
418 ParsedAttr::Syntax Syntax,
421 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
423 ParsedAttr::Kind AttrKind =
424 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
426 if (AttrKind == ParsedAttr::AT_Availability) {
427 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
430 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
431 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
432 ScopeName, ScopeLoc, Syntax);
434 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
435 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
436 ScopeName, ScopeLoc, Syntax);
438 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
439 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
440 ScopeName, ScopeLoc, Syntax);
442 } else if (attributeIsTypeArgAttr(*AttrName)) {
443 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
448 // These may refer to the function arguments, but need to be parsed early to
449 // participate in determining whether it's a redeclaration.
450 llvm::Optional<ParseScope> PrototypeScope;
451 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
452 D && D->isFunctionDeclarator()) {
453 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
454 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
455 Scope::FunctionDeclarationScope |
457 for (unsigned i = 0; i != FTI.NumParams; ++i) {
458 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
459 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
463 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
467 unsigned Parser::ParseClangAttributeArgs(
468 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
469 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
470 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
471 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
473 ParsedAttr::Kind AttrKind =
474 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
478 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
479 ScopeName, ScopeLoc, Syntax);
480 case ParsedAttr::AT_ExternalSourceSymbol:
481 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
482 ScopeName, ScopeLoc, Syntax);
484 case ParsedAttr::AT_Availability:
485 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
488 case ParsedAttr::AT_ObjCBridgeRelated:
489 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
490 ScopeName, ScopeLoc, Syntax);
492 case ParsedAttr::AT_TypeTagForDatatype:
493 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
494 ScopeName, ScopeLoc, Syntax);
497 return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
500 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
501 SourceLocation AttrNameLoc,
502 ParsedAttributes &Attrs) {
503 // If the attribute isn't known, we will not attempt to parse any
505 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
506 getTargetInfo(), getLangOpts())) {
507 // Eat the left paren, then skip to the ending right paren.
509 SkipUntil(tok::r_paren);
513 SourceLocation OpenParenLoc = Tok.getLocation();
515 if (AttrName->getName() == "property") {
516 // The property declspec is more complex in that it can take one or two
517 // assignment expressions as a parameter, but the lhs of the assignment
518 // must be named get or put.
520 BalancedDelimiterTracker T(*this, tok::l_paren);
521 T.expectAndConsume(diag::err_expected_lparen_after,
522 AttrName->getNameStart(), tok::r_paren);
527 AK_Get = 1 // indices into AccessorNames
529 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
530 bool HasInvalidAccessor = false;
532 // Parse the accessor specifications.
534 // Stop if this doesn't look like an accessor spec.
535 if (!Tok.is(tok::identifier)) {
536 // If the user wrote a completely empty list, use a special diagnostic.
537 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
538 AccessorNames[AK_Put] == nullptr &&
539 AccessorNames[AK_Get] == nullptr) {
540 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
544 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
549 SourceLocation KindLoc = Tok.getLocation();
550 StringRef KindStr = Tok.getIdentifierInfo()->getName();
551 if (KindStr == "get") {
553 } else if (KindStr == "put") {
556 // Recover from the common mistake of using 'set' instead of 'put'.
557 } else if (KindStr == "set") {
558 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
559 << FixItHint::CreateReplacement(KindLoc, "put");
562 // Handle the mistake of forgetting the accessor kind by skipping
564 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
565 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
567 HasInvalidAccessor = true;
568 goto next_property_accessor;
570 // Otherwise, complain about the unknown accessor kind.
572 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
573 HasInvalidAccessor = true;
576 // Try to keep parsing unless it doesn't look like an accessor spec.
577 if (!NextToken().is(tok::equal))
581 // Consume the identifier.
585 if (!TryConsumeToken(tok::equal)) {
586 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
591 // Expect the method name.
592 if (!Tok.is(tok::identifier)) {
593 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
597 if (Kind == AK_Invalid) {
598 // Just drop invalid accessors.
599 } else if (AccessorNames[Kind] != nullptr) {
600 // Complain about the repeated accessor, ignore it, and keep parsing.
601 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
603 AccessorNames[Kind] = Tok.getIdentifierInfo();
607 next_property_accessor:
608 // Keep processing accessors until we run out.
609 if (TryConsumeToken(tok::comma))
612 // If we run into the ')', stop without consuming it.
613 if (Tok.is(tok::r_paren))
616 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
620 // Only add the property attribute if it was well-formed.
621 if (!HasInvalidAccessor)
622 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
623 AccessorNames[AK_Get], AccessorNames[AK_Put],
624 ParsedAttr::AS_Declspec);
626 return !HasInvalidAccessor;
630 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
631 SourceLocation(), ParsedAttr::AS_Declspec);
633 // If this attribute's args were parsed, and it was expected to have
634 // arguments but none were provided, emit a diagnostic.
635 if (!Attrs.empty() && Attrs.begin()->getMaxArgs() && !NumArgs) {
636 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
642 /// [MS] decl-specifier:
643 /// __declspec ( extended-decl-modifier-seq )
645 /// [MS] extended-decl-modifier-seq:
646 /// extended-decl-modifier[opt]
647 /// extended-decl-modifier extended-decl-modifier-seq
648 void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
649 SourceLocation *End) {
650 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
651 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
653 while (Tok.is(tok::kw___declspec)) {
655 BalancedDelimiterTracker T(*this, tok::l_paren);
656 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
660 // An empty declspec is perfectly legal and should not warn. Additionally,
661 // you can specify multiple attributes per declspec.
662 while (Tok.isNot(tok::r_paren)) {
663 // Attribute not present.
664 if (TryConsumeToken(tok::comma))
667 // We expect either a well-known identifier or a generic string. Anything
668 // else is a malformed declspec.
669 bool IsString = Tok.getKind() == tok::string_literal;
670 if (!IsString && Tok.getKind() != tok::identifier &&
671 Tok.getKind() != tok::kw_restrict) {
672 Diag(Tok, diag::err_ms_declspec_type);
677 IdentifierInfo *AttrName;
678 SourceLocation AttrNameLoc;
680 SmallString<8> StrBuffer;
681 bool Invalid = false;
682 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
687 AttrName = PP.getIdentifierInfo(Str);
688 AttrNameLoc = ConsumeStringToken();
690 AttrName = Tok.getIdentifierInfo();
691 AttrNameLoc = ConsumeToken();
694 bool AttrHandled = false;
696 // Parse attribute arguments.
697 if (Tok.is(tok::l_paren))
698 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
699 else if (AttrName->getName() == "property")
700 // The property attribute must have an argument list.
701 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
702 << AttrName->getName();
705 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
706 ParsedAttr::AS_Declspec);
710 *End = T.getCloseLocation();
714 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
715 // Treat these like attributes
717 switch (Tok.getKind()) {
718 case tok::kw___fastcall:
719 case tok::kw___stdcall:
720 case tok::kw___thiscall:
721 case tok::kw___regcall:
722 case tok::kw___cdecl:
723 case tok::kw___vectorcall:
724 case tok::kw___ptr64:
726 case tok::kw___ptr32:
728 case tok::kw___uptr: {
729 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
730 SourceLocation AttrNameLoc = ConsumeToken();
731 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
732 ParsedAttr::AS_Keyword);
741 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
742 SourceLocation StartLoc = Tok.getLocation();
743 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
745 if (EndLoc.isValid()) {
746 SourceRange Range(StartLoc, EndLoc);
747 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
751 SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
752 SourceLocation EndLoc;
755 switch (Tok.getKind()) {
757 case tok::kw_volatile:
758 case tok::kw___fastcall:
759 case tok::kw___stdcall:
760 case tok::kw___thiscall:
761 case tok::kw___cdecl:
762 case tok::kw___vectorcall:
763 case tok::kw___ptr32:
764 case tok::kw___ptr64:
766 case tok::kw___unaligned:
769 EndLoc = ConsumeToken();
777 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
778 // Treat these like attributes
779 while (Tok.is(tok::kw___pascal)) {
780 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
781 SourceLocation AttrNameLoc = ConsumeToken();
782 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
783 ParsedAttr::AS_Keyword);
787 void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
788 // Treat these like attributes
789 while (Tok.is(tok::kw___kernel)) {
790 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
791 SourceLocation AttrNameLoc = ConsumeToken();
792 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
793 ParsedAttr::AS_Keyword);
797 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
798 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
799 SourceLocation AttrNameLoc = Tok.getLocation();
800 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
801 ParsedAttr::AS_Keyword);
804 void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
805 // Treat these like attributes, even though they're type specifiers.
807 switch (Tok.getKind()) {
808 case tok::kw__Nonnull:
809 case tok::kw__Nullable:
810 case tok::kw__Null_unspecified: {
811 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
812 SourceLocation AttrNameLoc = ConsumeToken();
813 if (!getLangOpts().ObjC)
814 Diag(AttrNameLoc, diag::ext_nullability)
816 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
817 ParsedAttr::AS_Keyword);
826 static bool VersionNumberSeparator(const char Separator) {
827 return (Separator == '.' || Separator == '_');
830 /// Parse a version number.
834 /// simple-integer '.' simple-integer
835 /// simple-integer '_' simple-integer
836 /// simple-integer '.' simple-integer '.' simple-integer
837 /// simple-integer '_' simple-integer '_' simple-integer
838 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
839 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
841 if (!Tok.is(tok::numeric_constant)) {
842 Diag(Tok, diag::err_expected_version);
843 SkipUntil(tok::comma, tok::r_paren,
844 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
845 return VersionTuple();
848 // Parse the major (and possibly minor and subminor) versions, which
849 // are stored in the numeric constant. We utilize a quirk of the
850 // lexer, which is that it handles something like 1.2.3 as a single
851 // numeric constant, rather than two separate tokens.
852 SmallString<512> Buffer;
853 Buffer.resize(Tok.getLength()+1);
854 const char *ThisTokBegin = &Buffer[0];
856 // Get the spelling of the token, which eliminates trigraphs, etc.
857 bool Invalid = false;
858 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
860 return VersionTuple();
862 // Parse the major version.
863 unsigned AfterMajor = 0;
865 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
866 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
870 if (AfterMajor == 0) {
871 Diag(Tok, diag::err_expected_version);
872 SkipUntil(tok::comma, tok::r_paren,
873 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
874 return VersionTuple();
877 if (AfterMajor == ActualLength) {
880 // We only had a single version component.
882 Diag(Tok, diag::err_zero_version);
883 return VersionTuple();
886 return VersionTuple(Major);
889 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
890 if (!VersionNumberSeparator(AfterMajorSeparator)
891 || (AfterMajor + 1 == ActualLength)) {
892 Diag(Tok, diag::err_expected_version);
893 SkipUntil(tok::comma, tok::r_paren,
894 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
895 return VersionTuple();
898 // Parse the minor version.
899 unsigned AfterMinor = AfterMajor + 1;
901 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
902 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
906 if (AfterMinor == ActualLength) {
909 // We had major.minor.
910 if (Major == 0 && Minor == 0) {
911 Diag(Tok, diag::err_zero_version);
912 return VersionTuple();
915 return VersionTuple(Major, Minor);
918 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
919 // If what follows is not a '.' or '_', we have a problem.
920 if (!VersionNumberSeparator(AfterMinorSeparator)) {
921 Diag(Tok, diag::err_expected_version);
922 SkipUntil(tok::comma, tok::r_paren,
923 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
924 return VersionTuple();
927 // Warn if separators, be it '.' or '_', do not match.
928 if (AfterMajorSeparator != AfterMinorSeparator)
929 Diag(Tok, diag::warn_expected_consistent_version_separator);
931 // Parse the subminor version.
932 unsigned AfterSubminor = AfterMinor + 1;
933 unsigned Subminor = 0;
934 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
935 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
939 if (AfterSubminor != ActualLength) {
940 Diag(Tok, diag::err_expected_version);
941 SkipUntil(tok::comma, tok::r_paren,
942 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
943 return VersionTuple();
946 return VersionTuple(Major, Minor, Subminor);
949 /// Parse the contents of the "availability" attribute.
951 /// availability-attribute:
952 /// 'availability' '(' platform ',' opt-strict version-arg-list,
953 /// opt-replacement, opt-message')'
961 /// version-arg-list:
963 /// version-arg ',' version-arg-list
966 /// 'introduced' '=' version
967 /// 'deprecated' '=' version
968 /// 'obsoleted' = version
971 /// 'replacement' '=' <string>
973 /// 'message' '=' <string>
974 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
975 SourceLocation AvailabilityLoc,
976 ParsedAttributes &attrs,
977 SourceLocation *endLoc,
978 IdentifierInfo *ScopeName,
979 SourceLocation ScopeLoc,
980 ParsedAttr::Syntax Syntax) {
981 enum { Introduced, Deprecated, Obsoleted, Unknown };
982 AvailabilityChange Changes[Unknown];
983 ExprResult MessageExpr, ReplacementExpr;
986 BalancedDelimiterTracker T(*this, tok::l_paren);
987 if (T.consumeOpen()) {
988 Diag(Tok, diag::err_expected) << tok::l_paren;
992 // Parse the platform name.
993 if (Tok.isNot(tok::identifier)) {
994 Diag(Tok, diag::err_availability_expected_platform);
995 SkipUntil(tok::r_paren, StopAtSemi);
998 IdentifierLoc *Platform = ParseIdentifierLoc();
999 if (const IdentifierInfo *const Ident = Platform->Ident) {
1000 // Canonicalize platform name from "macosx" to "macos".
1001 if (Ident->getName() == "macosx")
1002 Platform->Ident = PP.getIdentifierInfo("macos");
1003 // Canonicalize platform name from "macosx_app_extension" to
1004 // "macos_app_extension".
1005 else if (Ident->getName() == "macosx_app_extension")
1006 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1008 Platform->Ident = PP.getIdentifierInfo(
1009 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1012 // Parse the ',' following the platform name.
1013 if (ExpectAndConsume(tok::comma)) {
1014 SkipUntil(tok::r_paren, StopAtSemi);
1018 // If we haven't grabbed the pointers for the identifiers
1019 // "introduced", "deprecated", and "obsoleted", do so now.
1020 if (!Ident_introduced) {
1021 Ident_introduced = PP.getIdentifierInfo("introduced");
1022 Ident_deprecated = PP.getIdentifierInfo("deprecated");
1023 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
1024 Ident_unavailable = PP.getIdentifierInfo("unavailable");
1025 Ident_message = PP.getIdentifierInfo("message");
1026 Ident_strict = PP.getIdentifierInfo("strict");
1027 Ident_replacement = PP.getIdentifierInfo("replacement");
1030 // Parse the optional "strict", the optional "replacement" and the set of
1031 // introductions/deprecations/removals.
1032 SourceLocation UnavailableLoc, StrictLoc;
1034 if (Tok.isNot(tok::identifier)) {
1035 Diag(Tok, diag::err_availability_expected_change);
1036 SkipUntil(tok::r_paren, StopAtSemi);
1039 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1040 SourceLocation KeywordLoc = ConsumeToken();
1042 if (Keyword == Ident_strict) {
1043 if (StrictLoc.isValid()) {
1044 Diag(KeywordLoc, diag::err_availability_redundant)
1045 << Keyword << SourceRange(StrictLoc);
1047 StrictLoc = KeywordLoc;
1051 if (Keyword == Ident_unavailable) {
1052 if (UnavailableLoc.isValid()) {
1053 Diag(KeywordLoc, diag::err_availability_redundant)
1054 << Keyword << SourceRange(UnavailableLoc);
1056 UnavailableLoc = KeywordLoc;
1060 if (Keyword == Ident_deprecated && Platform->Ident &&
1061 Platform->Ident->isStr("swift")) {
1062 // For swift, we deprecate for all versions.
1063 if (Changes[Deprecated].KeywordLoc.isValid()) {
1064 Diag(KeywordLoc, diag::err_availability_redundant)
1066 << SourceRange(Changes[Deprecated].KeywordLoc);
1069 Changes[Deprecated].KeywordLoc = KeywordLoc;
1070 // Use a fake version here.
1071 Changes[Deprecated].Version = VersionTuple(1);
1075 if (Tok.isNot(tok::equal)) {
1076 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1077 SkipUntil(tok::r_paren, StopAtSemi);
1081 if (Keyword == Ident_message || Keyword == Ident_replacement) {
1082 if (Tok.isNot(tok::string_literal)) {
1083 Diag(Tok, diag::err_expected_string_literal)
1084 << /*Source='availability attribute'*/2;
1085 SkipUntil(tok::r_paren, StopAtSemi);
1088 if (Keyword == Ident_message)
1089 MessageExpr = ParseStringLiteralExpression();
1091 ReplacementExpr = ParseStringLiteralExpression();
1092 // Also reject wide string literals.
1093 if (StringLiteral *MessageStringLiteral =
1094 cast_or_null<StringLiteral>(MessageExpr.get())) {
1095 if (MessageStringLiteral->getCharByteWidth() != 1) {
1096 Diag(MessageStringLiteral->getSourceRange().getBegin(),
1097 diag::err_expected_string_literal)
1098 << /*Source='availability attribute'*/ 2;
1099 SkipUntil(tok::r_paren, StopAtSemi);
1103 if (Keyword == Ident_message)
1109 // Special handling of 'NA' only when applied to introduced or
1111 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1112 Tok.is(tok::identifier)) {
1113 IdentifierInfo *NA = Tok.getIdentifierInfo();
1114 if (NA->getName() == "NA") {
1116 if (Keyword == Ident_introduced)
1117 UnavailableLoc = KeywordLoc;
1122 SourceRange VersionRange;
1123 VersionTuple Version = ParseVersionTuple(VersionRange);
1125 if (Version.empty()) {
1126 SkipUntil(tok::r_paren, StopAtSemi);
1131 if (Keyword == Ident_introduced)
1133 else if (Keyword == Ident_deprecated)
1135 else if (Keyword == Ident_obsoleted)
1140 if (Index < Unknown) {
1141 if (!Changes[Index].KeywordLoc.isInvalid()) {
1142 Diag(KeywordLoc, diag::err_availability_redundant)
1144 << SourceRange(Changes[Index].KeywordLoc,
1145 Changes[Index].VersionRange.getEnd());
1148 Changes[Index].KeywordLoc = KeywordLoc;
1149 Changes[Index].Version = Version;
1150 Changes[Index].VersionRange = VersionRange;
1152 Diag(KeywordLoc, diag::err_availability_unknown_change)
1153 << Keyword << VersionRange;
1156 } while (TryConsumeToken(tok::comma));
1159 if (T.consumeClose())
1163 *endLoc = T.getCloseLocation();
1165 // The 'unavailable' availability cannot be combined with any other
1166 // availability changes. Make sure that hasn't happened.
1167 if (UnavailableLoc.isValid()) {
1168 bool Complained = false;
1169 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1170 if (Changes[Index].KeywordLoc.isValid()) {
1172 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1173 << SourceRange(Changes[Index].KeywordLoc,
1174 Changes[Index].VersionRange.getEnd());
1178 // Clear out the availability.
1179 Changes[Index] = AvailabilityChange();
1184 // Record this attribute
1185 attrs.addNew(&Availability,
1186 SourceRange(AvailabilityLoc, T.getCloseLocation()),
1187 ScopeName, ScopeLoc,
1189 Changes[Introduced],
1190 Changes[Deprecated],
1192 UnavailableLoc, MessageExpr.get(),
1193 Syntax, StrictLoc, ReplacementExpr.get());
1196 /// Parse the contents of the "external_source_symbol" attribute.
1198 /// external-source-symbol-attribute:
1199 /// 'external_source_symbol' '(' keyword-arg-list ')'
1201 /// keyword-arg-list:
1203 /// keyword-arg ',' keyword-arg-list
1206 /// 'language' '=' <string>
1207 /// 'defined_in' '=' <string>
1208 /// 'generated_declaration'
1209 void Parser::ParseExternalSourceSymbolAttribute(
1210 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1211 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1212 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1214 BalancedDelimiterTracker T(*this, tok::l_paren);
1215 if (T.expectAndConsume())
1218 // Initialize the pointers for the keyword identifiers when required.
1219 if (!Ident_language) {
1220 Ident_language = PP.getIdentifierInfo("language");
1221 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1222 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1225 ExprResult Language;
1226 bool HasLanguage = false;
1227 ExprResult DefinedInExpr;
1228 bool HasDefinedIn = false;
1229 IdentifierLoc *GeneratedDeclaration = nullptr;
1231 // Parse the language/defined_in/generated_declaration keywords
1233 if (Tok.isNot(tok::identifier)) {
1234 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1235 SkipUntil(tok::r_paren, StopAtSemi);
1239 SourceLocation KeywordLoc = Tok.getLocation();
1240 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1241 if (Keyword == Ident_generated_declaration) {
1242 if (GeneratedDeclaration) {
1243 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1244 SkipUntil(tok::r_paren, StopAtSemi);
1247 GeneratedDeclaration = ParseIdentifierLoc();
1251 if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1252 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1253 SkipUntil(tok::r_paren, StopAtSemi);
1258 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1259 Keyword->getName())) {
1260 SkipUntil(tok::r_paren, StopAtSemi);
1264 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1265 if (Keyword == Ident_language)
1268 HasDefinedIn = true;
1270 if (Tok.isNot(tok::string_literal)) {
1271 Diag(Tok, diag::err_expected_string_literal)
1272 << /*Source='external_source_symbol attribute'*/ 3
1273 << /*language | source container*/ (Keyword != Ident_language);
1274 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1277 if (Keyword == Ident_language) {
1279 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1281 ParseStringLiteralExpression();
1284 Language = ParseStringLiteralExpression();
1286 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1288 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1290 ParseStringLiteralExpression();
1293 DefinedInExpr = ParseStringLiteralExpression();
1295 } while (TryConsumeToken(tok::comma));
1298 if (T.consumeClose())
1301 *EndLoc = T.getCloseLocation();
1303 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1304 GeneratedDeclaration};
1305 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1306 ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1309 /// Parse the contents of the "objc_bridge_related" attribute.
1310 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1314 /// opt-class_method:
1315 /// Identifier: | <empty>
1317 /// opt-instance_method:
1318 /// Identifier | <empty>
1320 void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1321 SourceLocation ObjCBridgeRelatedLoc,
1322 ParsedAttributes &attrs,
1323 SourceLocation *endLoc,
1324 IdentifierInfo *ScopeName,
1325 SourceLocation ScopeLoc,
1326 ParsedAttr::Syntax Syntax) {
1328 BalancedDelimiterTracker T(*this, tok::l_paren);
1329 if (T.consumeOpen()) {
1330 Diag(Tok, diag::err_expected) << tok::l_paren;
1334 // Parse the related class name.
1335 if (Tok.isNot(tok::identifier)) {
1336 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1337 SkipUntil(tok::r_paren, StopAtSemi);
1340 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1341 if (ExpectAndConsume(tok::comma)) {
1342 SkipUntil(tok::r_paren, StopAtSemi);
1346 // Parse class method name. It's non-optional in the sense that a trailing
1347 // comma is required, but it can be the empty string, and then we record a
1349 IdentifierLoc *ClassMethod = nullptr;
1350 if (Tok.is(tok::identifier)) {
1351 ClassMethod = ParseIdentifierLoc();
1352 if (!TryConsumeToken(tok::colon)) {
1353 Diag(Tok, diag::err_objcbridge_related_selector_name);
1354 SkipUntil(tok::r_paren, StopAtSemi);
1358 if (!TryConsumeToken(tok::comma)) {
1359 if (Tok.is(tok::colon))
1360 Diag(Tok, diag::err_objcbridge_related_selector_name);
1362 Diag(Tok, diag::err_expected) << tok::comma;
1363 SkipUntil(tok::r_paren, StopAtSemi);
1367 // Parse instance method name. Also non-optional but empty string is
1369 IdentifierLoc *InstanceMethod = nullptr;
1370 if (Tok.is(tok::identifier))
1371 InstanceMethod = ParseIdentifierLoc();
1372 else if (Tok.isNot(tok::r_paren)) {
1373 Diag(Tok, diag::err_expected) << tok::r_paren;
1374 SkipUntil(tok::r_paren, StopAtSemi);
1379 if (T.consumeClose())
1383 *endLoc = T.getCloseLocation();
1385 // Record this attribute
1386 attrs.addNew(&ObjCBridgeRelated,
1387 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1388 ScopeName, ScopeLoc,
1395 // Late Parsed Attributes:
1396 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1398 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1400 void Parser::LateParsedClass::ParseLexedAttributes() {
1401 Self->ParseLexedAttributes(*Class);
1404 void Parser::LateParsedAttribute::ParseLexedAttributes() {
1405 Self->ParseLexedAttribute(*this, true, false);
1408 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1409 /// scope appropriately.
1410 void Parser::ParseLexedAttributes(ParsingClass &Class) {
1411 // Deal with templates
1412 // FIXME: Test cases to make sure this does the right thing for templates.
1413 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1414 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1416 if (HasTemplateScope)
1417 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1419 // Set or update the scope flags.
1420 bool AlreadyHasClassScope = Class.TopLevelClass;
1421 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
1422 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1423 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1425 // Enter the scope of nested classes
1426 if (!AlreadyHasClassScope)
1427 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1428 Class.TagOrTemplate);
1429 if (!Class.LateParsedDeclarations.empty()) {
1430 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1431 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1435 if (!AlreadyHasClassScope)
1436 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1437 Class.TagOrTemplate);
1440 /// Parse all attributes in LAs, and attach them to Decl D.
1441 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1442 bool EnterScope, bool OnDefinition) {
1443 assert(LAs.parseSoon() &&
1444 "Attribute list should be marked for immediate parsing.");
1445 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1448 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1454 /// Finish parsing an attribute for which parsing was delayed.
1455 /// This will be called at the end of parsing a class declaration
1456 /// for each LateParsedAttribute. We consume the saved tokens and
1457 /// create an attribute with the arguments filled in. We add this
1458 /// to the Attribute list for the decl.
1459 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1460 bool EnterScope, bool OnDefinition) {
1461 // Create a fake EOF so that attribute parsing won't go off the end of the
1464 AttrEnd.startToken();
1465 AttrEnd.setKind(tok::eof);
1466 AttrEnd.setLocation(Tok.getLocation());
1467 AttrEnd.setEofData(LA.Toks.data());
1468 LA.Toks.push_back(AttrEnd);
1470 // Append the current token at the end of the new token stream so that it
1471 // doesn't get lost.
1472 LA.Toks.push_back(Tok);
1473 PP.EnterTokenStream(LA.Toks, true, /*IsReinject=*/true);
1474 // Consume the previously pushed token.
1475 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1477 ParsedAttributes Attrs(AttrFactory);
1478 SourceLocation endLoc;
1480 if (LA.Decls.size() > 0) {
1481 Decl *D = LA.Decls[0];
1482 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1483 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1485 // Allow 'this' within late-parsed attributes.
1486 Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
1487 ND && ND->isCXXInstanceMember());
1489 if (LA.Decls.size() == 1) {
1490 // If the Decl is templatized, add template parameters to scope.
1491 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1492 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1493 if (HasTemplateScope)
1494 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1496 // If the Decl is on a function, add function parameters to the scope.
1497 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1499 this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope,
1502 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1504 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1505 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
1509 Actions.ActOnExitFunctionContext();
1510 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1512 if (HasTemplateScope) {
1516 // If there are multiple decls, then the decl cannot be within the
1518 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1519 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
1523 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1526 if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
1527 Attrs.begin()->isKnownToGCC())
1528 Diag(Tok, diag::warn_attribute_on_function_definition)
1531 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
1532 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1534 // Due to a parsing error, we either went over the cached tokens or
1535 // there are still cached tokens left, so we skip the leftover tokens.
1536 while (Tok.isNot(tok::eof))
1539 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1543 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1544 SourceLocation AttrNameLoc,
1545 ParsedAttributes &Attrs,
1546 SourceLocation *EndLoc,
1547 IdentifierInfo *ScopeName,
1548 SourceLocation ScopeLoc,
1549 ParsedAttr::Syntax Syntax) {
1550 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1552 BalancedDelimiterTracker T(*this, tok::l_paren);
1555 if (Tok.isNot(tok::identifier)) {
1556 Diag(Tok, diag::err_expected) << tok::identifier;
1560 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1562 if (ExpectAndConsume(tok::comma)) {
1567 SourceRange MatchingCTypeRange;
1568 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1569 if (MatchingCType.isInvalid()) {
1574 bool LayoutCompatible = false;
1575 bool MustBeNull = false;
1576 while (TryConsumeToken(tok::comma)) {
1577 if (Tok.isNot(tok::identifier)) {
1578 Diag(Tok, diag::err_expected) << tok::identifier;
1582 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1583 if (Flag->isStr("layout_compatible"))
1584 LayoutCompatible = true;
1585 else if (Flag->isStr("must_be_null"))
1588 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1592 ConsumeToken(); // consume flag
1595 if (!T.consumeClose()) {
1596 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1597 ArgumentKind, MatchingCType.get(),
1598 LayoutCompatible, MustBeNull, Syntax);
1602 *EndLoc = T.getCloseLocation();
1605 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1606 /// of a C++11 attribute-specifier in a location where an attribute is not
1607 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1610 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1611 /// this doesn't appear to actually be an attribute-specifier, and the caller
1612 /// should try to parse it.
1613 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1614 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1616 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1617 case CAK_NotAttributeSpecifier:
1618 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1621 case CAK_InvalidAttributeSpecifier:
1622 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1625 case CAK_AttributeSpecifier:
1626 // Parse and discard the attributes.
1627 SourceLocation BeginLoc = ConsumeBracket();
1629 SkipUntil(tok::r_square);
1630 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1631 SourceLocation EndLoc = ConsumeBracket();
1632 Diag(BeginLoc, diag::err_attributes_not_allowed)
1633 << SourceRange(BeginLoc, EndLoc);
1636 llvm_unreachable("All cases handled above.");
1639 /// We have found the opening square brackets of a C++11
1640 /// attribute-specifier in a location where an attribute is not permitted, but
1641 /// we know where the attributes ought to be written. Parse them anyway, and
1642 /// provide a fixit moving them to the right place.
1643 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1644 SourceLocation CorrectLocation) {
1645 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1646 Tok.is(tok::kw_alignas));
1648 // Consume the attributes.
1649 SourceLocation Loc = Tok.getLocation();
1650 ParseCXX11Attributes(Attrs);
1651 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1652 // FIXME: use err_attributes_misplaced
1653 Diag(Loc, diag::err_attributes_not_allowed)
1654 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1655 << FixItHint::CreateRemoval(AttrRange);
1658 void Parser::DiagnoseProhibitedAttributes(
1659 const SourceRange &Range, const SourceLocation CorrectLocation) {
1660 if (CorrectLocation.isValid()) {
1661 CharSourceRange AttrRange(Range, true);
1662 Diag(CorrectLocation, diag::err_attributes_misplaced)
1663 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1664 << FixItHint::CreateRemoval(AttrRange);
1666 Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
1669 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1671 for (const ParsedAttr &AL : Attrs) {
1672 if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
1674 if (AL.getKind() == ParsedAttr::UnknownAttribute)
1675 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL.getName();
1677 Diag(AL.getLoc(), DiagID) << AL.getName();
1683 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1684 // applies to var, not the type Foo.
1685 // As an exception to the rule, __declspec(align(...)) before the
1686 // class-key affects the type instead of the variable.
1687 // Also, Microsoft-style [attributes] seem to affect the type instead of the
1689 // This function moves attributes that should apply to the type off DS to Attrs.
1690 void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1692 Sema::TagUseKind TUK) {
1693 if (TUK == Sema::TUK_Reference)
1696 llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
1698 for (ParsedAttr &AL : DS.getAttributes()) {
1699 if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1700 AL.isDeclspecAttribute()) ||
1701 AL.isMicrosoftAttribute())
1702 ToBeMoved.push_back(&AL);
1705 for (ParsedAttr *AL : ToBeMoved) {
1706 DS.getAttributes().remove(AL);
1711 /// ParseDeclaration - Parse a full 'declaration', which consists of
1712 /// declaration-specifiers, some number of declarators, and a semicolon.
1713 /// 'Context' should be a DeclaratorContext value. This returns the
1714 /// location of the semicolon in DeclEnd.
1716 /// declaration: [C99 6.7]
1717 /// block-declaration ->
1718 /// simple-declaration
1720 /// [C++] template-declaration
1721 /// [C++] namespace-definition
1722 /// [C++] using-directive
1723 /// [C++] using-declaration
1724 /// [C++11/C11] static_assert-declaration
1725 /// others... [FIXME]
1727 Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
1728 SourceLocation &DeclEnd,
1729 ParsedAttributesWithRange &attrs) {
1730 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1731 // Must temporarily exit the objective-c container scope for
1732 // parsing c none objective-c decls.
1733 ObjCDeclContextSwitch ObjCDC(*this);
1735 Decl *SingleDecl = nullptr;
1736 switch (Tok.getKind()) {
1737 case tok::kw_template:
1738 case tok::kw_export:
1739 ProhibitAttributes(attrs);
1740 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
1742 case tok::kw_inline:
1743 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1744 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1745 ProhibitAttributes(attrs);
1746 SourceLocation InlineLoc = ConsumeToken();
1747 return ParseNamespace(Context, DeclEnd, InlineLoc);
1749 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
1751 case tok::kw_namespace:
1752 ProhibitAttributes(attrs);
1753 return ParseNamespace(Context, DeclEnd);
1755 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1757 case tok::kw_static_assert:
1758 case tok::kw__Static_assert:
1759 ProhibitAttributes(attrs);
1760 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1763 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
1766 // This routine returns a DeclGroup, if the thing we parsed only contains a
1767 // single decl, convert it now.
1768 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1771 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1772 /// declaration-specifiers init-declarator-list[opt] ';'
1773 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1774 /// init-declarator-list ';'
1775 ///[C90/C++]init-declarator-list ';' [TODO]
1776 /// [OMP] threadprivate-directive
1777 /// [OMP] allocate-directive [TODO]
1779 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1780 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1782 /// If RequireSemi is false, this does not check for a ';' at the end of the
1783 /// declaration. If it is true, it checks for and eats it.
1785 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1786 /// of a simple-declaration. If we find that we are, we also parse the
1787 /// for-range-initializer, and place it here.
1788 Parser::DeclGroupPtrTy
1789 Parser::ParseSimpleDeclaration(DeclaratorContext Context,
1790 SourceLocation &DeclEnd,
1791 ParsedAttributesWithRange &Attrs,
1792 bool RequireSemi, ForRangeInit *FRI) {
1793 // Parse the common declaration-specifiers piece.
1794 ParsingDeclSpec DS(*this);
1796 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1797 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1799 // If we had a free-standing type definition with a missing semicolon, we
1800 // may get this far before the problem becomes obvious.
1801 if (DS.hasTagDefinition() &&
1802 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1805 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1806 // declaration-specifiers init-declarator-list[opt] ';'
1807 if (Tok.is(tok::semi)) {
1808 ProhibitAttributes(Attrs);
1809 DeclEnd = Tok.getLocation();
1810 if (RequireSemi) ConsumeToken();
1811 RecordDecl *AnonRecord = nullptr;
1812 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1814 DS.complete(TheDecl);
1816 Decl* decls[] = {AnonRecord, TheDecl};
1817 return Actions.BuildDeclaratorGroup(decls);
1819 return Actions.ConvertDeclToDeclGroup(TheDecl);
1822 DS.takeAttributesFrom(Attrs);
1823 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1826 /// Returns true if this might be the start of a declarator, or a common typo
1827 /// for a declarator.
1828 bool Parser::MightBeDeclarator(DeclaratorContext Context) {
1829 switch (Tok.getKind()) {
1830 case tok::annot_cxxscope:
1831 case tok::annot_template_id:
1833 case tok::code_completion:
1834 case tok::coloncolon:
1836 case tok::kw___attribute:
1837 case tok::kw_operator:
1844 return getLangOpts().CPlusPlus;
1846 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1847 return Context == DeclaratorContext::MemberContext &&
1848 getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
1850 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1851 return Context == DeclaratorContext::MemberContext ||
1852 getLangOpts().CPlusPlus;
1854 case tok::identifier:
1855 switch (NextToken().getKind()) {
1856 case tok::code_completion:
1857 case tok::coloncolon:
1860 case tok::equalequal: // Might be a typo for '='.
1861 case tok::kw_alignas:
1863 case tok::kw___attribute:
1875 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1876 // and in block scope it's probably a label. Inside a class definition,
1877 // this is a bit-field.
1878 return Context == DeclaratorContext::MemberContext ||
1879 (getLangOpts().CPlusPlus &&
1880 Context == DeclaratorContext::FileContext);
1882 case tok::identifier: // Possible virt-specifier.
1883 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1894 /// Skip until we reach something which seems like a sensible place to pick
1895 /// up parsing after a malformed declaration. This will sometimes stop sooner
1896 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1897 void Parser::SkipMalformedDecl() {
1899 switch (Tok.getKind()) {
1901 // Skip until matching }, then stop. We've probably skipped over
1902 // a malformed class or function definition or similar.
1904 SkipUntil(tok::r_brace);
1905 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1906 // This declaration isn't over yet. Keep skipping.
1909 TryConsumeToken(tok::semi);
1914 SkipUntil(tok::r_square);
1919 SkipUntil(tok::r_paren);
1929 case tok::kw_inline:
1930 // 'inline namespace' at the start of a line is almost certainly
1931 // a good place to pick back up parsing, except in an Objective-C
1932 // @interface context.
1933 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1934 (!ParsingInObjCContainer || CurParsedObjCImpl))
1938 case tok::kw_namespace:
1939 // 'namespace' at the start of a line is almost certainly a good
1940 // place to pick back up parsing, except in an Objective-C
1941 // @interface context.
1942 if (Tok.isAtStartOfLine() &&
1943 (!ParsingInObjCContainer || CurParsedObjCImpl))
1948 // @end is very much like } in Objective-C contexts.
1949 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1950 ParsingInObjCContainer)
1956 // - and + probably start new method declarations in Objective-C contexts.
1957 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1962 case tok::annot_module_begin:
1963 case tok::annot_module_end:
1964 case tok::annot_module_include:
1975 /// ParseDeclGroup - Having concluded that this is either a function
1976 /// definition or a group of object declarations, actually parse the
1978 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1979 DeclaratorContext Context,
1980 SourceLocation *DeclEnd,
1981 ForRangeInit *FRI) {
1982 // Parse the first declarator.
1983 ParsingDeclarator D(*this, DS, Context);
1986 // Bail out if the first declarator didn't seem well-formed.
1987 if (!D.hasName() && !D.mayOmitIdentifier()) {
1988 SkipMalformedDecl();
1992 // Save late-parsed attributes for now; they need to be parsed in the
1993 // appropriate function scope after the function Decl has been constructed.
1994 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1995 LateParsedAttrList LateParsedAttrs(true);
1996 if (D.isFunctionDeclarator()) {
1997 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1999 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
2000 // attribute. If we find the keyword here, tell the user to put it
2001 // at the start instead.
2002 if (Tok.is(tok::kw__Noreturn)) {
2003 SourceLocation Loc = ConsumeToken();
2004 const char *PrevSpec;
2007 // We can offer a fixit if it's valid to mark this function as _Noreturn
2008 // and we don't have any other declarators in this declaration.
2009 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2010 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2011 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
2013 Diag(Loc, diag::err_c11_noreturn_misplaced)
2014 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
2015 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
2020 // Check to see if we have a function *definition* which must have a body.
2021 if (D.isFunctionDeclarator() &&
2022 // Look at the next token to make sure that this isn't a function
2023 // declaration. We have to check this because __attribute__ might be the
2024 // start of a function definition in GCC-extended K&R C.
2025 !isDeclarationAfterDeclarator()) {
2027 // Function definitions are only allowed at file scope and in C++ classes.
2028 // The C++ inline method definition case is handled elsewhere, so we only
2029 // need to handle the file scope definition case.
2030 if (Context == DeclaratorContext::FileContext) {
2031 if (isStartOfFunctionDefinition(D)) {
2032 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2033 Diag(Tok, diag::err_function_declared_typedef);
2035 // Recover by treating the 'typedef' as spurious.
2036 DS.ClearStorageClassSpecs();
2040 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
2041 return Actions.ConvertDeclToDeclGroup(TheDecl);
2044 if (isDeclarationSpecifier()) {
2045 // If there is an invalid declaration specifier right after the
2046 // function prototype, then we must be in a missing semicolon case
2047 // where this isn't actually a body. Just fall through into the code
2048 // that handles it as a prototype, and let the top-level code handle
2049 // the erroneous declspec where it would otherwise expect a comma or
2052 Diag(Tok, diag::err_expected_fn_body);
2053 SkipUntil(tok::semi);
2057 if (Tok.is(tok::l_brace)) {
2058 Diag(Tok, diag::err_function_definition_not_allowed);
2059 SkipMalformedDecl();
2065 if (ParseAsmAttributesAfterDeclarator(D))
2068 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2069 // must parse and analyze the for-range-initializer before the declaration is
2072 // Handle the Objective-C for-in loop variable similarly, although we
2073 // don't need to parse the container in advance.
2074 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2075 bool IsForRangeLoop = false;
2076 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2077 IsForRangeLoop = true;
2078 if (Tok.is(tok::l_brace))
2079 FRI->RangeExpr = ParseBraceInitializer();
2081 FRI->RangeExpr = ParseExpression();
2084 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2085 if (IsForRangeLoop) {
2086 Actions.ActOnCXXForRangeDecl(ThisDecl);
2089 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2090 VD->setObjCForDecl(true);
2092 Actions.FinalizeDeclaration(ThisDecl);
2093 D.complete(ThisDecl);
2094 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2097 SmallVector<Decl *, 8> DeclsInGroup;
2098 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2099 D, ParsedTemplateInfo(), FRI);
2100 if (LateParsedAttrs.size() > 0)
2101 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2102 D.complete(FirstDecl);
2104 DeclsInGroup.push_back(FirstDecl);
2106 bool ExpectSemi = Context != DeclaratorContext::ForContext;
2108 // If we don't have a comma, it is either the end of the list (a ';') or an
2110 SourceLocation CommaLoc;
2111 while (TryConsumeToken(tok::comma, CommaLoc)) {
2112 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2113 // This comma was followed by a line-break and something which can't be
2114 // the start of a declarator. The comma was probably a typo for a
2116 Diag(CommaLoc, diag::err_expected_semi_declaration)
2117 << FixItHint::CreateReplacement(CommaLoc, ";");
2122 // Parse the next declarator.
2124 D.setCommaLoc(CommaLoc);
2126 // Accept attributes in an init-declarator. In the first declarator in a
2127 // declaration, these would be part of the declspec. In subsequent
2128 // declarators, they become part of the declarator itself, so that they
2129 // don't apply to declarators after *this* one. Examples:
2130 // short __attribute__((common)) var; -> declspec
2131 // short var __attribute__((common)); -> declarator
2132 // short x, __attribute__((common)) var; -> declarator
2133 MaybeParseGNUAttributes(D);
2135 // MSVC parses but ignores qualifiers after the comma as an extension.
2136 if (getLangOpts().MicrosoftExt)
2137 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2140 if (!D.isInvalidType()) {
2141 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2142 D.complete(ThisDecl);
2144 DeclsInGroup.push_back(ThisDecl);
2149 *DeclEnd = Tok.getLocation();
2152 ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
2153 ? diag::err_invalid_token_after_toplevel_declarator
2154 : diag::err_expected_semi_declaration)) {
2155 // Okay, there was no semicolon and one was expected. If we see a
2156 // declaration specifier, just assume it was missing and continue parsing.
2157 // Otherwise things are very confused and we skip to recover.
2158 if (!isDeclarationSpecifier()) {
2159 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2160 TryConsumeToken(tok::semi);
2164 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2167 /// Parse an optional simple-asm-expr and attributes, and attach them to a
2168 /// declarator. Returns true on an error.
2169 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2170 // If a simple-asm-expr is present, parse it.
2171 if (Tok.is(tok::kw_asm)) {
2173 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2174 if (AsmLabel.isInvalid()) {
2175 SkipUntil(tok::semi, StopBeforeMatch);
2179 D.setAsmLabel(AsmLabel.get());
2183 MaybeParseGNUAttributes(D);
2187 /// Parse 'declaration' after parsing 'declaration-specifiers
2188 /// declarator'. This method parses the remainder of the declaration
2189 /// (including any attributes or initializer, among other things) and
2190 /// finalizes the declaration.
2192 /// init-declarator: [C99 6.7]
2194 /// declarator '=' initializer
2195 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2196 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2197 /// [C++] declarator initializer[opt]
2199 /// [C++] initializer:
2200 /// [C++] '=' initializer-clause
2201 /// [C++] '(' expression-list ')'
2202 /// [C++0x] '=' 'default' [TODO]
2203 /// [C++0x] '=' 'delete'
2204 /// [C++0x] braced-init-list
2206 /// According to the standard grammar, =default and =delete are function
2207 /// definitions, but that definitely doesn't fit with the parser here.
2209 Decl *Parser::ParseDeclarationAfterDeclarator(
2210 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2211 if (ParseAsmAttributesAfterDeclarator(D))
2214 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2217 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2218 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2219 // RAII type used to track whether we're inside an initializer.
2220 struct InitializerScopeRAII {
2225 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2226 : P(P), D(D), ThisDecl(ThisDecl) {
2227 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2229 if (D.getCXXScopeSpec().isSet()) {
2231 S = P.getCurScope();
2233 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2236 ~InitializerScopeRAII() { pop(); }
2238 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2240 if (D.getCXXScopeSpec().isSet())
2241 S = P.getCurScope();
2242 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2250 // Inform the current actions module that we just parsed this declarator.
2251 Decl *ThisDecl = nullptr;
2252 switch (TemplateInfo.Kind) {
2253 case ParsedTemplateInfo::NonTemplate:
2254 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2257 case ParsedTemplateInfo::Template:
2258 case ParsedTemplateInfo::ExplicitSpecialization: {
2259 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2260 *TemplateInfo.TemplateParams,
2262 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
2263 // Re-direct this decl to refer to the templated decl so that we can
2265 ThisDecl = VT->getTemplatedDecl();
2268 case ParsedTemplateInfo::ExplicitInstantiation: {
2269 if (Tok.is(tok::semi)) {
2270 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2271 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2272 if (ThisRes.isInvalid()) {
2273 SkipUntil(tok::semi, StopBeforeMatch);
2276 ThisDecl = ThisRes.get();
2278 // FIXME: This check should be for a variable template instantiation only.
2280 // Check that this is a valid instantiation
2281 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
2282 // If the declarator-id is not a template-id, issue a diagnostic and
2283 // recover by ignoring the 'template' keyword.
2284 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2285 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2286 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2288 SourceLocation LAngleLoc =
2289 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2290 Diag(D.getIdentifierLoc(),
2291 diag::err_explicit_instantiation_with_definition)
2292 << SourceRange(TemplateInfo.TemplateLoc)
2293 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2295 // Recover as if it were an explicit specialization.
2296 TemplateParameterLists FakedParamLists;
2297 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2298 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
2299 LAngleLoc, nullptr));
2302 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2309 // Parse declarator '=' initializer.
2310 // If a '==' or '+=' is found, suggest a fixit to '='.
2311 if (isTokenEqualOrEqualTypo()) {
2312 SourceLocation EqualLoc = ConsumeToken();
2314 if (Tok.is(tok::kw_delete)) {
2315 if (D.isFunctionDeclarator())
2316 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2319 Diag(ConsumeToken(), diag::err_deleted_non_function);
2320 } else if (Tok.is(tok::kw_default)) {
2321 if (D.isFunctionDeclarator())
2322 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2325 Diag(ConsumeToken(), diag::err_default_special_members);
2327 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2329 if (Tok.is(tok::code_completion)) {
2330 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2331 Actions.FinalizeDeclaration(ThisDecl);
2336 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2337 ExprResult Init = ParseInitializer();
2339 // If this is the only decl in (possibly) range based for statement,
2340 // our best guess is that the user meant ':' instead of '='.
2341 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2342 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2343 << FixItHint::CreateReplacement(EqualLoc, ":");
2344 // We are trying to stop parser from looking for ';' in this for
2345 // statement, therefore preventing spurious errors to be issued.
2346 FRI->ColonLoc = EqualLoc;
2348 FRI->RangeExpr = Init;
2353 if (Init.isInvalid()) {
2354 SmallVector<tok::TokenKind, 2> StopTokens;
2355 StopTokens.push_back(tok::comma);
2356 if (D.getContext() == DeclaratorContext::ForContext ||
2357 D.getContext() == DeclaratorContext::InitStmtContext)
2358 StopTokens.push_back(tok::r_paren);
2359 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2360 Actions.ActOnInitializerError(ThisDecl);
2362 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2363 /*DirectInit=*/false);
2365 } else if (Tok.is(tok::l_paren)) {
2366 // Parse C++ direct initializer: '(' expression-list ')'
2367 BalancedDelimiterTracker T(*this, tok::l_paren);
2371 CommaLocsTy CommaLocs;
2373 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2375 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2376 auto RunSignatureHelp = [&]() {
2377 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2378 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2379 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2380 CalledSignatureHelp = true;
2381 return PreferredType;
2383 auto SetPreferredType = [&] {
2384 PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2387 llvm::function_ref<void()> ExpressionStarts;
2389 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2390 // VarDecl. This is an error and it is reported in a call to
2391 // Actions.ActOnInitializerError(). However, we call
2392 // ProduceConstructorSignatureHelp only on VarDecls.
2393 ExpressionStarts = SetPreferredType;
2395 if (ParseExpressionList(Exprs, CommaLocs, ExpressionStarts)) {
2396 if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2397 Actions.ProduceConstructorSignatureHelp(
2398 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2399 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2400 CalledSignatureHelp = true;
2402 Actions.ActOnInitializerError(ThisDecl);
2403 SkipUntil(tok::r_paren, StopAtSemi);
2408 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2409 "Unexpected number of commas!");
2413 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2414 T.getCloseLocation(),
2416 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2417 /*DirectInit=*/true);
2419 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2420 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
2421 // Parse C++0x braced-init-list.
2422 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2424 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2426 ExprResult Init(ParseBraceInitializer());
2430 if (Init.isInvalid()) {
2431 Actions.ActOnInitializerError(ThisDecl);
2433 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2436 Actions.ActOnUninitializedDecl(ThisDecl);
2439 Actions.FinalizeDeclaration(ThisDecl);
2444 /// ParseSpecifierQualifierList
2445 /// specifier-qualifier-list:
2446 /// type-specifier specifier-qualifier-list[opt]
2447 /// type-qualifier specifier-qualifier-list[opt]
2448 /// [GNU] attributes specifier-qualifier-list[opt]
2450 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2451 DeclSpecContext DSC) {
2452 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2453 /// parse declaration-specifiers and complain about extra stuff.
2454 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2455 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2457 // Validate declspec for type-name.
2458 unsigned Specs = DS.getParsedSpecifiers();
2459 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2460 Diag(Tok, diag::err_expected_type);
2461 DS.SetTypeSpecError();
2462 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2463 Diag(Tok, diag::err_typename_requires_specqual);
2464 if (!DS.hasTypeSpecifier())
2465 DS.SetTypeSpecError();
2468 // Issue diagnostic and remove storage class if present.
2469 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2470 if (DS.getStorageClassSpecLoc().isValid())
2471 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2473 Diag(DS.getThreadStorageClassSpecLoc(),
2474 diag::err_typename_invalid_storageclass);
2475 DS.ClearStorageClassSpecs();
2478 // Issue diagnostic and remove function specifier if present.
2479 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2480 if (DS.isInlineSpecified())
2481 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2482 if (DS.isVirtualSpecified())
2483 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2484 if (DS.hasExplicitSpecifier())
2485 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2486 DS.ClearFunctionSpecs();
2489 // Issue diagnostic and remove constexpr specifier if present.
2490 if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2491 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2492 << (DS.getConstexprSpecifier() == CSK_consteval);
2493 DS.ClearConstexprSpec();
2497 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2498 /// specified token is valid after the identifier in a declarator which
2499 /// immediately follows the declspec. For example, these things are valid:
2501 /// int x [ 4]; // direct-declarator
2502 /// int x ( int y); // direct-declarator
2503 /// int(int x ) // direct-declarator
2504 /// int x ; // simple-declaration
2505 /// int x = 17; // init-declarator-list
2506 /// int x , y; // init-declarator-list
2507 /// int x __asm__ ("foo"); // init-declarator-list
2508 /// int x : 4; // struct-declarator
2509 /// int x { 5}; // C++'0x unified initializers
2511 /// This is not, because 'x' does not immediately follow the declspec (though
2512 /// ')' happens to be valid anyway).
2515 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2516 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2517 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2521 /// ParseImplicitInt - This method is called when we have an non-typename
2522 /// identifier in a declspec (which normally terminates the decl spec) when
2523 /// the declspec has no type specifier. In this case, the declspec is either
2524 /// malformed or is "implicit int" (in K&R and C89).
2526 /// This method handles diagnosing this prettily and returns false if the
2527 /// declspec is done being processed. If it recovers and thinks there may be
2528 /// other pieces of declspec after it, it returns true.
2530 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2531 const ParsedTemplateInfo &TemplateInfo,
2532 AccessSpecifier AS, DeclSpecContext DSC,
2533 ParsedAttributesWithRange &Attrs) {
2534 assert(Tok.is(tok::identifier) && "should have identifier");
2536 SourceLocation Loc = Tok.getLocation();
2537 // If we see an identifier that is not a type name, we normally would
2538 // parse it as the identifier being declared. However, when a typename
2539 // is typo'd or the definition is not included, this will incorrectly
2540 // parse the typename as the identifier name and fall over misparsing
2541 // later parts of the diagnostic.
2543 // As such, we try to do some look-ahead in cases where this would
2544 // otherwise be an "implicit-int" case to see if this is invalid. For
2545 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2546 // an identifier with implicit int, we'd get a parse error because the
2547 // next token is obviously invalid for a type. Parse these as a case
2548 // with an invalid type specifier.
2549 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2551 // Since we know that this either implicit int (which is rare) or an
2552 // error, do lookahead to try to do better recovery. This never applies
2553 // within a type specifier. Outside of C++, we allow this even if the
2554 // language doesn't "officially" support implicit int -- we support
2555 // implicit int as an extension in C99 and C11.
2556 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2557 isValidAfterIdentifierInDeclarator(NextToken())) {
2558 // If this token is valid for implicit int, e.g. "static x = 4", then
2559 // we just avoid eating the identifier, so it will be parsed as the
2560 // identifier in the declarator.
2564 // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2565 // for incomplete declarations such as `pipe p`.
2566 if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
2569 if (getLangOpts().CPlusPlus &&
2570 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2571 // Don't require a type specifier if we have the 'auto' storage class
2572 // specifier in C++98 -- we'll promote it to a type specifier.
2574 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2578 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2579 getLangOpts().MSVCCompat) {
2580 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2581 // Give Sema a chance to recover if we are in a template with dependent base
2583 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2584 *Tok.getIdentifierInfo(), Tok.getLocation(),
2585 DSC == DeclSpecContext::DSC_template_type_arg)) {
2586 const char *PrevSpec;
2588 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2589 Actions.getASTContext().getPrintingPolicy());
2590 DS.SetRangeEnd(Tok.getLocation());
2596 // Otherwise, if we don't consume this token, we are going to emit an
2597 // error anyway. Try to recover from various common problems. Check
2598 // to see if this was a reference to a tag name without a tag specified.
2599 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2601 // C++ doesn't need this, and isTagName doesn't take SS.
2602 if (SS == nullptr) {
2603 const char *TagName = nullptr, *FixitTagName = nullptr;
2604 tok::TokenKind TagKind = tok::unknown;
2606 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2608 case DeclSpec::TST_enum:
2609 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2610 case DeclSpec::TST_union:
2611 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2612 case DeclSpec::TST_struct:
2613 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2614 case DeclSpec::TST_interface:
2615 TagName="__interface"; FixitTagName = "__interface ";
2616 TagKind=tok::kw___interface;break;
2617 case DeclSpec::TST_class:
2618 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2622 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2623 LookupResult R(Actions, TokenName, SourceLocation(),
2624 Sema::LookupOrdinaryName);
2626 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2627 << TokenName << TagName << getLangOpts().CPlusPlus
2628 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2630 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2631 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2633 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2634 << TokenName << TagName;
2637 // Parse this as a tag as if the missing tag were present.
2638 if (TagKind == tok::kw_enum)
2639 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2640 DeclSpecContext::DSC_normal);
2642 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2643 /*EnteringContext*/ false,
2644 DeclSpecContext::DSC_normal, Attrs);
2649 // Determine whether this identifier could plausibly be the name of something
2650 // being declared (with a missing type).
2651 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2652 DSC == DeclSpecContext::DSC_class)) {
2653 // Look ahead to the next token to try to figure out what this declaration
2654 // was supposed to be.
2655 switch (NextToken().getKind()) {
2656 case tok::l_paren: {
2657 // static x(4); // 'x' is not a type
2658 // x(int n); // 'x' is not a type
2659 // x (*p)[]; // 'x' is a type
2661 // Since we're in an error case, we can afford to perform a tentative
2662 // parse to determine which case we're in.
2663 TentativeParsingAction PA(*this);
2665 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2668 if (TPR != TPResult::False) {
2669 // The identifier is followed by a parenthesized declarator.
2670 // It's supposed to be a type.
2674 // If we're in a context where we could be declaring a constructor,
2675 // check whether this is a constructor declaration with a bogus name.
2676 if (DSC == DeclSpecContext::DSC_class ||
2677 (DSC == DeclSpecContext::DSC_top_level && SS)) {
2678 IdentifierInfo *II = Tok.getIdentifierInfo();
2679 if (Actions.isCurrentClassNameTypo(II, SS)) {
2680 Diag(Loc, diag::err_constructor_bad_name)
2681 << Tok.getIdentifierInfo() << II
2682 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2683 Tok.setIdentifierInfo(II);
2695 // This looks like a variable or function declaration. The type is
2696 // probably missing. We're done parsing decl-specifiers.
2697 // But only if we are not in a function prototype scope.
2698 if (getCurScope()->isFunctionPrototypeScope())
2701 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2705 // This is probably supposed to be a type. This includes cases like:
2707 // struct S { unsinged : 4; };
2712 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2713 // and attempt to recover.
2715 IdentifierInfo *II = Tok.getIdentifierInfo();
2716 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2717 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2720 // The action has suggested that the type T could be used. Set that as
2721 // the type in the declaration specifiers, consume the would-be type
2722 // name token, and we're done.
2723 const char *PrevSpec;
2725 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2726 Actions.getASTContext().getPrintingPolicy());
2727 DS.SetRangeEnd(Tok.getLocation());
2729 // There may be other declaration specifiers after this.
2731 } else if (II != Tok.getIdentifierInfo()) {
2732 // If no type was suggested, the correction is to a keyword
2733 Tok.setKind(II->getTokenID());
2734 // There may be other declaration specifiers after this.
2738 // Otherwise, the action had no suggestion for us. Mark this as an error.
2739 DS.SetTypeSpecError();
2740 DS.SetRangeEnd(Tok.getLocation());
2743 // Eat any following template arguments.
2744 if (IsTemplateName) {
2745 SourceLocation LAngle, RAngle;
2746 TemplateArgList Args;
2747 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2750 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2751 // avoid rippling error messages on subsequent uses of the same type,
2752 // could be useful if #include was forgotten.
2756 /// Determine the declaration specifier context from the declarator
2759 /// \param Context the declarator context, which is one of the
2760 /// DeclaratorContext enumerator values.
2761 Parser::DeclSpecContext
2762 Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2763 if (Context == DeclaratorContext::MemberContext)
2764 return DeclSpecContext::DSC_class;
2765 if (Context == DeclaratorContext::FileContext)
2766 return DeclSpecContext::DSC_top_level;
2767 if (Context == DeclaratorContext::TemplateParamContext)
2768 return DeclSpecContext::DSC_template_param;
2769 if (Context == DeclaratorContext::TemplateArgContext ||
2770 Context == DeclaratorContext::TemplateTypeArgContext)
2771 return DeclSpecContext::DSC_template_type_arg;
2772 if (Context == DeclaratorContext::TrailingReturnContext ||
2773 Context == DeclaratorContext::TrailingReturnVarContext)
2774 return DeclSpecContext::DSC_trailing;
2775 if (Context == DeclaratorContext::AliasDeclContext ||
2776 Context == DeclaratorContext::AliasTemplateContext)
2777 return DeclSpecContext::DSC_alias_declaration;
2778 return DeclSpecContext::DSC_normal;
2781 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2783 /// FIXME: Simply returns an alignof() expression if the argument is a
2784 /// type. Ideally, the type should be propagated directly into Sema.
2787 /// [C11] constant-expression
2788 /// [C++0x] type-id ...[opt]
2789 /// [C++0x] assignment-expression ...[opt]
2790 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2791 SourceLocation &EllipsisLoc) {
2793 if (isTypeIdInParens()) {
2794 SourceLocation TypeLoc = Tok.getLocation();
2795 ParsedType Ty = ParseTypeName().get();
2796 SourceRange TypeRange(Start, Tok.getLocation());
2797 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2798 Ty.getAsOpaquePtr(), TypeRange);
2800 ER = ParseConstantExpression();
2802 if (getLangOpts().CPlusPlus11)
2803 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2808 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2809 /// attribute to Attrs.
2811 /// alignment-specifier:
2812 /// [C11] '_Alignas' '(' type-id ')'
2813 /// [C11] '_Alignas' '(' constant-expression ')'
2814 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2815 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2816 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2817 SourceLocation *EndLoc) {
2818 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2819 "Not an alignment-specifier!");
2821 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2822 SourceLocation KWLoc = ConsumeToken();
2824 BalancedDelimiterTracker T(*this, tok::l_paren);
2825 if (T.expectAndConsume())
2828 SourceLocation EllipsisLoc;
2829 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2830 if (ArgExpr.isInvalid()) {
2837 *EndLoc = T.getCloseLocation();
2839 ArgsVector ArgExprs;
2840 ArgExprs.push_back(ArgExpr.get());
2841 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2842 ParsedAttr::AS_Keyword, EllipsisLoc);
2845 /// Determine whether we're looking at something that might be a declarator
2846 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2847 /// diagnose a missing semicolon after a prior tag definition in the decl
2850 /// \return \c true if an error occurred and this can't be any kind of
2853 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2854 DeclSpecContext DSContext,
2855 LateParsedAttrList *LateAttrs) {
2856 assert(DS.hasTagDefinition() && "shouldn't call this");
2858 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2859 DSContext == DeclSpecContext::DSC_top_level);
2861 if (getLangOpts().CPlusPlus &&
2862 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2863 tok::annot_template_id) &&
2864 TryAnnotateCXXScopeToken(EnteringContext)) {
2865 SkipMalformedDecl();
2869 bool HasScope = Tok.is(tok::annot_cxxscope);
2870 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2871 Token AfterScope = HasScope ? NextToken() : Tok;
2873 // Determine whether the following tokens could possibly be a
2875 bool MightBeDeclarator = true;
2876 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2877 // A declarator-id can't start with 'typename'.
2878 MightBeDeclarator = false;
2879 } else if (AfterScope.is(tok::annot_template_id)) {
2880 // If we have a type expressed as a template-id, this cannot be a
2881 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2882 TemplateIdAnnotation *Annot =
2883 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2884 if (Annot->Kind == TNK_Type_template)
2885 MightBeDeclarator = false;
2886 } else if (AfterScope.is(tok::identifier)) {
2887 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2889 // These tokens cannot come after the declarator-id in a
2890 // simple-declaration, and are likely to come after a type-specifier.
2891 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2892 tok::annot_cxxscope, tok::coloncolon)) {
2893 // Missing a semicolon.
2894 MightBeDeclarator = false;
2895 } else if (HasScope) {
2896 // If the declarator-id has a scope specifier, it must redeclare a
2897 // previously-declared entity. If that's a type (and this is not a
2898 // typedef), that's an error.
2900 Actions.RestoreNestedNameSpecifierAnnotation(
2901 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2902 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2903 Sema::NameClassification Classification = Actions.ClassifyName(
2904 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2905 /*IsAddressOfOperand=*/false, /*CCC=*/nullptr);
2906 switch (Classification.getKind()) {
2907 case Sema::NC_Error:
2908 SkipMalformedDecl();
2911 case Sema::NC_Keyword:
2912 case Sema::NC_NestedNameSpecifier:
2913 llvm_unreachable("typo correction and nested name specifiers not "
2917 case Sema::NC_TypeTemplate:
2918 // Not a previously-declared non-type entity.
2919 MightBeDeclarator = false;
2922 case Sema::NC_Unknown:
2923 case Sema::NC_Expression:
2924 case Sema::NC_VarTemplate:
2925 case Sema::NC_FunctionTemplate:
2926 case Sema::NC_UndeclaredTemplate:
2927 // Might be a redeclaration of a prior entity.
2933 if (MightBeDeclarator)
2936 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2937 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
2938 diag::err_expected_after)
2939 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2941 // Try to recover from the typo, by dropping the tag definition and parsing
2942 // the problematic tokens as a type.
2944 // FIXME: Split the DeclSpec into pieces for the standalone
2945 // declaration and pieces for the following declaration, instead
2946 // of assuming that all the other pieces attach to new declaration,
2947 // and call ParsedFreeStandingDeclSpec as appropriate.
2948 DS.ClearTypeSpecType();
2949 ParsedTemplateInfo NotATemplate;
2950 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2954 // Choose the apprpriate diagnostic error for why fixed point types are
2955 // disabled, set the previous specifier, and mark as invalid.
2956 static void SetupFixedPointError(const LangOptions &LangOpts,
2957 const char *&PrevSpec, unsigned &DiagID,
2959 assert(!LangOpts.FixedPoint);
2960 DiagID = diag::err_fixed_point_not_enabled;
2961 PrevSpec = ""; // Not used by diagnostic
2965 /// ParseDeclarationSpecifiers
2966 /// declaration-specifiers: [C99 6.7]
2967 /// storage-class-specifier declaration-specifiers[opt]
2968 /// type-specifier declaration-specifiers[opt]
2969 /// [C99] function-specifier declaration-specifiers[opt]
2970 /// [C11] alignment-specifier declaration-specifiers[opt]
2971 /// [GNU] attributes declaration-specifiers[opt]
2972 /// [Clang] '__module_private__' declaration-specifiers[opt]
2973 /// [ObjC1] '__kindof' declaration-specifiers[opt]
2975 /// storage-class-specifier: [C99 6.7.1]
2982 /// [C++11] 'thread_local'
2983 /// [C11] '_Thread_local'
2984 /// [GNU] '__thread'
2985 /// function-specifier: [C99 6.7.4]
2988 /// [C++] 'explicit'
2989 /// [OpenCL] '__kernel'
2990 /// 'friend': [C++ dcl.friend]
2991 /// 'constexpr': [C++0x dcl.constexpr]
2992 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2993 const ParsedTemplateInfo &TemplateInfo,
2995 DeclSpecContext DSContext,
2996 LateParsedAttrList *LateAttrs) {
2997 if (DS.getSourceRange().isInvalid()) {
2998 // Start the range at the current token but make the end of the range
2999 // invalid. This will make the entire range invalid unless we successfully
3001 DS.SetRangeStart(Tok.getLocation());
3002 DS.SetRangeEnd(SourceLocation());
3005 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3006 DSContext == DeclSpecContext::DSC_top_level);
3007 bool AttrsLastTime = false;
3008 ParsedAttributesWithRange attrs(AttrFactory);
3009 // We use Sema's policy to get bool macros right.
3010 PrintingPolicy Policy = Actions.getPrintingPolicy();
3012 bool isInvalid = false;
3013 bool isStorageClass = false;
3014 const char *PrevSpec = nullptr;
3015 unsigned DiagID = 0;
3017 // This value needs to be set to the location of the last token if the last
3018 // token of the specifier is already consumed.
3019 SourceLocation ConsumedEnd;
3021 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3022 // implementation for VS2013 uses _Atomic as an identifier for one of the
3023 // classes in <atomic>.
3025 // A typedef declaration containing _Atomic<...> is among the places where
3026 // the class is used. If we are currently parsing such a declaration, treat
3027 // the token as an identifier.
3028 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3029 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
3030 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3031 Tok.setKind(tok::identifier);
3033 SourceLocation Loc = Tok.getLocation();
3035 switch (Tok.getKind()) {
3039 ProhibitAttributes(attrs);
3041 // Reject C++11 attributes that appertain to decl specifiers as
3042 // we don't support any C++11 attributes that appertain to decl
3043 // specifiers. This also conforms to what g++ 4.8 is doing.
3044 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
3046 DS.takeAttributesFrom(attrs);
3049 // If this is not a declaration specifier token, we're done reading decl
3050 // specifiers. First verify that DeclSpec's are consistent.
3051 DS.Finish(Actions, Policy);
3055 case tok::kw_alignas:
3056 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
3057 goto DoneWithDeclSpec;
3059 ProhibitAttributes(attrs);
3060 // FIXME: It would be good to recover by accepting the attributes,
3061 // but attempting to do that now would cause serious
3062 // madness in terms of diagnostics.
3064 attrs.Range = SourceRange();
3066 ParseCXX11Attributes(attrs);
3067 AttrsLastTime = true;
3070 case tok::code_completion: {
3071 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
3072 if (DS.hasTypeSpecifier()) {
3073 bool AllowNonIdentifiers
3074 = (getCurScope()->getFlags() & (Scope::ControlScope |
3076 Scope::TemplateParamScope |
3077 Scope::FunctionPrototypeScope |
3078 Scope::AtCatchScope)) == 0;
3079 bool AllowNestedNameSpecifiers
3080 = DSContext == DeclSpecContext::DSC_top_level ||
3081 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3083 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3084 AllowNonIdentifiers,
3085 AllowNestedNameSpecifiers);
3086 return cutOffParsing();
3089 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3090 CCC = Sema::PCC_LocalDeclarationSpecifiers;
3091 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3092 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3093 : Sema::PCC_Template;
3094 else if (DSContext == DeclSpecContext::DSC_class)
3095 CCC = Sema::PCC_Class;
3096 else if (CurParsedObjCImpl)
3097 CCC = Sema::PCC_ObjCImplementation;
3099 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3100 return cutOffParsing();
3103 case tok::coloncolon: // ::foo::bar
3104 // C++ scope specifier. Annotate and loop, or bail out on error.
3105 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3106 if (!DS.hasTypeSpecifier())
3107 DS.SetTypeSpecError();
3108 goto DoneWithDeclSpec;
3110 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3111 goto DoneWithDeclSpec;
3114 case tok::annot_cxxscope: {
3115 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3116 goto DoneWithDeclSpec;
3119 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3120 Tok.getAnnotationRange(),
3123 // We are looking for a qualified typename.
3124 Token Next = NextToken();
3125 if (Next.is(tok::annot_template_id) &&
3126 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3127 ->Kind == TNK_Type_template) {
3128 // We have a qualified template-id, e.g., N::A<int>
3130 // If this would be a valid constructor declaration with template
3131 // arguments, we will reject the attempt to form an invalid type-id
3132 // referring to the injected-class-name when we annotate the token,
3133 // per C++ [class.qual]p2.
3135 // To improve diagnostics for this case, parse the declaration as a
3136 // constructor (and reject the extra template arguments later).
3137 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
3138 if ((DSContext == DeclSpecContext::DSC_top_level ||
3139 DSContext == DeclSpecContext::DSC_class) &&
3141 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3142 isConstructorDeclarator(/*Unqualified*/ false)) {
3143 // The user meant this to be an out-of-line constructor
3144 // definition, but template arguments are not allowed
3145 // there. Just allow this as a constructor; we'll
3146 // complain about it later.
3147 goto DoneWithDeclSpec;
3150 DS.getTypeSpecScope() = SS;
3151 ConsumeAnnotationToken(); // The C++ scope.
3152 assert(Tok.is(tok::annot_template_id) &&
3153 "ParseOptionalCXXScopeSpecifier not working");
3154 AnnotateTemplateIdTokenAsType();
3158 if (Next.is(tok::annot_typename)) {
3159 DS.getTypeSpecScope() = SS;
3160 ConsumeAnnotationToken(); // The C++ scope.
3161 if (Tok.getAnnotationValue()) {
3162 ParsedType T = getTypeAnnotation(Tok);
3163 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3164 Tok.getAnnotationEndLoc(),
3165 PrevSpec, DiagID, T, Policy);
3170 DS.SetTypeSpecError();
3171 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3172 ConsumeAnnotationToken(); // The typename
3175 if (Next.isNot(tok::identifier))
3176 goto DoneWithDeclSpec;
3178 // Check whether this is a constructor declaration. If we're in a
3179 // context where the identifier could be a class name, and it has the
3180 // shape of a constructor declaration, process it as one.
3181 if ((DSContext == DeclSpecContext::DSC_top_level ||
3182 DSContext == DeclSpecContext::DSC_class) &&
3183 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3185 isConstructorDeclarator(/*Unqualified*/ false))
3186 goto DoneWithDeclSpec;
3188 ParsedType TypeRep =
3189 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3190 getCurScope(), &SS, false, false, nullptr,
3191 /*IsCtorOrDtorName=*/false,
3192 /*WantNontrivialTypeSourceInfo=*/true,
3193 isClassTemplateDeductionContext(DSContext));
3195 // If the referenced identifier is not a type, then this declspec is
3196 // erroneous: We already checked about that it has no type specifier, and
3197 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3200 // Eat the scope spec so the identifier is current.
3201 ConsumeAnnotationToken();
3202 ParsedAttributesWithRange Attrs(AttrFactory);
3203 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3204 if (!Attrs.empty()) {
3205 AttrsLastTime = true;
3206 attrs.takeAllFrom(Attrs);
3210 goto DoneWithDeclSpec;
3213 DS.getTypeSpecScope() = SS;
3214 ConsumeAnnotationToken(); // The C++ scope.
3216 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3217 DiagID, TypeRep, Policy);
3221 DS.SetRangeEnd(Tok.getLocation());
3222 ConsumeToken(); // The typename.
3227 case tok::annot_typename: {
3228 // If we've previously seen a tag definition, we were almost surely
3229 // missing a semicolon after it.
3230 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3231 goto DoneWithDeclSpec;
3233 if (Tok.getAnnotationValue()) {
3234 ParsedType T = getTypeAnnotation(Tok);
3235 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3238 DS.SetTypeSpecError();
3243 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3244 ConsumeAnnotationToken(); // The typename
3249 case tok::kw___is_signed:
3250 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3251 // typically treats it as a trait. If we see __is_signed as it appears
3252 // in libstdc++, e.g.,
3254 // static const bool __is_signed;
3256 // then treat __is_signed as an identifier rather than as a keyword.
3257 if (DS.getTypeSpecType() == TST_bool &&
3258 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3259 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3260 TryKeywordIdentFallback(true);
3262 // We're done with the declaration-specifiers.
3263 goto DoneWithDeclSpec;
3266 case tok::kw___super:
3267 case tok::kw_decltype:
3268 case tok::identifier: {
3269 // This identifier can only be a typedef name if we haven't already seen
3270 // a type-specifier. Without this check we misparse:
3271 // typedef int X; struct Y { short X; }; as 'short int'.
3272 if (DS.hasTypeSpecifier())
3273 goto DoneWithDeclSpec;
3275 // If the token is an identifier named "__declspec" and Microsoft
3276 // extensions are not enabled, it is likely that there will be cascading
3277 // parse errors if this really is a __declspec attribute. Attempt to
3278 // recognize that scenario and recover gracefully.
3279 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3280 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3281 Diag(Loc, diag::err_ms_attributes_not_enabled);
3283 // The next token should be an open paren. If it is, eat the entire
3284 // attribute declaration and continue.
3285 if (NextToken().is(tok::l_paren)) {
3286 // Consume the __declspec identifier.
3289 // Eat the parens and everything between them.
3290 BalancedDelimiterTracker T(*this, tok::l_paren);
3291 if (T.consumeOpen()) {
3292 assert(false && "Not a left paren?");
3300 // In C++, check to see if this is a scope specifier like foo::bar::, if
3301 // so handle it as such. This is important for ctor parsing.
3302 if (getLangOpts().CPlusPlus) {
3303 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3304 DS.SetTypeSpecError();
3305 goto DoneWithDeclSpec;
3307 if (!Tok.is(tok::identifier))
3311 // Check for need to substitute AltiVec keyword tokens.
3312 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3315 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3316 // allow the use of a typedef name as a type specifier.
3317 if (DS.isTypeAltiVecVector())
3318 goto DoneWithDeclSpec;
3320 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3321 isObjCInstancetype()) {
3322 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3324 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3325 DiagID, TypeRep, Policy);
3329 DS.SetRangeEnd(Loc);
3334 // If we're in a context where the identifier could be a class name,
3335 // check whether this is a constructor declaration.
3336 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3337 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3338 isConstructorDeclarator(/*Unqualified*/true))
3339 goto DoneWithDeclSpec;
3341 ParsedType TypeRep = Actions.getTypeName(
3342 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3343 false, false, nullptr, false, false,
3344 isClassTemplateDeductionContext(DSContext));
3346 // If this is not a typedef name, don't parse it as part of the declspec,
3347 // it must be an implicit int or an error.
3349 ParsedAttributesWithRange Attrs(AttrFactory);
3350 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3351 if (!Attrs.empty()) {
3352 AttrsLastTime = true;
3353 attrs.takeAllFrom(Attrs);
3357 goto DoneWithDeclSpec;
3360 // Likewise, if this is a context where the identifier could be a template
3361 // name, check whether this is a deduction guide declaration.
3362 if (getLangOpts().CPlusPlus17 &&
3363 (DSContext == DeclSpecContext::DSC_class ||
3364 DSContext == DeclSpecContext::DSC_top_level) &&
3365 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3366 Tok.getLocation()) &&
3367 isConstructorDeclarator(/*Unqualified*/ true,
3368 /*DeductionGuide*/ true))
3369 goto DoneWithDeclSpec;
3371 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3372 DiagID, TypeRep, Policy);
3376 DS.SetRangeEnd(Tok.getLocation());
3377 ConsumeToken(); // The identifier
3379 // Objective-C supports type arguments and protocol references
3380 // following an Objective-C object or object pointer
3381 // type. Handle either one of them.
3382 if (Tok.is(tok::less) && getLangOpts().ObjC) {
3383 SourceLocation NewEndLoc;
3384 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3385 Loc, TypeRep, /*consumeLastToken=*/true,
3387 if (NewTypeRep.isUsable()) {
3388 DS.UpdateTypeRep(NewTypeRep.get());
3389 DS.SetRangeEnd(NewEndLoc);
3393 // Need to support trailing type qualifiers (e.g. "id<p> const").
3394 // If a type specifier follows, it will be diagnosed elsewhere.
3399 case tok::annot_template_id: {
3400 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3401 if (TemplateId->Kind != TNK_Type_template &&
3402 TemplateId->Kind != TNK_Undeclared_template) {
3403 // This template-id does not refer to a type name, so we're
3404 // done with the type-specifiers.
3405 goto DoneWithDeclSpec;
3408 // If we're in a context where the template-id could be a
3409 // constructor name or specialization, check whether this is a
3410 // constructor declaration.
3411 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3412 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3413 isConstructorDeclarator(TemplateId->SS.isEmpty()))
3414 goto DoneWithDeclSpec;
3416 // Turn the template-id annotation token into a type annotation
3417 // token, then try again to parse it as a type-specifier.
3418 AnnotateTemplateIdTokenAsType();
3422 // GNU attributes support.
3423 case tok::kw___attribute:
3424 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3427 // Microsoft declspec support.
3428 case tok::kw___declspec:
3429 ParseMicrosoftDeclSpecs(DS.getAttributes());
3432 // Microsoft single token adornments.
3433 case tok::kw___forceinline: {
3434 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3435 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3436 SourceLocation AttrNameLoc = Tok.getLocation();
3437 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3438 nullptr, 0, ParsedAttr::AS_Keyword);
3442 case tok::kw___unaligned:
3443 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3447 case tok::kw___sptr:
3448 case tok::kw___uptr:
3449 case tok::kw___ptr64:
3450 case tok::kw___ptr32:
3452 case tok::kw___cdecl:
3453 case tok::kw___stdcall:
3454 case tok::kw___fastcall:
3455 case tok::kw___thiscall:
3456 case tok::kw___regcall:
3457 case tok::kw___vectorcall:
3458 ParseMicrosoftTypeAttributes(DS.getAttributes());
3461 // Borland single token adornments.
3462 case tok::kw___pascal:
3463 ParseBorlandTypeAttributes(DS.getAttributes());
3466 // OpenCL single token adornments.
3467 case tok::kw___kernel:
3468 ParseOpenCLKernelAttributes(DS.getAttributes());
3471 // Nullability type specifiers.
3472 case tok::kw__Nonnull:
3473 case tok::kw__Nullable:
3474 case tok::kw__Null_unspecified:
3475 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3478 // Objective-C 'kindof' types.
3479 case tok::kw___kindof:
3480 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3481 nullptr, 0, ParsedAttr::AS_Keyword);
3482 (void)ConsumeToken();
3485 // storage-class-specifier
3486 case tok::kw_typedef:
3487 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3488 PrevSpec, DiagID, Policy);
3489 isStorageClass = true;
3491 case tok::kw_extern:
3492 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3493 Diag(Tok, diag::ext_thread_before) << "extern";
3494 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3495 PrevSpec, DiagID, Policy);
3496 isStorageClass = true;
3498 case tok::kw___private_extern__:
3499 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3500 Loc, PrevSpec, DiagID, Policy);
3501 isStorageClass = true;
3503 case tok::kw_static:
3504 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3505 Diag(Tok, diag::ext_thread_before) << "static";
3506 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3507 PrevSpec, DiagID, Policy);
3508 isStorageClass = true;
3511 if (getLangOpts().CPlusPlus11) {
3512 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3513 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3514 PrevSpec, DiagID, Policy);
3516 Diag(Tok, diag::ext_auto_storage_class)
3517 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3519 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3522 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3523 PrevSpec, DiagID, Policy);
3524 isStorageClass = true;
3526 case tok::kw___auto_type:
3527 Diag(Tok, diag::ext_auto_type);
3528 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3531 case tok::kw_register:
3532 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3533 PrevSpec, DiagID, Policy);
3534 isStorageClass = true;
3536 case tok::kw_mutable:
3537 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3538 PrevSpec, DiagID, Policy);
3539 isStorageClass = true;
3541 case tok::kw___thread:
3542 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3544 isStorageClass = true;
3546 case tok::kw_thread_local:
3547 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3549 isStorageClass = true;
3551 case tok::kw__Thread_local:
3552 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3553 Loc, PrevSpec, DiagID);
3554 isStorageClass = true;
3557 // function-specifier
3558 case tok::kw_inline:
3559 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3561 case tok::kw_virtual:
3562 // C++ for OpenCL does not allow virtual function qualifier, to avoid
3563 // function pointers restricted in OpenCL v2.0 s6.9.a.
3564 if (getLangOpts().OpenCLCPlusPlus) {
3565 DiagID = diag::err_openclcxx_virtual_function;
3566 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3570 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3573 case tok::kw_explicit: {
3574 SourceLocation ExplicitLoc = Loc;
3575 SourceLocation CloseParenLoc;
3576 ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
3577 ConsumedEnd = ExplicitLoc;
3578 ConsumeToken(); // kw_explicit
3579 if (Tok.is(tok::l_paren)) {
3580 if (getLangOpts().CPlusPlus2a) {
3581 ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
3582 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3583 Tracker.consumeOpen();
3584 ExplicitExpr = ParseConstantExpression();
3585 ConsumedEnd = Tok.getLocation();
3586 if (ExplicitExpr.isUsable()) {
3587 CloseParenLoc = Tok.getLocation();
3588 Tracker.consumeClose();
3590 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
3592 Tracker.skipToEnd();
3594 Diag(Tok.getLocation(), diag::warn_cxx2a_compat_explicit_bool);
3596 isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
3597 ExplicitSpec, CloseParenLoc);
3600 case tok::kw__Noreturn:
3601 if (!getLangOpts().C11)
3602 Diag(Loc, diag::ext_c11_noreturn);
3603 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3606 // alignment-specifier
3607 case tok::kw__Alignas:
3608 if (!getLangOpts().C11)
3609 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
3610 ParseAlignmentSpecifier(DS.getAttributes());
3614 case tok::kw_friend:
3615 if (DSContext == DeclSpecContext::DSC_class)
3616 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3618 PrevSpec = ""; // not actually used by the diagnostic
3619 DiagID = diag::err_friend_invalid_in_context;
3625 case tok::kw___module_private__:
3626 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3630 case tok::kw_constexpr:
3631 isInvalid = DS.SetConstexprSpec(CSK_constexpr, Loc, PrevSpec, DiagID);
3635 case tok::kw_consteval:
3636 isInvalid = DS.SetConstexprSpec(CSK_consteval, Loc, PrevSpec, DiagID);
3641 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3645 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
3646 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3649 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3652 case tok::kw___int64:
3653 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3656 case tok::kw_signed:
3657 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3660 case tok::kw_unsigned:
3661 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3664 case tok::kw__Complex:
3665 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3668 case tok::kw__Imaginary:
3669 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3673 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3677 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3681 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3684 case tok::kw___int128:
3685 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3689 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3693 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3696 case tok::kw_double:
3697 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3700 case tok::kw__Float16:
3701 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3704 case tok::kw__Accum:
3705 if (!getLangOpts().FixedPoint) {
3706 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3708 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3712 case tok::kw__Fract:
3713 if (!getLangOpts().FixedPoint) {
3714 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3716 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3721 if (!getLangOpts().FixedPoint) {
3722 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3724 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3727 case tok::kw___float128:
3728 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3731 case tok::kw_wchar_t:
3732 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3735 case tok::kw_char8_t:
3736 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3739 case tok::kw_char16_t:
3740 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3743 case tok::kw_char32_t:
3744 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3749 if (Tok.is(tok::kw_bool) &&
3750 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3751 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3752 PrevSpec = ""; // Not used by the diagnostic.
3753 DiagID = diag::err_bool_redeclaration;
3754 // For better error recovery.
3755 Tok.setKind(tok::identifier);
3758 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3762 case tok::kw__Decimal32:
3763 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3766 case tok::kw__Decimal64:
3767 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3770 case tok::kw__Decimal128:
3771 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3774 case tok::kw___vector:
3775 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3777 case tok::kw___pixel:
3778 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3780 case tok::kw___bool:
3781 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3784 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200 &&
3785 !getLangOpts().OpenCLCPlusPlus)) {
3786 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3787 // support the "pipe" word as identifier.
3788 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3789 goto DoneWithDeclSpec;
3791 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3793 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
3794 case tok::kw_##ImgType##_t: \
3795 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3798 #include "clang/Basic/OpenCLImageTypes.def"
3799 case tok::kw___unknown_anytype:
3800 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3801 PrevSpec, DiagID, Policy);
3806 case tok::kw_struct:
3807 case tok::kw___interface:
3808 case tok::kw_union: {
3809 tok::TokenKind Kind = Tok.getKind();
3812 // These are attributes following class specifiers.
3813 // To produce better diagnostic, we parse them when
3814 // parsing class specifier.
3815 ParsedAttributesWithRange Attributes(AttrFactory);
3816 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3817 EnteringContext, DSContext, Attributes);
3819 // If there are attributes following class specifier,
3820 // take them over and handle them here.
3821 if (!Attributes.empty()) {
3822 AttrsLastTime = true;
3823 attrs.takeAllFrom(Attributes);
3831 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3836 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3839 case tok::kw_volatile:
3840 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3843 case tok::kw_restrict:
3844 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3848 // C++ typename-specifier:
3849 case tok::kw_typename:
3850 if (TryAnnotateTypeOrScopeToken()) {
3851 DS.SetTypeSpecError();
3852 goto DoneWithDeclSpec;
3854 if (!Tok.is(tok::kw_typename))
3858 // GNU typeof support.
3859 case tok::kw_typeof:
3860 ParseTypeofSpecifier(DS);
3863 case tok::annot_decltype:
3864 ParseDecltypeSpecifier(DS);
3867 case tok::annot_pragma_pack:
3871 case tok::annot_pragma_ms_pragma:
3872 HandlePragmaMSPragma();
3875 case tok::annot_pragma_ms_vtordisp:
3876 HandlePragmaMSVtorDisp();
3879 case tok::annot_pragma_ms_pointers_to_members:
3880 HandlePragmaMSPointersToMembers();
3883 case tok::kw___underlying_type:
3884 ParseUnderlyingTypeSpecifier(DS);
3887 case tok::kw__Atomic:
3889 // If the _Atomic keyword is immediately followed by a left parenthesis,
3890 // it is interpreted as a type specifier (with a type name), not as a
3892 if (NextToken().is(tok::l_paren)) {
3893 ParseAtomicSpecifier(DS);
3896 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3900 // OpenCL address space qualifiers:
3901 case tok::kw___generic:
3902 // generic address space is introduced only in OpenCL v2.0
3903 // see OpenCL C Spec v2.0 s6.5.5
3904 if (Actions.getLangOpts().OpenCLVersion < 200 &&
3905 !Actions.getLangOpts().OpenCLCPlusPlus) {
3906 DiagID = diag::err_opencl_unknown_type_specifier;
3907 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3912 case tok::kw_private:
3913 case tok::kw___private:
3914 case tok::kw___global:
3915 case tok::kw___local:
3916 case tok::kw___constant:
3917 // OpenCL access qualifiers:
3918 case tok::kw___read_only:
3919 case tok::kw___write_only:
3920 case tok::kw___read_write:
3921 ParseOpenCLQualifiers(DS.getAttributes());
3925 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3926 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3927 // but we support it.
3928 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
3929 goto DoneWithDeclSpec;
3931 SourceLocation StartLoc = Tok.getLocation();
3932 SourceLocation EndLoc;
3933 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3934 if (Type.isUsable()) {
3935 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3936 PrevSpec, DiagID, Type.get(),
3937 Actions.getASTContext().getPrintingPolicy()))
3938 Diag(StartLoc, DiagID) << PrevSpec;
3940 DS.SetRangeEnd(EndLoc);
3942 DS.SetTypeSpecError();
3945 // Need to support trailing type qualifiers (e.g. "id<p> const").
3946 // If a type specifier follows, it will be diagnosed elsewhere.
3950 DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
3952 // If the specifier wasn't legal, issue a diagnostic.
3954 assert(PrevSpec && "Method did not return previous specifier!");
3957 if (DiagID == diag::ext_duplicate_declspec ||
3958 DiagID == diag::ext_warn_duplicate_declspec ||
3959 DiagID == diag::err_duplicate_declspec)
3960 Diag(Loc, DiagID) << PrevSpec
3961 << FixItHint::CreateRemoval(
3962 SourceRange(Loc, DS.getEndLoc()));
3963 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
3964 Diag(Loc, DiagID) << getLangOpts().OpenCLCPlusPlus
3965 << getLangOpts().getOpenCLVersionTuple().getAsString()
3966 << PrevSpec << isStorageClass;
3968 Diag(Loc, DiagID) << PrevSpec;
3971 if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
3972 // After an error the next token can be an annotation token.
3975 AttrsLastTime = false;
3979 /// ParseStructDeclaration - Parse a struct declaration without the terminating
3982 /// Note that a struct declaration refers to a declaration in a struct,
3983 /// not to the declaration of a struct.
3985 /// struct-declaration:
3986 /// [C2x] attributes-specifier-seq[opt]
3987 /// specifier-qualifier-list struct-declarator-list
3988 /// [GNU] __extension__ struct-declaration
3989 /// [GNU] specifier-qualifier-list
3990 /// struct-declarator-list:
3991 /// struct-declarator
3992 /// struct-declarator-list ',' struct-declarator
3993 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3994 /// struct-declarator:
3996 /// [GNU] declarator attributes[opt]
3997 /// declarator[opt] ':' constant-expression
3998 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
4000 void Parser::ParseStructDeclaration(
4001 ParsingDeclSpec &DS,
4002 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4004 if (Tok.is(tok::kw___extension__)) {
4005 // __extension__ silences extension warnings in the subexpression.
4006 ExtensionRAIIObject O(Diags); // Use RAII to do this.
4008 return ParseStructDeclaration(DS, FieldsCallback);
4011 // Parse leading attributes.
4012 ParsedAttributesWithRange Attrs(AttrFactory);
4013 MaybeParseCXX11Attributes(Attrs);
4014 DS.takeAttributesFrom(Attrs);
4016 // Parse the common specifier-qualifiers-list piece.
4017 ParseSpecifierQualifierList(DS);
4019 // If there are no declarators, this is a free-standing declaration
4020 // specifier. Let the actions module cope with it.
4021 if (Tok.is(tok::semi)) {
4022 RecordDecl *AnonRecord = nullptr;
4023 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
4025 assert(!AnonRecord && "Did not expect anonymous struct or union here");
4026 DS.complete(TheDecl);
4030 // Read struct-declarators until we find the semicolon.
4031 bool FirstDeclarator = true;
4032 SourceLocation CommaLoc;
4034 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
4035 DeclaratorInfo.D.setCommaLoc(CommaLoc);
4037 // Attributes are only allowed here on successive declarators.
4038 if (!FirstDeclarator)
4039 MaybeParseGNUAttributes(DeclaratorInfo.D);
4041 /// struct-declarator: declarator
4042 /// struct-declarator: declarator[opt] ':' constant-expression
4043 if (Tok.isNot(tok::colon)) {
4044 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4045 ColonProtectionRAIIObject X(*this);
4046 ParseDeclarator(DeclaratorInfo.D);
4048 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4050 if (TryConsumeToken(tok::colon)) {
4051 ExprResult Res(ParseConstantExpression());
4052 if (Res.isInvalid())
4053 SkipUntil(tok::semi, StopBeforeMatch);
4055 DeclaratorInfo.BitfieldSize = Res.get();
4058 // If attributes exist after the declarator, parse them.
4059 MaybeParseGNUAttributes(DeclaratorInfo.D);
4061 // We're done with this declarator; invoke the callback.
4062 FieldsCallback(DeclaratorInfo);
4064 // If we don't have a comma, it is either the end of the list (a ';')
4065 // or an error, bail out.
4066 if (!TryConsumeToken(tok::comma, CommaLoc))
4069 FirstDeclarator = false;
4073 /// ParseStructUnionBody
4074 /// struct-contents:
4075 /// struct-declaration-list
4077 /// [GNU] "struct-declaration-list" without terminatoring ';'
4078 /// struct-declaration-list:
4079 /// struct-declaration
4080 /// struct-declaration-list struct-declaration
4081 /// [OBC] '@' 'defs' '(' class-name ')'
4083 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4084 unsigned TagType, Decl *TagDecl) {
4085 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4086 "parsing struct/union body");
4087 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4089 BalancedDelimiterTracker T(*this, tok::l_brace);
4090 if (T.consumeOpen())
4093 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4094 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
4096 SmallVector<Decl *, 32> FieldDecls;
4098 // While we still have something to read, read the declarations in the struct.
4099 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4100 Tok.isNot(tok::eof)) {
4101 // Each iteration of this loop reads one struct-declaration.
4103 // Check for extraneous top-level semicolon.
4104 if (Tok.is(tok::semi)) {
4105 ConsumeExtraSemi(InsideStruct, TagType);
4109 // Parse _Static_assert declaration.
4110 if (Tok.is(tok::kw__Static_assert)) {
4111 SourceLocation DeclEnd;
4112 ParseStaticAssertDeclaration(DeclEnd);
4116 if (Tok.is(tok::annot_pragma_pack)) {
4121 if (Tok.is(tok::annot_pragma_align)) {
4122 HandlePragmaAlign();
4126 if (Tok.is(tok::annot_pragma_openmp)) {
4127 // Result can be ignored, because it must be always empty.
4128 AccessSpecifier AS = AS_none;
4129 ParsedAttributesWithRange Attrs(AttrFactory);
4130 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4134 if (!Tok.is(tok::at)) {
4135 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4136 // Install the declarator into the current TagDecl.
4138 Actions.ActOnField(getCurScope(), TagDecl,
4139 FD.D.getDeclSpec().getSourceRange().getBegin(),
4140 FD.D, FD.BitfieldSize);
4141 FieldDecls.push_back(Field);
4145 // Parse all the comma separated declarators.
4146 ParsingDeclSpec DS(*this);
4147 ParseStructDeclaration(DS, CFieldCallback);
4148 } else { // Handle @defs
4150 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4151 Diag(Tok, diag::err_unexpected_at);
4152 SkipUntil(tok::semi);
4156 ExpectAndConsume(tok::l_paren);
4157 if (!Tok.is(tok::identifier)) {
4158 Diag(Tok, diag::err_expected) << tok::identifier;
4159 SkipUntil(tok::semi);
4162 SmallVector<Decl *, 16> Fields;
4163 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4164 Tok.getIdentifierInfo(), Fields);
4165 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4167 ExpectAndConsume(tok::r_paren);
4170 if (TryConsumeToken(tok::semi))
4173 if (Tok.is(tok::r_brace)) {
4174 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4178 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4179 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4180 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4181 // If we stopped at a ';', eat it.
4182 TryConsumeToken(tok::semi);
4187 ParsedAttributes attrs(AttrFactory);
4188 // If attributes exist after struct contents, parse them.
4189 MaybeParseGNUAttributes(attrs);
4191 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4192 T.getOpenLocation(), T.getCloseLocation(), attrs);
4194 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4197 /// ParseEnumSpecifier
4198 /// enum-specifier: [C99 6.7.2.2]
4199 /// 'enum' identifier[opt] '{' enumerator-list '}'
4200 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4201 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4202 /// '}' attributes[opt]
4203 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4205 /// 'enum' identifier
4206 /// [GNU] 'enum' attributes[opt] identifier
4208 /// [C++11] enum-head '{' enumerator-list[opt] '}'
4209 /// [C++11] enum-head '{' enumerator-list ',' '}'
4211 /// enum-head: [C++11]
4212 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4213 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
4214 /// identifier enum-base[opt]
4216 /// enum-key: [C++11]
4221 /// enum-base: [C++11]
4222 /// ':' type-specifier-seq
4224 /// [C++] elaborated-type-specifier:
4225 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4227 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4228 const ParsedTemplateInfo &TemplateInfo,
4229 AccessSpecifier AS, DeclSpecContext DSC) {
4230 // Parse the tag portion of this.
4231 if (Tok.is(tok::code_completion)) {
4232 // Code completion for an enum name.
4233 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
4234 return cutOffParsing();
4237 // If attributes exist after tag, parse them.
4238 ParsedAttributesWithRange attrs(AttrFactory);
4239 MaybeParseGNUAttributes(attrs);
4240 MaybeParseCXX11Attributes(attrs);
4241 MaybeParseMicrosoftDeclSpecs(attrs);
4243 SourceLocation ScopedEnumKWLoc;
4244 bool IsScopedUsingClassTag = false;
4246 // In C++11, recognize 'enum class' and 'enum struct'.
4247 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4248 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4249 : diag::ext_scoped_enum);
4250 IsScopedUsingClassTag = Tok.is(tok::kw_class);
4251 ScopedEnumKWLoc = ConsumeToken();
4253 // Attributes are not allowed between these keywords. Diagnose,
4254 // but then just treat them like they appeared in the right place.
4255 ProhibitAttributes(attrs);
4257 // They are allowed afterwards, though.
4258 MaybeParseGNUAttributes(attrs);
4259 MaybeParseCXX11Attributes(attrs);
4260 MaybeParseMicrosoftDeclSpecs(attrs);
4263 // C++11 [temp.explicit]p12:
4264 // The usual access controls do not apply to names used to specify
4265 // explicit instantiations.
4266 // We extend this to also cover explicit specializations. Note that
4267 // we don't suppress if this turns out to be an elaborated type
4269 bool shouldDelayDiagsInTag =
4270 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4271 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4272 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4274 // Enum definitions should not be parsed in a trailing-return-type.
4275 bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
4277 CXXScopeSpec &SS = DS.getTypeSpecScope();
4278 if (getLangOpts().CPlusPlus) {
4279 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4280 // if a fixed underlying type is allowed.
4281 ColonProtectionRAIIObject X(*this, AllowDeclaration);
4284 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
4285 /*EnteringContext=*/true))
4288 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4289 Diag(Tok, diag::err_expected) << tok::identifier;
4290 if (Tok.isNot(tok::l_brace)) {
4291 // Has no name and is not a definition.
4292 // Skip the rest of this declarator, up until the comma or semicolon.
4293 SkipUntil(tok::comma, StopAtSemi);
4301 // Must have either 'enum name' or 'enum {...}'.
4302 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4303 !(AllowDeclaration && Tok.is(tok::colon))) {
4304 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4306 // Skip the rest of this declarator, up until the comma or semicolon.
4307 SkipUntil(tok::comma, StopAtSemi);
4311 // If an identifier is present, consume and remember it.
4312 IdentifierInfo *Name = nullptr;
4313 SourceLocation NameLoc;
4314 if (Tok.is(tok::identifier)) {
4315 Name = Tok.getIdentifierInfo();
4316 NameLoc = ConsumeToken();
4319 if (!Name && ScopedEnumKWLoc.isValid()) {
4320 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4321 // declaration of a scoped enumeration.
4322 Diag(Tok, diag::err_scoped_enum_missing_identifier);
4323 ScopedEnumKWLoc = SourceLocation();
4324 IsScopedUsingClassTag = false;
4327 // Okay, end the suppression area. We'll decide whether to emit the
4328 // diagnostics in a second.
4329 if (shouldDelayDiagsInTag)
4330 diagsFromTag.done();
4332 TypeResult BaseType;
4334 // Parse the fixed underlying type.
4335 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4336 if (AllowDeclaration && Tok.is(tok::colon)) {
4337 bool PossibleBitfield = false;
4338 if (CanBeBitfield) {
4339 // If we're in class scope, this can either be an enum declaration with
4340 // an underlying type, or a declaration of a bitfield member. We try to
4341 // use a simple disambiguation scheme first to catch the common cases
4342 // (integer literal, sizeof); if it's still ambiguous, we then consider
4343 // anything that's a simple-type-specifier followed by '(' as an
4344 // expression. This suffices because function types are not valid
4345 // underlying types anyway.
4346 EnterExpressionEvaluationContext Unevaluated(
4347 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4348 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
4349 // If the next token starts an expression, we know we're parsing a
4350 // bit-field. This is the common case.
4351 if (TPR == TPResult::True)
4352 PossibleBitfield = true;
4353 // If the next token starts a type-specifier-seq, it may be either a
4354 // a fixed underlying type or the start of a function-style cast in C++;
4355 // lookahead one more token to see if it's obvious that we have a
4356 // fixed underlying type.
4357 else if (TPR == TPResult::False &&
4358 GetLookAheadToken(2).getKind() == tok::semi) {
4362 // We have the start of a type-specifier-seq, so we have to perform
4363 // tentative parsing to determine whether we have an expression or a
4365 TentativeParsingAction TPA(*this);
4370 // If we see a type specifier followed by an open-brace, we have an
4371 // ambiguity between an underlying type and a C++11 braced
4372 // function-style cast. Resolve this by always treating it as an
4374 // FIXME: The standard is not entirely clear on how to disambiguate in
4376 if ((getLangOpts().CPlusPlus &&
4377 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
4378 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
4379 // We'll parse this as a bitfield later.
4380 PossibleBitfield = true;
4383 // We have a type-specifier-seq.
4392 if (!PossibleBitfield) {
4394 BaseType = ParseTypeName(&Range);
4396 if (!getLangOpts().ObjC) {
4397 if (getLangOpts().CPlusPlus11)
4398 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4399 else if (getLangOpts().CPlusPlus)
4400 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type);
4401 else if (getLangOpts().MicrosoftExt)
4402 Diag(StartLoc, diag::ext_ms_c_enum_fixed_underlying_type);
4404 Diag(StartLoc, diag::ext_clang_c_enum_fixed_underlying_type);
4409 // There are four options here. If we have 'friend enum foo;' then this is a
4410 // friend declaration, and cannot have an accompanying definition. If we have
4411 // 'enum foo;', then this is a forward declaration. If we have
4412 // 'enum foo {...' then this is a definition. Otherwise we have something
4413 // like 'enum foo xyz', a reference.
4415 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4416 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4417 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4419 Sema::TagUseKind TUK;
4420 if (!AllowDeclaration) {
4421 TUK = Sema::TUK_Reference;
4422 } else if (Tok.is(tok::l_brace)) {
4423 if (DS.isFriendSpecified()) {
4424 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4425 << SourceRange(DS.getFriendSpecLoc());
4427 SkipUntil(tok::r_brace, StopAtSemi);
4428 TUK = Sema::TUK_Friend;
4430 TUK = Sema::TUK_Definition;
4432 } else if (!isTypeSpecifier(DSC) &&
4433 (Tok.is(tok::semi) ||
4434 (Tok.isAtStartOfLine() &&
4435 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4436 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4437 if (Tok.isNot(tok::semi)) {
4438 // A semicolon was missing after this declaration. Diagnose and recover.
4439 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4440 PP.EnterToken(Tok, /*IsReinject=*/true);
4441 Tok.setKind(tok::semi);
4444 TUK = Sema::TUK_Reference;
4447 // If this is an elaborated type specifier, and we delayed
4448 // diagnostics before, just merge them into the current pool.
4449 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4450 diagsFromTag.redelay();
4453 MultiTemplateParamsArg TParams;
4454 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4455 TUK != Sema::TUK_Reference) {
4456 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4457 // Skip the rest of this declarator, up until the comma or semicolon.
4458 Diag(Tok, diag::err_enum_template);
4459 SkipUntil(tok::comma, StopAtSemi);
4463 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4464 // Enumerations can't be explicitly instantiated.
4465 DS.SetTypeSpecError();
4466 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4470 assert(TemplateInfo.TemplateParams && "no template parameters");
4471 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4472 TemplateInfo.TemplateParams->size());
4475 if (TUK == Sema::TUK_Reference)
4476 ProhibitAttributes(attrs);
4478 if (!Name && TUK != Sema::TUK_Definition) {
4479 Diag(Tok, diag::err_enumerator_unnamed_no_def);
4481 // Skip the rest of this declarator, up until the comma or semicolon.
4482 SkipUntil(tok::comma, StopAtSemi);
4486 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4488 Sema::SkipBodyInfo SkipBody;
4489 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4490 NextToken().is(tok::identifier))
4491 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4492 NextToken().getIdentifierInfo(),
4493 NextToken().getLocation());
4496 bool IsDependent = false;
4497 const char *PrevSpec = nullptr;
4499 Decl *TagDecl = Actions.ActOnTag(
4500 getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
4501 attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4502 ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
4503 DSC == DeclSpecContext::DSC_type_specifier,
4504 DSC == DeclSpecContext::DSC_template_param ||
4505 DSC == DeclSpecContext::DSC_template_type_arg,
4508 if (SkipBody.ShouldSkip) {
4509 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4511 BalancedDelimiterTracker T(*this, tok::l_brace);
4515 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4516 NameLoc.isValid() ? NameLoc : StartLoc,
4517 PrevSpec, DiagID, TagDecl, Owned,
4518 Actions.getASTContext().getPrintingPolicy()))
4519 Diag(StartLoc, DiagID) << PrevSpec;
4524 // This enum has a dependent nested-name-specifier. Handle it as a
4527 DS.SetTypeSpecError();
4528 Diag(Tok, diag::err_expected_type_name_after_typename);
4532 TypeResult Type = Actions.ActOnDependentTag(
4533 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4534 if (Type.isInvalid()) {
4535 DS.SetTypeSpecError();
4539 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4540 NameLoc.isValid() ? NameLoc : StartLoc,
4541 PrevSpec, DiagID, Type.get(),
4542 Actions.getASTContext().getPrintingPolicy()))
4543 Diag(StartLoc, DiagID) << PrevSpec;
4549 // The action failed to produce an enumeration tag. If this is a
4550 // definition, consume the entire definition.
4551 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4553 SkipUntil(tok::r_brace, StopAtSemi);
4556 DS.SetTypeSpecError();
4560 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4561 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4562 ParseEnumBody(StartLoc, D);
4563 if (SkipBody.CheckSameAsPrevious &&
4564 !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4565 DS.SetTypeSpecError();
4570 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4571 NameLoc.isValid() ? NameLoc : StartLoc,
4572 PrevSpec, DiagID, TagDecl, Owned,
4573 Actions.getASTContext().getPrintingPolicy()))
4574 Diag(StartLoc, DiagID) << PrevSpec;
4577 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4578 /// enumerator-list:
4580 /// enumerator-list ',' enumerator
4582 /// enumeration-constant attributes[opt]
4583 /// enumeration-constant attributes[opt] '=' constant-expression
4584 /// enumeration-constant:
4587 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4588 // Enter the scope of the enum body and start the definition.
4589 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4590 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4592 BalancedDelimiterTracker T(*this, tok::l_brace);
4595 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4596 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4597 Diag(Tok, diag::err_empty_enum);
4599 SmallVector<Decl *, 32> EnumConstantDecls;
4600 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4602 Decl *LastEnumConstDecl = nullptr;
4604 // Parse the enumerator-list.
4605 while (Tok.isNot(tok::r_brace)) {
4606 // Parse enumerator. If failed, try skipping till the start of the next
4607 // enumerator definition.
4608 if (Tok.isNot(tok::identifier)) {
4609 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4610 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4611 TryConsumeToken(tok::comma))
4615 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4616 SourceLocation IdentLoc = ConsumeToken();
4618 // If attributes exist after the enumerator, parse them.
4619 ParsedAttributesWithRange attrs(AttrFactory);
4620 MaybeParseGNUAttributes(attrs);
4621 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4622 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4623 if (getLangOpts().CPlusPlus)
4624 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4625 ? diag::warn_cxx14_compat_ns_enum_attribute
4626 : diag::ext_ns_enum_attribute)
4627 << 1 /*enumerator*/;
4628 ParseCXX11Attributes(attrs);
4631 SourceLocation EqualLoc;
4632 ExprResult AssignedVal;
4633 EnumAvailabilityDiags.emplace_back(*this);
4635 if (TryConsumeToken(tok::equal, EqualLoc)) {
4636 AssignedVal = ParseConstantExpression();
4637 if (AssignedVal.isInvalid())
4638 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4641 // Install the enumerator constant into EnumDecl.
4642 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
4643 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4644 EqualLoc, AssignedVal.get());
4645 EnumAvailabilityDiags.back().done();
4647 EnumConstantDecls.push_back(EnumConstDecl);
4648 LastEnumConstDecl = EnumConstDecl;
4650 if (Tok.is(tok::identifier)) {
4651 // We're missing a comma between enumerators.
4652 SourceLocation Loc = getEndOfPreviousToken();
4653 Diag(Loc, diag::err_enumerator_list_missing_comma)
4654 << FixItHint::CreateInsertion(Loc, ", ");
4658 // Emumerator definition must be finished, only comma or r_brace are
4660 SourceLocation CommaLoc;
4661 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4662 if (EqualLoc.isValid())
4663 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4666 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4667 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4668 if (TryConsumeToken(tok::comma, CommaLoc))
4675 // If comma is followed by r_brace, emit appropriate warning.
4676 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4677 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4678 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4679 diag::ext_enumerator_list_comma_cxx :
4680 diag::ext_enumerator_list_comma_c)
4681 << FixItHint::CreateRemoval(CommaLoc);
4682 else if (getLangOpts().CPlusPlus11)
4683 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4684 << FixItHint::CreateRemoval(CommaLoc);
4692 // If attributes exist after the identifier list, parse them.
4693 ParsedAttributes attrs(AttrFactory);
4694 MaybeParseGNUAttributes(attrs);
4696 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4697 getCurScope(), attrs);
4699 // Now handle enum constant availability diagnostics.
4700 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4701 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4702 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4703 EnumAvailabilityDiags[i].redelay();
4704 PD.complete(EnumConstantDecls[i]);
4708 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4710 // The next token must be valid after an enum definition. If not, a ';'
4711 // was probably forgotten.
4712 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4713 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4714 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4715 // Push this token back into the preprocessor and change our current token
4716 // to ';' so that the rest of the code recovers as though there were an
4717 // ';' after the definition.
4718 PP.EnterToken(Tok, /*IsReinject=*/true);
4719 Tok.setKind(tok::semi);
4723 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4724 /// is definitely a type-specifier. Return false if it isn't part of a type
4725 /// specifier or if we're not sure.
4726 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4727 switch (Tok.getKind()) {
4728 default: return false;
4732 case tok::kw___int64:
4733 case tok::kw___int128:
4734 case tok::kw_signed:
4735 case tok::kw_unsigned:
4736 case tok::kw__Complex:
4737 case tok::kw__Imaginary:
4740 case tok::kw_wchar_t:
4741 case tok::kw_char8_t:
4742 case tok::kw_char16_t:
4743 case tok::kw_char32_t:
4747 case tok::kw_double:
4748 case tok::kw__Accum:
4749 case tok::kw__Fract:
4750 case tok::kw__Float16:
4751 case tok::kw___float128:
4754 case tok::kw__Decimal32:
4755 case tok::kw__Decimal64:
4756 case tok::kw__Decimal128:
4757 case tok::kw___vector:
4758 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4759 #include "clang/Basic/OpenCLImageTypes.def"
4761 // struct-or-union-specifier (C99) or class-specifier (C++)
4763 case tok::kw_struct:
4764 case tok::kw___interface:
4770 case tok::annot_typename:
4775 /// isTypeSpecifierQualifier - Return true if the current token could be the
4776 /// start of a specifier-qualifier-list.
4777 bool Parser::isTypeSpecifierQualifier() {
4778 switch (Tok.getKind()) {
4779 default: return false;
4781 case tok::identifier: // foo::bar
4782 if (TryAltiVecVectorToken())
4785 case tok::kw_typename: // typename T::type
4786 // Annotate typenames and C++ scope specifiers. If we get one, just
4787 // recurse to handle whatever we get.
4788 if (TryAnnotateTypeOrScopeToken())
4790 if (Tok.is(tok::identifier))
4792 return isTypeSpecifierQualifier();
4794 case tok::coloncolon: // ::foo::bar
4795 if (NextToken().is(tok::kw_new) || // ::new
4796 NextToken().is(tok::kw_delete)) // ::delete
4799 if (TryAnnotateTypeOrScopeToken())
4801 return isTypeSpecifierQualifier();
4803 // GNU attributes support.
4804 case tok::kw___attribute:
4805 // GNU typeof support.
4806 case tok::kw_typeof:
4811 case tok::kw___int64:
4812 case tok::kw___int128:
4813 case tok::kw_signed:
4814 case tok::kw_unsigned:
4815 case tok::kw__Complex:
4816 case tok::kw__Imaginary:
4819 case tok::kw_wchar_t:
4820 case tok::kw_char8_t:
4821 case tok::kw_char16_t:
4822 case tok::kw_char32_t:
4826 case tok::kw_double:
4827 case tok::kw__Accum:
4828 case tok::kw__Fract:
4829 case tok::kw__Float16:
4830 case tok::kw___float128:
4833 case tok::kw__Decimal32:
4834 case tok::kw__Decimal64:
4835 case tok::kw__Decimal128:
4836 case tok::kw___vector:
4837 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4838 #include "clang/Basic/OpenCLImageTypes.def"
4840 // struct-or-union-specifier (C99) or class-specifier (C++)
4842 case tok::kw_struct:
4843 case tok::kw___interface:
4850 case tok::kw_volatile:
4851 case tok::kw_restrict:
4854 // Debugger support.
4855 case tok::kw___unknown_anytype:
4858 case tok::annot_typename:
4861 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4863 return getLangOpts().ObjC;
4865 case tok::kw___cdecl:
4866 case tok::kw___stdcall:
4867 case tok::kw___fastcall:
4868 case tok::kw___thiscall:
4869 case tok::kw___regcall:
4870 case tok::kw___vectorcall:
4872 case tok::kw___ptr64:
4873 case tok::kw___ptr32:
4874 case tok::kw___pascal:
4875 case tok::kw___unaligned:
4877 case tok::kw__Nonnull:
4878 case tok::kw__Nullable:
4879 case tok::kw__Null_unspecified:
4881 case tok::kw___kindof:
4883 case tok::kw___private:
4884 case tok::kw___local:
4885 case tok::kw___global:
4886 case tok::kw___constant:
4887 case tok::kw___generic:
4888 case tok::kw___read_only:
4889 case tok::kw___read_write:
4890 case tok::kw___write_only:
4893 case tok::kw_private:
4894 return getLangOpts().OpenCL;
4897 case tok::kw__Atomic:
4902 /// isDeclarationSpecifier() - Return true if the current token is part of a
4903 /// declaration specifier.
4905 /// \param DisambiguatingWithExpression True to indicate that the purpose of
4906 /// this check is to disambiguate between an expression and a declaration.
4907 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4908 switch (Tok.getKind()) {
4909 default: return false;
4912 return (getLangOpts().OpenCL && getLangOpts().OpenCLVersion >= 200) ||
4913 getLangOpts().OpenCLCPlusPlus;
4915 case tok::identifier: // foo::bar
4916 // Unfortunate hack to support "Class.factoryMethod" notation.
4917 if (getLangOpts().ObjC && NextToken().is(tok::period))
4919 if (TryAltiVecVectorToken())
4922 case tok::kw_decltype: // decltype(T())::type
4923 case tok::kw_typename: // typename T::type
4924 // Annotate typenames and C++ scope specifiers. If we get one, just
4925 // recurse to handle whatever we get.
4926 if (TryAnnotateTypeOrScopeToken())
4928 if (Tok.is(tok::identifier))
4931 // If we're in Objective-C and we have an Objective-C class type followed
4932 // by an identifier and then either ':' or ']', in a place where an
4933 // expression is permitted, then this is probably a class message send
4934 // missing the initial '['. In this case, we won't consider this to be
4935 // the start of a declaration.
4936 if (DisambiguatingWithExpression &&
4937 isStartOfObjCClassMessageMissingOpenBracket())
4940 return isDeclarationSpecifier();
4942 case tok::coloncolon: // ::foo::bar
4943 if (NextToken().is(tok::kw_new) || // ::new
4944 NextToken().is(tok::kw_delete)) // ::delete
4947 // Annotate typenames and C++ scope specifiers. If we get one, just
4948 // recurse to handle whatever we get.
4949 if (TryAnnotateTypeOrScopeToken())
4951 return isDeclarationSpecifier();
4953 // storage-class-specifier
4954 case tok::kw_typedef:
4955 case tok::kw_extern:
4956 case tok::kw___private_extern__:
4957 case tok::kw_static:
4959 case tok::kw___auto_type:
4960 case tok::kw_register:
4961 case tok::kw___thread:
4962 case tok::kw_thread_local:
4963 case tok::kw__Thread_local:
4966 case tok::kw___module_private__:
4969 case tok::kw___unknown_anytype:
4974 case tok::kw___int64:
4975 case tok::kw___int128:
4976 case tok::kw_signed:
4977 case tok::kw_unsigned:
4978 case tok::kw__Complex:
4979 case tok::kw__Imaginary:
4982 case tok::kw_wchar_t:
4983 case tok::kw_char8_t:
4984 case tok::kw_char16_t:
4985 case tok::kw_char32_t:
4990 case tok::kw_double:
4991 case tok::kw__Accum:
4992 case tok::kw__Fract:
4993 case tok::kw__Float16:
4994 case tok::kw___float128:
4997 case tok::kw__Decimal32:
4998 case tok::kw__Decimal64:
4999 case tok::kw__Decimal128:
5000 case tok::kw___vector:
5002 // struct-or-union-specifier (C99) or class-specifier (C++)
5004 case tok::kw_struct:
5006 case tok::kw___interface:
5012 case tok::kw_volatile:
5013 case tok::kw_restrict:
5016 // function-specifier
5017 case tok::kw_inline:
5018 case tok::kw_virtual:
5019 case tok::kw_explicit:
5020 case tok::kw__Noreturn:
5022 // alignment-specifier
5023 case tok::kw__Alignas:
5026 case tok::kw_friend:
5028 // static_assert-declaration
5029 case tok::kw__Static_assert:
5031 // GNU typeof support.
5032 case tok::kw_typeof:
5035 case tok::kw___attribute:
5037 // C++11 decltype and constexpr.
5038 case tok::annot_decltype:
5039 case tok::kw_constexpr:
5042 case tok::kw_consteval:
5045 case tok::kw__Atomic:
5048 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5050 return getLangOpts().ObjC;
5053 case tok::annot_typename:
5054 return !DisambiguatingWithExpression ||
5055 !isStartOfObjCClassMessageMissingOpenBracket();
5057 case tok::kw___declspec:
5058 case tok::kw___cdecl:
5059 case tok::kw___stdcall:
5060 case tok::kw___fastcall:
5061 case tok::kw___thiscall:
5062 case tok::kw___regcall:
5063 case tok::kw___vectorcall:
5065 case tok::kw___sptr:
5066 case tok::kw___uptr:
5067 case tok::kw___ptr64:
5068 case tok::kw___ptr32:
5069 case tok::kw___forceinline:
5070 case tok::kw___pascal:
5071 case tok::kw___unaligned:
5073 case tok::kw__Nonnull:
5074 case tok::kw__Nullable:
5075 case tok::kw__Null_unspecified:
5077 case tok::kw___kindof:
5079 case tok::kw___private:
5080 case tok::kw___local:
5081 case tok::kw___global:
5082 case tok::kw___constant:
5083 case tok::kw___generic:
5084 case tok::kw___read_only:
5085 case tok::kw___read_write:
5086 case tok::kw___write_only:
5087 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5088 #include "clang/Basic/OpenCLImageTypes.def"
5092 case tok::kw_private:
5093 return getLangOpts().OpenCL;
5097 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
5098 TentativeParsingAction TPA(*this);
5100 // Parse the C++ scope specifier.
5102 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
5103 /*EnteringContext=*/true)) {
5108 // Parse the constructor name.
5109 if (Tok.is(tok::identifier)) {
5110 // We already know that we have a constructor name; just consume
5113 } else if (Tok.is(tok::annot_template_id)) {
5114 ConsumeAnnotationToken();
5120 // There may be attributes here, appertaining to the constructor name or type
5121 // we just stepped past.
5122 SkipCXX11Attributes();
5124 // Current class name must be followed by a left parenthesis.
5125 if (Tok.isNot(tok::l_paren)) {
5131 // A right parenthesis, or ellipsis followed by a right parenthesis signals
5132 // that we have a constructor.
5133 if (Tok.is(tok::r_paren) ||
5134 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
5139 // A C++11 attribute here signals that we have a constructor, and is an
5140 // attribute on the first constructor parameter.
5141 if (getLangOpts().CPlusPlus11 &&
5142 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5143 /*OuterMightBeMessageSend*/ true)) {
5148 // If we need to, enter the specified scope.
5149 DeclaratorScopeObj DeclScopeObj(*this, SS);
5150 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
5151 DeclScopeObj.EnterDeclaratorScope();
5153 // Optionally skip Microsoft attributes.
5154 ParsedAttributes Attrs(AttrFactory);
5155 MaybeParseMicrosoftAttributes(Attrs);
5157 // Check whether the next token(s) are part of a declaration
5158 // specifier, in which case we have the start of a parameter and,
5159 // therefore, we know that this is a constructor.
5160 bool IsConstructor = false;
5161 if (isDeclarationSpecifier())
5162 IsConstructor = true;
5163 else if (Tok.is(tok::identifier) ||
5164 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5165 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5166 // This might be a parenthesized member name, but is more likely to
5167 // be a constructor declaration with an invalid argument type. Keep
5169 if (Tok.is(tok::annot_cxxscope))
5170 ConsumeAnnotationToken();
5173 // If this is not a constructor, we must be parsing a declarator,
5174 // which must have one of the following syntactic forms (see the
5175 // grammar extract at the start of ParseDirectDeclarator):
5176 switch (Tok.getKind()) {
5181 // C(X [ [attribute]]);
5182 case tok::coloncolon:
5185 // Assume this isn't a constructor, rather than assuming it's a
5186 // constructor with an unnamed parameter of an ill-formed type.
5192 // Skip past the right-paren and any following attributes to get to
5193 // the function body or trailing-return-type.
5195 SkipCXX11Attributes();
5197 if (DeductionGuide) {
5198 // C(X) -> ... is a deduction guide.
5199 IsConstructor = Tok.is(tok::arrow);
5202 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
5203 // Assume these were meant to be constructors:
5204 // C(X) : (the name of a bit-field cannot be parenthesized).
5205 // C(X) try (this is otherwise ill-formed).
5206 IsConstructor = true;
5208 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
5209 // If we have a constructor name within the class definition,
5210 // assume these were meant to be constructors:
5213 // ... because otherwise we would be declaring a non-static data
5214 // member that is ill-formed because it's of the same type as its
5215 // surrounding class.
5217 // FIXME: We can actually do this whether or not the name is qualified,
5218 // because if it is qualified in this context it must be being used as
5219 // a constructor name.
5220 // currently, so we're somewhat conservative here.
5221 IsConstructor = IsUnqualified;
5226 IsConstructor = true;
5232 return IsConstructor;
5235 /// ParseTypeQualifierListOpt
5236 /// type-qualifier-list: [C99 6.7.5]
5238 /// [vendor] attributes
5239 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5240 /// type-qualifier-list type-qualifier
5241 /// [vendor] type-qualifier-list attributes
5242 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5243 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
5244 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
5245 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5246 /// AttrRequirements bitmask values.
5247 void Parser::ParseTypeQualifierListOpt(
5248 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5249 bool IdentifierRequired,
5250 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
5251 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
5252 isCXX11AttributeSpecifier()) {
5253 ParsedAttributesWithRange attrs(AttrFactory);
5254 ParseCXX11Attributes(attrs);
5255 DS.takeAttributesFrom(attrs);
5258 SourceLocation EndLoc;
5261 bool isInvalid = false;
5262 const char *PrevSpec = nullptr;
5263 unsigned DiagID = 0;
5264 SourceLocation Loc = Tok.getLocation();
5266 switch (Tok.getKind()) {
5267 case tok::code_completion:
5268 if (CodeCompletionHandler)
5269 (*CodeCompletionHandler)();
5271 Actions.CodeCompleteTypeQualifiers(DS);
5272 return cutOffParsing();
5275 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
5278 case tok::kw_volatile:
5279 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5282 case tok::kw_restrict:
5283 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5286 case tok::kw__Atomic:
5288 goto DoneWithTypeQuals;
5289 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5293 // OpenCL qualifiers:
5294 case tok::kw_private:
5295 if (!getLangOpts().OpenCL)
5296 goto DoneWithTypeQuals;
5298 case tok::kw___private:
5299 case tok::kw___global:
5300 case tok::kw___local:
5301 case tok::kw___constant:
5302 case tok::kw___generic:
5303 case tok::kw___read_only:
5304 case tok::kw___write_only:
5305 case tok::kw___read_write:
5306 ParseOpenCLQualifiers(DS.getAttributes());
5309 case tok::kw___unaligned:
5310 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5313 case tok::kw___uptr:
5314 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
5315 // with the MS modifier keyword.
5316 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
5317 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5318 if (TryKeywordIdentFallback(false))
5322 case tok::kw___sptr:
5324 case tok::kw___ptr64:
5325 case tok::kw___ptr32:
5326 case tok::kw___cdecl:
5327 case tok::kw___stdcall:
5328 case tok::kw___fastcall:
5329 case tok::kw___thiscall:
5330 case tok::kw___regcall:
5331 case tok::kw___vectorcall:
5332 if (AttrReqs & AR_DeclspecAttributesParsed) {
5333 ParseMicrosoftTypeAttributes(DS.getAttributes());
5336 goto DoneWithTypeQuals;
5337 case tok::kw___pascal:
5338 if (AttrReqs & AR_VendorAttributesParsed) {
5339 ParseBorlandTypeAttributes(DS.getAttributes());
5342 goto DoneWithTypeQuals;
5344 // Nullability type specifiers.
5345 case tok::kw__Nonnull:
5346 case tok::kw__Nullable:
5347 case tok::kw__Null_unspecified:
5348 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5351 // Objective-C 'kindof' types.
5352 case tok::kw___kindof:
5353 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
5354 nullptr, 0, ParsedAttr::AS_Keyword);
5355 (void)ConsumeToken();
5358 case tok::kw___attribute:
5359 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5360 // When GNU attributes are expressly forbidden, diagnose their usage.
5361 Diag(Tok, diag::err_attributes_not_allowed);
5363 // Parse the attributes even if they are rejected to ensure that error
5364 // recovery is graceful.
5365 if (AttrReqs & AR_GNUAttributesParsed ||
5366 AttrReqs & AR_GNUAttributesParsedAndRejected) {
5367 ParseGNUAttributes(DS.getAttributes());
5368 continue; // do *not* consume the next token!
5370 // otherwise, FALL THROUGH!
5374 // If this is not a type-qualifier token, we're done reading type
5375 // qualifiers. First verify that DeclSpec's are consistent.
5376 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
5377 if (EndLoc.isValid())
5378 DS.SetRangeEnd(EndLoc);
5382 // If the specifier combination wasn't legal, issue a diagnostic.
5384 assert(PrevSpec && "Method did not return previous specifier!");
5385 Diag(Tok, DiagID) << PrevSpec;
5387 EndLoc = ConsumeToken();
5391 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
5393 void Parser::ParseDeclarator(Declarator &D) {
5394 /// This implements the 'declarator' production in the C grammar, then checks
5395 /// for well-formedness and issues diagnostics.
5396 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5399 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
5400 DeclaratorContext TheContext) {
5401 if (Kind == tok::star || Kind == tok::caret)
5404 if (Kind == tok::kw_pipe &&
5405 ((Lang.OpenCL && Lang.OpenCLVersion >= 200) || Lang.OpenCLCPlusPlus))
5408 if (!Lang.CPlusPlus)
5411 if (Kind == tok::amp)
5414 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5415 // But we must not parse them in conversion-type-ids and new-type-ids, since
5416 // those can be legitimately followed by a && operator.
5417 // (The same thing can in theory happen after a trailing-return-type, but
5418 // since those are a C++11 feature, there is no rejects-valid issue there.)
5419 if (Kind == tok::ampamp)
5420 return Lang.CPlusPlus11 ||
5421 (TheContext != DeclaratorContext::ConversionIdContext &&
5422 TheContext != DeclaratorContext::CXXNewContext);
5427 // Indicates whether the given declarator is a pipe declarator.
5428 static bool isPipeDeclerator(const Declarator &D) {
5429 const unsigned NumTypes = D.getNumTypeObjects();
5431 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5432 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5438 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5439 /// is parsed by the function passed to it. Pass null, and the direct-declarator
5440 /// isn't parsed at all, making this function effectively parse the C++
5441 /// ptr-operator production.
5443 /// If the grammar of this construct is extended, matching changes must also be
5444 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5445 /// isConstructorDeclarator.
5447 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5448 /// [C] pointer[opt] direct-declarator
5449 /// [C++] direct-declarator
5450 /// [C++] ptr-operator declarator
5452 /// pointer: [C99 6.7.5]
5453 /// '*' type-qualifier-list[opt]
5454 /// '*' type-qualifier-list[opt] pointer
5457 /// '*' cv-qualifier-seq[opt]
5460 /// [GNU] '&' restrict[opt] attributes[opt]
5461 /// [GNU?] '&&' restrict[opt] attributes[opt]
5462 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
5463 void Parser::ParseDeclaratorInternal(Declarator &D,
5464 DirectDeclParseFunction DirectDeclParser) {
5465 if (Diags.hasAllExtensionsSilenced())
5468 // C++ member pointers start with a '::' or a nested-name.
5469 // Member pointers get special handling, since there's no place for the
5470 // scope spec in the generic path below.
5471 if (getLangOpts().CPlusPlus &&
5472 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
5473 (Tok.is(tok::identifier) &&
5474 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
5475 Tok.is(tok::annot_cxxscope))) {
5476 bool EnteringContext =
5477 D.getContext() == DeclaratorContext::FileContext ||
5478 D.getContext() == DeclaratorContext::MemberContext;
5480 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
5482 if (SS.isNotEmpty()) {
5483 if (Tok.isNot(tok::star)) {
5484 // The scope spec really belongs to the direct-declarator.
5485 if (D.mayHaveIdentifier())
5486 D.getCXXScopeSpec() = SS;
5488 AnnotateScopeToken(SS, true);
5490 if (DirectDeclParser)
5491 (this->*DirectDeclParser)(D);
5495 SourceLocation Loc = ConsumeToken();
5497 DeclSpec DS(AttrFactory);
5498 ParseTypeQualifierListOpt(DS);
5499 D.ExtendWithDeclSpec(DS);
5501 // Recurse to parse whatever is left.
5502 ParseDeclaratorInternal(D, DirectDeclParser);
5504 // Sema will have to catch (syntactically invalid) pointers into global
5505 // scope. It has to catch pointers into namespace scope anyway.
5506 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
5507 SS, DS.getTypeQualifiers(), DS.getEndLoc()),
5508 std::move(DS.getAttributes()),
5509 /* Don't replace range end. */ SourceLocation());
5514 tok::TokenKind Kind = Tok.getKind();
5516 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
5517 DeclSpec DS(AttrFactory);
5518 ParseTypeQualifierListOpt(DS);
5521 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
5522 std::move(DS.getAttributes()), SourceLocation());
5525 // Not a pointer, C++ reference, or block.
5526 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
5527 if (DirectDeclParser)
5528 (this->*DirectDeclParser)(D);
5532 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5533 // '&&' -> rvalue reference
5534 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
5537 if (Kind == tok::star || Kind == tok::caret) {
5539 DeclSpec DS(AttrFactory);
5541 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5542 // C++11 attributes are allowed.
5543 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
5544 ((D.getContext() != DeclaratorContext::CXXNewContext)
5545 ? AR_GNUAttributesParsed
5546 : AR_GNUAttributesParsedAndRejected);
5547 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
5548 D.ExtendWithDeclSpec(DS);
5550 // Recursively parse the declarator.
5551 ParseDeclaratorInternal(D, DirectDeclParser);
5552 if (Kind == tok::star)
5553 // Remember that we parsed a pointer type, and remember the type-quals.
5554 D.AddTypeInfo(DeclaratorChunk::getPointer(
5555 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5556 DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
5557 DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
5558 std::move(DS.getAttributes()), SourceLocation());
5560 // Remember that we parsed a Block type, and remember the type-quals.
5562 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
5563 std::move(DS.getAttributes()), SourceLocation());
5566 DeclSpec DS(AttrFactory);
5568 // Complain about rvalue references in C++03, but then go on and build
5570 if (Kind == tok::ampamp)
5571 Diag(Loc, getLangOpts().CPlusPlus11 ?
5572 diag::warn_cxx98_compat_rvalue_reference :
5573 diag::ext_rvalue_reference);
5575 // GNU-style and C++11 attributes are allowed here, as is restrict.
5576 ParseTypeQualifierListOpt(DS);
5577 D.ExtendWithDeclSpec(DS);
5579 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5580 // cv-qualifiers are introduced through the use of a typedef or of a
5581 // template type argument, in which case the cv-qualifiers are ignored.
5582 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5583 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5584 Diag(DS.getConstSpecLoc(),
5585 diag::err_invalid_reference_qualifier_application) << "const";
5586 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5587 Diag(DS.getVolatileSpecLoc(),
5588 diag::err_invalid_reference_qualifier_application) << "volatile";
5589 // 'restrict' is permitted as an extension.
5590 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5591 Diag(DS.getAtomicSpecLoc(),
5592 diag::err_invalid_reference_qualifier_application) << "_Atomic";
5595 // Recursively parse the declarator.
5596 ParseDeclaratorInternal(D, DirectDeclParser);
5598 if (D.getNumTypeObjects() > 0) {
5599 // C++ [dcl.ref]p4: There shall be no references to references.
5600 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5601 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5602 if (const IdentifierInfo *II = D.getIdentifier())
5603 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5606 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5609 // Once we've complained about the reference-to-reference, we
5610 // can go ahead and build the (technically ill-formed)
5611 // declarator: reference collapsing will take care of it.
5615 // Remember that we parsed a reference type.
5616 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
5618 std::move(DS.getAttributes()), SourceLocation());
5622 // When correcting from misplaced brackets before the identifier, the location
5623 // is saved inside the declarator so that other diagnostic messages can use
5624 // them. This extracts and returns that location, or returns the provided
5625 // location if a stored location does not exist.
5626 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5627 SourceLocation Loc) {
5628 if (D.getName().StartLocation.isInvalid() &&
5629 D.getName().EndLocation.isValid())
5630 return D.getName().EndLocation;
5635 /// ParseDirectDeclarator
5636 /// direct-declarator: [C99 6.7.5]
5637 /// [C99] identifier
5638 /// '(' declarator ')'
5639 /// [GNU] '(' attributes declarator ')'
5640 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5641 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5642 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5643 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5644 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5645 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5646 /// attribute-specifier-seq[opt]
5647 /// direct-declarator '(' parameter-type-list ')'
5648 /// direct-declarator '(' identifier-list[opt] ')'
5649 /// [GNU] direct-declarator '(' parameter-forward-declarations
5650 /// parameter-type-list[opt] ')'
5651 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
5652 /// cv-qualifier-seq[opt] exception-specification[opt]
5653 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5654 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5655 /// ref-qualifier[opt] exception-specification[opt]
5656 /// [C++] declarator-id
5657 /// [C++11] declarator-id attribute-specifier-seq[opt]
5659 /// declarator-id: [C++ 8]
5660 /// '...'[opt] id-expression
5661 /// '::'[opt] nested-name-specifier[opt] type-name
5663 /// id-expression: [C++ 5.1]
5667 /// unqualified-id: [C++ 5.1]
5669 /// operator-function-id
5670 /// conversion-function-id
5674 /// C++17 adds the following, which we also handle here:
5676 /// simple-declaration:
5677 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5679 /// Note, any additional constructs added here may need corresponding changes
5680 /// in isConstructorDeclarator.
5681 void Parser::ParseDirectDeclarator(Declarator &D) {
5682 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
5684 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
5685 // This might be a C++17 structured binding.
5686 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5687 D.getCXXScopeSpec().isEmpty())
5688 return ParseDecompositionDeclarator(D);
5690 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5691 // this context it is a bitfield. Also in range-based for statement colon
5692 // may delimit for-range-declaration.
5693 ColonProtectionRAIIObject X(
5694 *this, D.getContext() == DeclaratorContext::MemberContext ||
5695 (D.getContext() == DeclaratorContext::ForContext &&
5696 getLangOpts().CPlusPlus11));
5698 // ParseDeclaratorInternal might already have parsed the scope.
5699 if (D.getCXXScopeSpec().isEmpty()) {
5700 bool EnteringContext =
5701 D.getContext() == DeclaratorContext::FileContext ||
5702 D.getContext() == DeclaratorContext::MemberContext;
5703 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
5707 if (D.getCXXScopeSpec().isValid()) {
5708 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5709 D.getCXXScopeSpec()))
5710 // Change the declaration context for name lookup, until this function
5711 // is exited (and the declarator has been parsed).
5712 DeclScopeObj.EnterDeclaratorScope();
5713 else if (getObjCDeclContext()) {
5714 // Ensure that we don't interpret the next token as an identifier when
5715 // dealing with declarations in an Objective-C container.
5716 D.SetIdentifier(nullptr, Tok.getLocation());
5717 D.setInvalidType(true);
5719 goto PastIdentifier;
5723 // C++0x [dcl.fct]p14:
5724 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5725 // parameter-declaration-clause without a preceding comma. In this case,
5726 // the ellipsis is parsed as part of the abstract-declarator if the type
5727 // of the parameter either names a template parameter pack that has not
5728 // been expanded or contains auto; otherwise, it is parsed as part of the
5729 // parameter-declaration-clause.
5730 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
5731 !((D.getContext() == DeclaratorContext::PrototypeContext ||
5732 D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5733 D.getContext() == DeclaratorContext::BlockLiteralContext) &&
5734 NextToken().is(tok::r_paren) &&
5735 !D.hasGroupingParens() &&
5736 !Actions.containsUnexpandedParameterPacks(D) &&
5737 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
5738 SourceLocation EllipsisLoc = ConsumeToken();
5739 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
5740 // The ellipsis was put in the wrong place. Recover, and explain to
5741 // the user what they should have done.
5743 if (EllipsisLoc.isValid())
5744 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5747 D.setEllipsisLoc(EllipsisLoc);
5749 // The ellipsis can't be followed by a parenthesized declarator. We
5750 // check for that in ParseParenDeclarator, after we have disambiguated
5751 // the l_paren token.
5754 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5756 // We found something that indicates the start of an unqualified-id.
5757 // Parse that unqualified-id.
5758 bool AllowConstructorName;
5759 bool AllowDeductionGuide;
5760 if (D.getDeclSpec().hasTypeSpecifier()) {
5761 AllowConstructorName = false;
5762 AllowDeductionGuide = false;
5763 } else if (D.getCXXScopeSpec().isSet()) {
5764 AllowConstructorName =
5765 (D.getContext() == DeclaratorContext::FileContext ||
5766 D.getContext() == DeclaratorContext::MemberContext);
5767 AllowDeductionGuide = false;
5769 AllowConstructorName =
5770 (D.getContext() == DeclaratorContext::MemberContext);
5771 AllowDeductionGuide =
5772 (D.getContext() == DeclaratorContext::FileContext ||
5773 D.getContext() == DeclaratorContext::MemberContext);
5776 bool HadScope = D.getCXXScopeSpec().isValid();
5777 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5778 /*EnteringContext=*/true,
5779 /*AllowDestructorName=*/true, AllowConstructorName,
5780 AllowDeductionGuide, nullptr, nullptr,
5782 // Once we're past the identifier, if the scope was bad, mark the
5783 // whole declarator bad.
5784 D.getCXXScopeSpec().isInvalid()) {
5785 D.SetIdentifier(nullptr, Tok.getLocation());
5786 D.setInvalidType(true);
5788 // ParseUnqualifiedId might have parsed a scope specifier during error
5789 // recovery. If it did so, enter that scope.
5790 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5791 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5792 D.getCXXScopeSpec()))
5793 DeclScopeObj.EnterDeclaratorScope();
5795 // Parsed the unqualified-id; update range information and move along.
5796 if (D.getSourceRange().getBegin().isInvalid())
5797 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5798 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
5800 goto PastIdentifier;
5803 if (D.getCXXScopeSpec().isNotEmpty()) {
5804 // We have a scope specifier but no following unqualified-id.
5805 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5806 diag::err_expected_unqualified_id)
5808 D.SetIdentifier(nullptr, Tok.getLocation());
5809 goto PastIdentifier;
5811 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
5812 assert(!getLangOpts().CPlusPlus &&
5813 "There's a C++-specific check for tok::identifier above");
5814 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5815 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5816 D.SetRangeEnd(Tok.getLocation());
5818 goto PastIdentifier;
5819 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5820 // We're not allowed an identifier here, but we got one. Try to figure out
5821 // if the user was trying to attach a name to the type, or whether the name
5822 // is some unrelated trailing syntax.
5823 bool DiagnoseIdentifier = false;
5824 if (D.hasGroupingParens())
5825 // An identifier within parens is unlikely to be intended to be anything
5826 // other than a name being "declared".
5827 DiagnoseIdentifier = true;
5828 else if (D.getContext() == DeclaratorContext::TemplateArgContext)
5829 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5830 DiagnoseIdentifier =
5831 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
5832 else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5833 D.getContext() == DeclaratorContext::AliasTemplateContext)
5834 // The most likely error is that the ';' was forgotten.
5835 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
5836 else if ((D.getContext() == DeclaratorContext::TrailingReturnContext ||
5837 D.getContext() == DeclaratorContext::TrailingReturnVarContext) &&
5838 !isCXX11VirtSpecifier(Tok))
5839 DiagnoseIdentifier = NextToken().isOneOf(
5840 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5841 if (DiagnoseIdentifier) {
5842 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5843 << FixItHint::CreateRemoval(Tok.getLocation());
5844 D.SetIdentifier(nullptr, Tok.getLocation());
5846 goto PastIdentifier;
5850 if (Tok.is(tok::l_paren)) {
5851 // If this might be an abstract-declarator followed by a direct-initializer,
5852 // check whether this is a valid declarator chunk. If it can't be, assume
5853 // that it's an initializer instead.
5854 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
5855 RevertingTentativeParsingAction PA(*this);
5856 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
5858 D.SetIdentifier(nullptr, Tok.getLocation());
5859 goto PastIdentifier;
5863 // direct-declarator: '(' declarator ')'
5864 // direct-declarator: '(' attributes declarator ')'
5865 // Example: 'char (*X)' or 'int (*XX)(void)'
5866 ParseParenDeclarator(D);
5868 // If the declarator was parenthesized, we entered the declarator
5869 // scope when parsing the parenthesized declarator, then exited
5870 // the scope already. Re-enter the scope, if we need to.
5871 if (D.getCXXScopeSpec().isSet()) {
5872 // If there was an error parsing parenthesized declarator, declarator
5873 // scope may have been entered before. Don't do it again.
5874 if (!D.isInvalidType() &&
5875 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5876 D.getCXXScopeSpec()))
5877 // Change the declaration context for name lookup, until this function
5878 // is exited (and the declarator has been parsed).
5879 DeclScopeObj.EnterDeclaratorScope();
5881 } else if (D.mayOmitIdentifier()) {
5882 // This could be something simple like "int" (in which case the declarator
5883 // portion is empty), if an abstract-declarator is allowed.
5884 D.SetIdentifier(nullptr, Tok.getLocation());
5886 // The grammar for abstract-pack-declarator does not allow grouping parens.
5887 // FIXME: Revisit this once core issue 1488 is resolved.
5888 if (D.hasEllipsis() && D.hasGroupingParens())
5889 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5890 diag::ext_abstract_pack_declarator_parens);
5892 if (Tok.getKind() == tok::annot_pragma_parser_crash)
5894 if (Tok.is(tok::l_square))
5895 return ParseMisplacedBracketDeclarator(D);
5896 if (D.getContext() == DeclaratorContext::MemberContext) {
5897 // Objective-C++: Detect C++ keywords and try to prevent further errors by
5898 // treating these keyword as valid member names.
5899 if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
5900 Tok.getIdentifierInfo() &&
5901 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5902 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5903 diag::err_expected_member_name_or_semi_objcxx_keyword)
5904 << Tok.getIdentifierInfo()
5905 << (D.getDeclSpec().isEmpty() ? SourceRange()
5906 : D.getDeclSpec().getSourceRange());
5907 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5908 D.SetRangeEnd(Tok.getLocation());
5910 goto PastIdentifier;
5912 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5913 diag::err_expected_member_name_or_semi)
5914 << (D.getDeclSpec().isEmpty() ? SourceRange()
5915 : D.getDeclSpec().getSourceRange());
5916 } else if (getLangOpts().CPlusPlus) {
5917 if (Tok.isOneOf(tok::period, tok::arrow))
5918 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
5920 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5921 if (Tok.isAtStartOfLine() && Loc.isValid())
5922 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5923 << getLangOpts().CPlusPlus;
5925 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5926 diag::err_expected_unqualified_id)
5927 << getLangOpts().CPlusPlus;
5930 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5931 diag::err_expected_either)
5932 << tok::identifier << tok::l_paren;
5934 D.SetIdentifier(nullptr, Tok.getLocation());
5935 D.setInvalidType(true);
5939 assert(D.isPastIdentifier() &&
5940 "Haven't past the location of the identifier yet?");
5942 // Don't parse attributes unless we have parsed an unparenthesized name.
5943 if (D.hasName() && !D.getNumTypeObjects())
5944 MaybeParseCXX11Attributes(D);
5947 if (Tok.is(tok::l_paren)) {
5948 // Enter function-declaration scope, limiting any declarators to the
5949 // function prototype scope, including parameter declarators.
5950 ParseScope PrototypeScope(this,
5951 Scope::FunctionPrototypeScope|Scope::DeclScope|
5952 (D.isFunctionDeclaratorAFunctionDeclaration()
5953 ? Scope::FunctionDeclarationScope : 0));
5955 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5956 // In such a case, check if we actually have a function declarator; if it
5957 // is not, the declarator has been fully parsed.
5958 bool IsAmbiguous = false;
5959 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5960 // The name of the declarator, if any, is tentatively declared within
5961 // a possible direct initializer.
5962 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5963 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5964 TentativelyDeclaredIdentifiers.pop_back();
5965 if (!IsFunctionDecl)
5968 ParsedAttributes attrs(AttrFactory);
5969 BalancedDelimiterTracker T(*this, tok::l_paren);
5971 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
5972 PrototypeScope.Exit();
5973 } else if (Tok.is(tok::l_square)) {
5974 ParseBracketDeclarator(D);
5981 void Parser::ParseDecompositionDeclarator(Declarator &D) {
5982 assert(Tok.is(tok::l_square));
5984 // If this doesn't look like a structured binding, maybe it's a misplaced
5985 // array declarator.
5986 // FIXME: Consume the l_square first so we don't need extra lookahead for
5988 if (!(NextToken().is(tok::identifier) &&
5989 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5990 !(NextToken().is(tok::r_square) &&
5991 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5992 return ParseMisplacedBracketDeclarator(D);
5994 BalancedDelimiterTracker T(*this, tok::l_square);
5997 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5998 while (Tok.isNot(tok::r_square)) {
5999 if (!Bindings.empty()) {
6000 if (Tok.is(tok::comma))
6003 if (Tok.is(tok::identifier)) {
6004 SourceLocation EndLoc = getEndOfPreviousToken();
6005 Diag(EndLoc, diag::err_expected)
6006 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
6008 Diag(Tok, diag::err_expected_comma_or_rsquare);
6011 SkipUntil(tok::r_square, tok::comma, tok::identifier,
6012 StopAtSemi | StopBeforeMatch);
6013 if (Tok.is(tok::comma))
6015 else if (Tok.isNot(tok::identifier))
6020 if (Tok.isNot(tok::identifier)) {
6021 Diag(Tok, diag::err_expected) << tok::identifier;
6025 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
6029 if (Tok.isNot(tok::r_square))
6030 // We've already diagnosed a problem here.
6033 // C++17 does not allow the identifier-list in a structured binding
6035 if (Bindings.empty())
6036 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
6041 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
6042 T.getCloseLocation());
6045 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
6046 /// only called before the identifier, so these are most likely just grouping
6047 /// parens for precedence. If we find that these are actually function
6048 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
6050 /// direct-declarator:
6051 /// '(' declarator ')'
6052 /// [GNU] '(' attributes declarator ')'
6053 /// direct-declarator '(' parameter-type-list ')'
6054 /// direct-declarator '(' identifier-list[opt] ')'
6055 /// [GNU] direct-declarator '(' parameter-forward-declarations
6056 /// parameter-type-list[opt] ')'
6058 void Parser::ParseParenDeclarator(Declarator &D) {
6059 BalancedDelimiterTracker T(*this, tok::l_paren);
6062 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
6064 // Eat any attributes before we look at whether this is a grouping or function
6065 // declarator paren. If this is a grouping paren, the attribute applies to
6066 // the type being built up, for example:
6067 // int (__attribute__(()) *x)(long y)
6068 // If this ends up not being a grouping paren, the attribute applies to the
6069 // first argument, for example:
6070 // int (__attribute__(()) int x)
6071 // In either case, we need to eat any attributes to be able to determine what
6072 // sort of paren this is.
6074 ParsedAttributes attrs(AttrFactory);
6075 bool RequiresArg = false;
6076 if (Tok.is(tok::kw___attribute)) {
6077 ParseGNUAttributes(attrs);
6079 // We require that the argument list (if this is a non-grouping paren) be
6080 // present even if the attribute list was empty.
6084 // Eat any Microsoft extensions.
6085 ParseMicrosoftTypeAttributes(attrs);
6087 // Eat any Borland extensions.
6088 if (Tok.is(tok::kw___pascal))
6089 ParseBorlandTypeAttributes(attrs);
6091 // If we haven't past the identifier yet (or where the identifier would be
6092 // stored, if this is an abstract declarator), then this is probably just
6093 // grouping parens. However, if this could be an abstract-declarator, then
6094 // this could also be the start of function arguments (consider 'void()').
6097 if (!D.mayOmitIdentifier()) {
6098 // If this can't be an abstract-declarator, this *must* be a grouping
6099 // paren, because we haven't seen the identifier yet.
6101 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
6102 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
6103 NextToken().is(tok::r_paren)) || // C++ int(...)
6104 isDeclarationSpecifier() || // 'int(int)' is a function.
6105 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
6106 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
6107 // considered to be a type, not a K&R identifier-list.
6110 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6114 // If this is a grouping paren, handle:
6115 // direct-declarator: '(' declarator ')'
6116 // direct-declarator: '(' attributes declarator ')'
6118 SourceLocation EllipsisLoc = D.getEllipsisLoc();
6119 D.setEllipsisLoc(SourceLocation());
6121 bool hadGroupingParens = D.hasGroupingParens();
6122 D.setGroupingParens(true);
6123 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6127 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
6128 std::move(attrs), T.getCloseLocation());
6130 D.setGroupingParens(hadGroupingParens);
6132 // An ellipsis cannot be placed outside parentheses.
6133 if (EllipsisLoc.isValid())
6134 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6139 // Okay, if this wasn't a grouping paren, it must be the start of a function
6140 // argument list. Recognize that this declarator will never have an
6141 // identifier (and remember where it would have been), then call into
6142 // ParseFunctionDeclarator to handle of argument list.
6143 D.SetIdentifier(nullptr, Tok.getLocation());
6145 // Enter function-declaration scope, limiting any declarators to the
6146 // function prototype scope, including parameter declarators.
6147 ParseScope PrototypeScope(this,
6148 Scope::FunctionPrototypeScope | Scope::DeclScope |
6149 (D.isFunctionDeclaratorAFunctionDeclaration()
6150 ? Scope::FunctionDeclarationScope : 0));
6151 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
6152 PrototypeScope.Exit();
6155 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
6156 /// declarator D up to a paren, which indicates that we are parsing function
6159 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
6160 /// immediately after the open paren - they should be considered to be the
6161 /// first argument of a parameter.
6163 /// If RequiresArg is true, then the first argument of the function is required
6164 /// to be present and required to not be an identifier list.
6166 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6167 /// (C++11) ref-qualifier[opt], exception-specification[opt],
6168 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
6170 /// [C++11] exception-specification:
6171 /// dynamic-exception-specification
6172 /// noexcept-specification
6174 void Parser::ParseFunctionDeclarator(Declarator &D,
6175 ParsedAttributes &FirstArgAttrs,
6176 BalancedDelimiterTracker &Tracker,
6179 assert(getCurScope()->isFunctionPrototypeScope() &&
6180 "Should call from a Function scope");
6181 // lparen is already consumed!
6182 assert(D.isPastIdentifier() && "Should not call before identifier!");
6184 // This should be true when the function has typed arguments.
6185 // Otherwise, it is treated as a K&R-style function.
6186 bool HasProto = false;
6187 // Build up an array of information about the parsed arguments.
6188 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
6189 // Remember where we see an ellipsis, if any.
6190 SourceLocation EllipsisLoc;
6192 DeclSpec DS(AttrFactory);
6193 bool RefQualifierIsLValueRef = true;
6194 SourceLocation RefQualifierLoc;
6195 ExceptionSpecificationType ESpecType = EST_None;
6196 SourceRange ESpecRange;
6197 SmallVector<ParsedType, 2> DynamicExceptions;
6198 SmallVector<SourceRange, 2> DynamicExceptionRanges;
6199 ExprResult NoexceptExpr;
6200 CachedTokens *ExceptionSpecTokens = nullptr;
6201 ParsedAttributesWithRange FnAttrs(AttrFactory);
6202 TypeResult TrailingReturnType;
6204 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6205 EndLoc is the end location for the function declarator.
6206 They differ for trailing return types. */
6207 SourceLocation StartLoc, LocalEndLoc, EndLoc;
6208 SourceLocation LParenLoc, RParenLoc;
6209 LParenLoc = Tracker.getOpenLocation();
6210 StartLoc = LParenLoc;
6212 if (isFunctionDeclaratorIdentifierList()) {
6214 Diag(Tok, diag::err_argument_required_after_attribute);
6216 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6218 Tracker.consumeClose();
6219 RParenLoc = Tracker.getCloseLocation();
6220 LocalEndLoc = RParenLoc;
6223 // If there are attributes following the identifier list, parse them and
6225 MaybeParseCXX11Attributes(FnAttrs);
6226 ProhibitAttributes(FnAttrs);
6228 if (Tok.isNot(tok::r_paren))
6229 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
6231 else if (RequiresArg)
6232 Diag(Tok, diag::err_argument_required_after_attribute);
6234 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6235 || getLangOpts().OpenCL;
6237 // If we have the closing ')', eat it.
6238 Tracker.consumeClose();
6239 RParenLoc = Tracker.getCloseLocation();
6240 LocalEndLoc = RParenLoc;
6243 if (getLangOpts().CPlusPlus) {
6244 // FIXME: Accept these components in any order, and produce fixits to
6245 // correct the order if the user gets it wrong. Ideally we should deal
6246 // with the pure-specifier in the same way.
6248 // Parse cv-qualifier-seq[opt].
6249 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
6250 /*AtomicAllowed*/ false,
6251 /*IdentifierRequired=*/false,
6252 llvm::function_ref<void()>([&]() {
6253 Actions.CodeCompleteFunctionQualifiers(DS, D);
6255 if (!DS.getSourceRange().getEnd().isInvalid()) {
6256 EndLoc = DS.getSourceRange().getEnd();
6259 // Parse ref-qualifier[opt].
6260 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
6261 EndLoc = RefQualifierLoc;
6263 // C++11 [expr.prim.general]p3:
6264 // If a declaration declares a member function or member function
6265 // template of a class X, the expression this is a prvalue of type
6266 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6267 // and the end of the function-definition, member-declarator, or
6269 // FIXME: currently, "static" case isn't handled correctly.
6270 bool IsCXX11MemberFunction =
6271 getLangOpts().CPlusPlus11 &&
6272 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6273 (D.getContext() == DeclaratorContext::MemberContext
6274 ? !D.getDeclSpec().isFriendSpecified()
6275 : D.getContext() == DeclaratorContext::FileContext &&
6276 D.getCXXScopeSpec().isValid() &&
6277 Actions.CurContext->isRecord());
6279 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
6280 if (D.getDeclSpec().hasConstexprSpecifier() && !getLangOpts().CPlusPlus14)
6282 // FIXME: Collect C++ address spaces.
6283 // If there are multiple different address spaces, the source is invalid.
6284 // Carry on using the first addr space for the qualifiers of 'this'.
6285 // The diagnostic will be given later while creating the function
6286 // prototype for the method.
6287 if (getLangOpts().OpenCLCPlusPlus) {
6288 for (ParsedAttr &attr : DS.getAttributes()) {
6289 LangAS ASIdx = attr.asOpenCLLangAS();
6290 if (ASIdx != LangAS::Default) {
6291 Q.addAddressSpace(ASIdx);
6297 Sema::CXXThisScopeRAII ThisScope(
6298 Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
6299 IsCXX11MemberFunction);
6301 // Parse exception-specification[opt].
6302 bool Delayed = D.isFirstDeclarationOfMember() &&
6303 D.isFunctionDeclaratorAFunctionDeclaration();
6304 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6305 GetLookAheadToken(0).is(tok::kw_noexcept) &&
6306 GetLookAheadToken(1).is(tok::l_paren) &&
6307 GetLookAheadToken(2).is(tok::kw_noexcept) &&
6308 GetLookAheadToken(3).is(tok::l_paren) &&
6309 GetLookAheadToken(4).is(tok::identifier) &&
6310 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6311 // HACK: We've got an exception-specification
6312 // noexcept(noexcept(swap(...)))
6314 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6315 // on a 'swap' member function. This is a libstdc++ bug; the lookup
6316 // for 'swap' will only find the function we're currently declaring,
6317 // whereas it expects to find a non-member swap through ADL. Turn off
6318 // delayed parsing to give it a chance to find what it expects.
6321 ESpecType = tryParseExceptionSpecification(Delayed,
6324 DynamicExceptionRanges,
6326 ExceptionSpecTokens);
6327 if (ESpecType != EST_None)
6328 EndLoc = ESpecRange.getEnd();
6330 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6331 // after the exception-specification.
6332 MaybeParseCXX11Attributes(FnAttrs);
6334 // Parse trailing-return-type[opt].
6335 LocalEndLoc = EndLoc;
6336 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
6337 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
6338 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
6339 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
6340 LocalEndLoc = Tok.getLocation();
6342 TrailingReturnType =
6343 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
6344 EndLoc = Range.getEnd();
6346 } else if (standardAttributesAllowed()) {
6347 MaybeParseCXX11Attributes(FnAttrs);
6351 // Collect non-parameter declarations from the prototype if this is a function
6352 // declaration. They will be moved into the scope of the function. Only do
6353 // this in C and not C++, where the decls will continue to live in the
6354 // surrounding context.
6355 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6356 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6357 !getLangOpts().CPlusPlus) {
6358 for (Decl *D : getCurScope()->decls()) {
6359 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6360 if (!ND || isa<ParmVarDecl>(ND))
6362 DeclsInPrototype.push_back(ND);
6366 // Remember that we parsed a function type, and remember the attributes.
6367 D.AddTypeInfo(DeclaratorChunk::getFunction(
6368 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6369 ParamInfo.size(), EllipsisLoc, RParenLoc,
6370 RefQualifierIsLValueRef, RefQualifierLoc,
6371 /*MutableLoc=*/SourceLocation(),
6372 ESpecType, ESpecRange, DynamicExceptions.data(),
6373 DynamicExceptionRanges.data(), DynamicExceptions.size(),
6374 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6375 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
6376 LocalEndLoc, D, TrailingReturnType, &DS),
6377 std::move(FnAttrs), EndLoc);
6380 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6381 /// true if a ref-qualifier is found.
6382 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6383 SourceLocation &RefQualifierLoc) {
6384 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
6385 Diag(Tok, getLangOpts().CPlusPlus11 ?
6386 diag::warn_cxx98_compat_ref_qualifier :
6387 diag::ext_ref_qualifier);
6389 RefQualifierIsLValueRef = Tok.is(tok::amp);
6390 RefQualifierLoc = ConsumeToken();
6396 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
6397 /// identifier list form for a K&R-style function: void foo(a,b,c)
6399 /// Note that identifier-lists are only allowed for normal declarators, not for
6400 /// abstract-declarators.
6401 bool Parser::isFunctionDeclaratorIdentifierList() {
6402 return !getLangOpts().CPlusPlus
6403 && Tok.is(tok::identifier)
6404 && !TryAltiVecVectorToken()
6405 // K&R identifier lists can't have typedefs as identifiers, per C99
6407 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6408 // Identifier lists follow a really simple grammar: the identifiers can
6409 // be followed *only* by a ", identifier" or ")". However, K&R
6410 // identifier lists are really rare in the brave new modern world, and
6411 // it is very common for someone to typo a type in a non-K&R style
6412 // list. If we are presented with something like: "void foo(intptr x,
6413 // float y)", we don't want to start parsing the function declarator as
6414 // though it is a K&R style declarator just because intptr is an
6417 // To handle this, we check to see if the token after the first
6418 // identifier is a "," or ")". Only then do we parse it as an
6420 && (!Tok.is(tok::eof) &&
6421 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
6424 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6425 /// we found a K&R-style identifier list instead of a typed parameter list.
6427 /// After returning, ParamInfo will hold the parsed parameters.
6429 /// identifier-list: [C99 6.7.5]
6431 /// identifier-list ',' identifier
6433 void Parser::ParseFunctionDeclaratorIdentifierList(
6435 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
6436 // If there was no identifier specified for the declarator, either we are in
6437 // an abstract-declarator, or we are in a parameter declarator which was found
6438 // to be abstract. In abstract-declarators, identifier lists are not valid:
6440 if (!D.getIdentifier())
6441 Diag(Tok, diag::ext_ident_list_in_param);
6443 // Maintain an efficient lookup of params we have seen so far.
6444 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6447 // If this isn't an identifier, report the error and skip until ')'.
6448 if (Tok.isNot(tok::identifier)) {
6449 Diag(Tok, diag::err_expected) << tok::identifier;
6450 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
6451 // Forget we parsed anything.
6456 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6458 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6459 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6460 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6462 // Verify that the argument identifier has not already been mentioned.
6463 if (!ParamsSoFar.insert(ParmII).second) {
6464 Diag(Tok, diag::err_param_redefinition) << ParmII;
6466 // Remember this identifier in ParamInfo.
6467 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6472 // Eat the identifier.
6474 // The list continues if we see a comma.
6475 } while (TryConsumeToken(tok::comma));
6478 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6479 /// after the opening parenthesis. This function will not parse a K&R-style
6480 /// identifier list.
6482 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
6483 /// caller parsed those arguments immediately after the open paren - they should
6484 /// be considered to be part of the first parameter.
6486 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6487 /// be the location of the ellipsis, if any was parsed.
6489 /// parameter-type-list: [C99 6.7.5]
6491 /// parameter-list ',' '...'
6492 /// [C++] parameter-list '...'
6494 /// parameter-list: [C99 6.7.5]
6495 /// parameter-declaration
6496 /// parameter-list ',' parameter-declaration
6498 /// parameter-declaration: [C99 6.7.5]
6499 /// declaration-specifiers declarator
6500 /// [C++] declaration-specifiers declarator '=' assignment-expression
6501 /// [C++11] initializer-clause
6502 /// [GNU] declaration-specifiers declarator attributes
6503 /// declaration-specifiers abstract-declarator[opt]
6504 /// [C++] declaration-specifiers abstract-declarator[opt]
6505 /// '=' assignment-expression
6506 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
6507 /// [C++11] attribute-specifier-seq parameter-declaration
6509 void Parser::ParseParameterDeclarationClause(
6511 ParsedAttributes &FirstArgAttrs,
6512 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
6513 SourceLocation &EllipsisLoc) {
6515 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6516 // before deciding this was a parameter-declaration-clause.
6517 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
6520 // Parse the declaration-specifiers.
6521 // Just use the ParsingDeclaration "scope" of the declarator.
6522 DeclSpec DS(AttrFactory);
6524 // Parse any C++11 attributes.
6525 MaybeParseCXX11Attributes(DS.getAttributes());
6527 // Skip any Microsoft attributes before a param.
6528 MaybeParseMicrosoftAttributes(DS.getAttributes());
6530 SourceLocation DSStart = Tok.getLocation();
6532 // If the caller parsed attributes for the first argument, add them now.
6533 // Take them so that we only apply the attributes to the first parameter.
6534 // FIXME: If we can leave the attributes in the token stream somehow, we can
6535 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6537 DS.takeAttributesFrom(FirstArgAttrs);
6539 ParseDeclarationSpecifiers(DS);
6542 // Parse the declarator. This is "PrototypeContext" or
6543 // "LambdaExprParameterContext", because we must accept either
6544 // 'declarator' or 'abstract-declarator' here.
6545 Declarator ParmDeclarator(
6546 DS, D.getContext() == DeclaratorContext::LambdaExprContext
6547 ? DeclaratorContext::LambdaExprParameterContext
6548 : DeclaratorContext::PrototypeContext);
6549 ParseDeclarator(ParmDeclarator);
6551 // Parse GNU attributes, if present.
6552 MaybeParseGNUAttributes(ParmDeclarator);
6554 // Remember this parsed parameter in ParamInfo.
6555 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
6557 // DefArgToks is used when the parsing of default arguments needs
6559 std::unique_ptr<CachedTokens> DefArgToks;
6561 // If no parameter was specified, verify that *something* was specified,
6562 // otherwise we have a missing type and identifier.
6563 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
6564 ParmDeclarator.getNumTypeObjects() == 0) {
6565 // Completely missing, emit error.
6566 Diag(DSStart, diag::err_missing_param);
6568 // Otherwise, we have something. Add it and let semantic analysis try
6569 // to grok it and add the result to the ParamInfo we are building.
6571 // Last chance to recover from a misplaced ellipsis in an attempted
6572 // parameter pack declaration.
6573 if (Tok.is(tok::ellipsis) &&
6574 (NextToken().isNot(tok::r_paren) ||
6575 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6576 !Actions.isUnexpandedParameterPackPermitted())) &&
6577 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6578 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6580 // Inform the actions module about the parameter declarator, so it gets
6581 // added to the current scope.
6582 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
6583 // Parse the default argument, if any. We parse the default
6584 // arguments in all dialects; the semantic analysis in
6585 // ActOnParamDefaultArgument will reject the default argument in
6587 if (Tok.is(tok::equal)) {
6588 SourceLocation EqualLoc = Tok.getLocation();
6590 // Parse the default argument
6591 if (D.getContext() == DeclaratorContext::MemberContext) {
6592 // If we're inside a class definition, cache the tokens
6593 // corresponding to the default argument. We'll actually parse
6594 // them when we see the end of the class definition.
6595 DefArgToks.reset(new CachedTokens);
6597 SourceLocation ArgStartLoc = NextToken().getLocation();
6598 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
6600 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6602 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
6609 // The argument isn't actually potentially evaluated unless it is
6611 EnterExpressionEvaluationContext Eval(
6613 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6616 ExprResult DefArgResult;
6617 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
6618 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
6619 DefArgResult = ParseBraceInitializer();
6621 DefArgResult = ParseAssignmentExpression();
6622 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
6623 if (DefArgResult.isInvalid()) {
6624 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6625 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
6627 // Inform the actions module about the default argument
6628 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
6629 DefArgResult.get());
6634 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6635 ParmDeclarator.getIdentifierLoc(),
6636 Param, std::move(DefArgToks)));
6639 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6640 if (!getLangOpts().CPlusPlus) {
6641 // We have ellipsis without a preceding ',', which is ill-formed
6642 // in C. Complain and provide the fix.
6643 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6644 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6645 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6646 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6647 // It looks like this was supposed to be a parameter pack. Warn and
6648 // point out where the ellipsis should have gone.
6649 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6650 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6651 << ParmEllipsis.isValid() << ParmEllipsis;
6652 if (ParmEllipsis.isValid()) {
6654 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6656 Diag(ParmDeclarator.getIdentifierLoc(),
6657 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6658 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6660 << !ParmDeclarator.hasName();
6662 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
6663 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6666 // We can't have any more parameters after an ellipsis.
6670 // If the next token is a comma, consume it and keep reading arguments.
6671 } while (TryConsumeToken(tok::comma));
6674 /// [C90] direct-declarator '[' constant-expression[opt] ']'
6675 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6676 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6677 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6678 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
6679 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
6680 /// attribute-specifier-seq[opt]
6681 void Parser::ParseBracketDeclarator(Declarator &D) {
6682 if (CheckProhibitedCXX11Attribute())
6685 BalancedDelimiterTracker T(*this, tok::l_square);
6688 // C array syntax has many features, but by-far the most common is [] and [4].
6689 // This code does a fast path to handle some of the most obvious cases.
6690 if (Tok.getKind() == tok::r_square) {
6692 ParsedAttributes attrs(AttrFactory);
6693 MaybeParseCXX11Attributes(attrs);
6695 // Remember that we parsed the empty array type.
6696 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
6697 T.getOpenLocation(),
6698 T.getCloseLocation()),
6699 std::move(attrs), T.getCloseLocation());
6701 } else if (Tok.getKind() == tok::numeric_constant &&
6702 GetLookAheadToken(1).is(tok::r_square)) {
6703 // [4] is very common. Parse the numeric constant expression.
6704 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
6708 ParsedAttributes attrs(AttrFactory);
6709 MaybeParseCXX11Attributes(attrs);
6711 // Remember that we parsed a array type, and remember its features.
6712 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
6713 T.getOpenLocation(),
6714 T.getCloseLocation()),
6715 std::move(attrs), T.getCloseLocation());
6717 } else if (Tok.getKind() == tok::code_completion) {
6718 Actions.CodeCompleteBracketDeclarator(getCurScope());
6719 return cutOffParsing();
6722 // If valid, this location is the position where we read the 'static' keyword.
6723 SourceLocation StaticLoc;
6724 TryConsumeToken(tok::kw_static, StaticLoc);
6726 // If there is a type-qualifier-list, read it now.
6727 // Type qualifiers in an array subscript are a C99 feature.
6728 DeclSpec DS(AttrFactory);
6729 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
6731 // If we haven't already read 'static', check to see if there is one after the
6732 // type-qualifier-list.
6733 if (!StaticLoc.isValid())
6734 TryConsumeToken(tok::kw_static, StaticLoc);
6736 // Handle "direct-declarator [ type-qual-list[opt] * ]".
6737 bool isStar = false;
6738 ExprResult NumElements;
6740 // Handle the case where we have '[*]' as the array size. However, a leading
6741 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
6742 // the token after the star is a ']'. Since stars in arrays are
6743 // infrequent, use of lookahead is not costly here.
6744 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
6745 ConsumeToken(); // Eat the '*'.
6747 if (StaticLoc.isValid()) {
6748 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
6749 StaticLoc = SourceLocation(); // Drop the static.
6752 } else if (Tok.isNot(tok::r_square)) {
6753 // Note, in C89, this production uses the constant-expr production instead
6754 // of assignment-expr. The only difference is that assignment-expr allows
6755 // things like '=' and '*='. Sema rejects these in C89 mode because they
6756 // are not i-c-e's, so we don't need to distinguish between the two here.
6758 // Parse the constant-expression or assignment-expression now (depending
6760 if (getLangOpts().CPlusPlus) {
6761 NumElements = ParseConstantExpression();
6763 EnterExpressionEvaluationContext Unevaluated(
6764 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6766 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
6769 if (StaticLoc.isValid()) {
6770 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6771 StaticLoc = SourceLocation(); // Drop the static.
6775 // If there was an error parsing the assignment-expression, recover.
6776 if (NumElements.isInvalid()) {
6777 D.setInvalidType(true);
6778 // If the expression was invalid, skip it.
6779 SkipUntil(tok::r_square, StopAtSemi);
6785 MaybeParseCXX11Attributes(DS.getAttributes());
6787 // Remember that we parsed a array type, and remember its features.
6789 DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
6790 isStar, NumElements.get(), T.getOpenLocation(),
6791 T.getCloseLocation()),
6792 std::move(DS.getAttributes()), T.getCloseLocation());
6795 /// Diagnose brackets before an identifier.
6796 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6797 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6798 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6800 SourceLocation StartBracketLoc = Tok.getLocation();
6801 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6803 while (Tok.is(tok::l_square)) {
6804 ParseBracketDeclarator(TempDeclarator);
6807 // Stuff the location of the start of the brackets into the Declarator.
6808 // The diagnostics from ParseDirectDeclarator will make more sense if
6809 // they use this location instead.
6810 if (Tok.is(tok::semi))
6811 D.getName().EndLocation = StartBracketLoc;
6813 SourceLocation SuggestParenLoc = Tok.getLocation();
6815 // Now that the brackets are removed, try parsing the declarator again.
6816 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6818 // Something went wrong parsing the brackets, in which case,
6819 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6821 if (TempDeclarator.getNumTypeObjects() == 0)
6824 // Determine if parens will need to be suggested in the diagnostic.
6825 bool NeedParens = false;
6826 if (D.getNumTypeObjects() != 0) {
6827 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6828 case DeclaratorChunk::Pointer:
6829 case DeclaratorChunk::Reference:
6830 case DeclaratorChunk::BlockPointer:
6831 case DeclaratorChunk::MemberPointer:
6832 case DeclaratorChunk::Pipe:
6835 case DeclaratorChunk::Array:
6836 case DeclaratorChunk::Function:
6837 case DeclaratorChunk::Paren:
6843 // Create a DeclaratorChunk for the inserted parens.
6844 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
6845 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
6849 // Adding back the bracket info to the end of the Declarator.
6850 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6851 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
6852 D.AddTypeInfo(Chunk, SourceLocation());
6855 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6856 // If parentheses are required, always suggest them.
6857 if (!D.getIdentifier() && !NeedParens)
6860 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
6862 // Generate the move bracket error message.
6863 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
6864 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
6867 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6868 << getLangOpts().CPlusPlus
6869 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6870 << FixItHint::CreateInsertion(EndLoc, ")")
6871 << FixItHint::CreateInsertionFromRange(
6872 EndLoc, CharSourceRange(BracketRange, true))
6873 << FixItHint::CreateRemoval(BracketRange);
6875 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6876 << getLangOpts().CPlusPlus
6877 << FixItHint::CreateInsertionFromRange(
6878 EndLoc, CharSourceRange(BracketRange, true))
6879 << FixItHint::CreateRemoval(BracketRange);
6883 /// [GNU] typeof-specifier:
6884 /// typeof ( expressions )
6885 /// typeof ( type-name )
6886 /// [GNU/C++] typeof unary-expression
6888 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
6889 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
6891 SourceLocation StartLoc = ConsumeToken();
6893 const bool hasParens = Tok.is(tok::l_paren);
6895 EnterExpressionEvaluationContext Unevaluated(
6896 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6897 Sema::ReuseLambdaContextDecl);
6901 SourceRange CastRange;
6902 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6903 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
6905 DS.setTypeofParensRange(CastRange);
6907 if (CastRange.getEnd().isInvalid())
6908 // FIXME: Not accurate, the range gets one token more than it should.
6909 DS.SetRangeEnd(Tok.getLocation());
6911 DS.SetRangeEnd(CastRange.getEnd());
6915 DS.SetTypeSpecError();
6919 const char *PrevSpec = nullptr;
6921 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6922 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
6924 Actions.getASTContext().getPrintingPolicy()))
6925 Diag(StartLoc, DiagID) << PrevSpec;
6929 // If we get here, the operand to the typeof was an expression.
6930 if (Operand.isInvalid()) {
6931 DS.SetTypeSpecError();
6935 // We might need to transform the operand if it is potentially evaluated.
6936 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6937 if (Operand.isInvalid()) {
6938 DS.SetTypeSpecError();
6942 const char *PrevSpec = nullptr;
6944 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6945 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
6946 DiagID, Operand.get(),
6947 Actions.getASTContext().getPrintingPolicy()))
6948 Diag(StartLoc, DiagID) << PrevSpec;
6951 /// [C11] atomic-specifier:
6952 /// _Atomic ( type-name )
6954 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
6955 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6956 "Not an atomic specifier");
6958 SourceLocation StartLoc = ConsumeToken();
6959 BalancedDelimiterTracker T(*this, tok::l_paren);
6960 if (T.consumeOpen())
6963 TypeResult Result = ParseTypeName();
6964 if (Result.isInvalid()) {
6965 SkipUntil(tok::r_paren, StopAtSemi);
6972 if (T.getCloseLocation().isInvalid())
6975 DS.setTypeofParensRange(T.getRange());
6976 DS.SetRangeEnd(T.getCloseLocation());
6978 const char *PrevSpec = nullptr;
6980 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
6981 DiagID, Result.get(),
6982 Actions.getASTContext().getPrintingPolicy()))
6983 Diag(StartLoc, DiagID) << PrevSpec;
6986 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6987 /// from TryAltiVecVectorToken.
6988 bool Parser::TryAltiVecVectorTokenOutOfLine() {
6989 Token Next = NextToken();
6990 switch (Next.getKind()) {
6991 default: return false;
6994 case tok::kw_signed:
6995 case tok::kw_unsigned:
7000 case tok::kw_double:
7002 case tok::kw___bool:
7003 case tok::kw___pixel:
7004 Tok.setKind(tok::kw___vector);
7006 case tok::identifier:
7007 if (Next.getIdentifierInfo() == Ident_pixel) {
7008 Tok.setKind(tok::kw___vector);
7011 if (Next.getIdentifierInfo() == Ident_bool) {
7012 Tok.setKind(tok::kw___vector);
7019 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
7020 const char *&PrevSpec, unsigned &DiagID,
7022 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
7023 if (Tok.getIdentifierInfo() == Ident_vector) {
7024 Token Next = NextToken();
7025 switch (Next.getKind()) {
7028 case tok::kw_signed:
7029 case tok::kw_unsigned:
7034 case tok::kw_double:
7036 case tok::kw___bool:
7037 case tok::kw___pixel:
7038 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
7040 case tok::identifier:
7041 if (Next.getIdentifierInfo() == Ident_pixel) {
7042 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
7045 if (Next.getIdentifierInfo() == Ident_bool) {
7046 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
7053 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
7054 DS.isTypeAltiVecVector()) {
7055 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
7057 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
7058 DS.isTypeAltiVecVector()) {
7059 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);