1 //===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Declaration portions of the Parser interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclTemplate.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/PrettyDeclStackTrace.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/SemaDiagnostic.h"
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/Support/ScopedPrinter.h"
34 using namespace clang;
36 //===----------------------------------------------------------------------===//
37 // C99 6.7: Declarations.
38 //===----------------------------------------------------------------------===//
41 /// type-name: [C99 6.7.6]
42 /// specifier-qualifier-list abstract-declarator[opt]
44 /// Called type-id in C++.
45 TypeResult Parser::ParseTypeName(SourceRange *Range,
46 Declarator::TheContext Context,
49 ParsedAttributes *Attrs) {
50 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
51 if (DSC == DSC_normal)
52 DSC = DSC_type_specifier;
54 // Parse the common declaration-specifiers piece.
55 DeclSpec DS(AttrFactory);
57 DS.addAttributes(Attrs->getList());
58 ParseSpecifierQualifierList(DS, AS, DSC);
60 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
62 // Parse the abstract-declarator, if present.
63 Declarator DeclaratorInfo(DS, Context);
64 ParseDeclarator(DeclaratorInfo);
66 *Range = DeclaratorInfo.getSourceRange();
68 if (DeclaratorInfo.isInvalidType())
71 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
74 /// isAttributeLateParsed - Return true if the attribute has arguments that
75 /// require late parsing.
76 static bool isAttributeLateParsed(const IdentifierInfo &II) {
77 #define CLANG_ATTR_LATE_PARSED_LIST
78 return llvm::StringSwitch<bool>(II.getName())
79 #include "clang/Parse/AttrParserStringSwitches.inc"
81 #undef CLANG_ATTR_LATE_PARSED_LIST
84 /// ParseGNUAttributes - Parse a non-empty attributes list.
88 /// attributes attribute
91 /// '__attribute__' '(' '(' attribute-list ')' ')'
93 /// [GNU] attribute-list:
95 /// attribute_list ',' attrib
100 /// attrib-name '(' identifier ')'
101 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
102 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
104 /// [GNU] attrib-name:
110 /// Whether an attribute takes an 'identifier' is determined by the
111 /// attrib-name. GCC's behavior here is not worth imitating:
113 /// * In C mode, if the attribute argument list starts with an identifier
114 /// followed by a ',' or an ')', and the identifier doesn't resolve to
115 /// a type, it is parsed as an identifier. If the attribute actually
116 /// wanted an expression, it's out of luck (but it turns out that no
117 /// attributes work that way, because C constant expressions are very
119 /// * In C++ mode, if the attribute argument list starts with an identifier,
120 /// and the attribute *wants* an identifier, it is parsed as an identifier.
121 /// At block scope, any additional tokens between the identifier and the
122 /// ',' or ')' are ignored, otherwise they produce a parse error.
124 /// We follow the C++ model, but don't allow junk after the identifier.
125 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
126 SourceLocation *endLoc,
127 LateParsedAttrList *LateAttrs,
129 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
131 while (Tok.is(tok::kw___attribute)) {
133 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
135 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
138 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
139 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
142 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
144 // Allow empty/non-empty attributes. ((__vector_size__(16),,,,))
145 if (TryConsumeToken(tok::comma))
148 // Expect an identifier or declaration specifier (const, int, etc.)
149 if (Tok.isAnnotation())
151 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
155 SourceLocation AttrNameLoc = ConsumeToken();
157 if (Tok.isNot(tok::l_paren)) {
158 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
159 AttributeList::AS_GNU);
163 // Handle "parameterized" attributes
164 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
165 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
166 SourceLocation(), AttributeList::AS_GNU, D);
170 // Handle attributes with arguments that require late parsing.
171 LateParsedAttribute *LA =
172 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
173 LateAttrs->push_back(LA);
175 // Attributes in a class are parsed at the end of the class, along
176 // with other late-parsed declarations.
177 if (!ClassStack.empty() && !LateAttrs->parseSoon())
178 getCurrentClass().LateParsedDeclarations.push_back(LA);
180 // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
181 // recursively consumes balanced parens.
182 LA->Toks.push_back(Tok);
184 // Consume everything up to and including the matching right parens.
185 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
189 Eof.setLocation(Tok.getLocation());
190 LA->Toks.push_back(Eof);
193 if (ExpectAndConsume(tok::r_paren))
194 SkipUntil(tok::r_paren, StopAtSemi);
195 SourceLocation Loc = Tok.getLocation();
196 if (ExpectAndConsume(tok::r_paren))
197 SkipUntil(tok::r_paren, StopAtSemi);
203 /// \brief Normalizes an attribute name by dropping prefixed and suffixed __.
204 static StringRef normalizeAttrName(StringRef Name) {
205 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
206 Name = Name.drop_front(2).drop_back(2);
210 /// \brief Determine whether the given attribute has an identifier argument.
211 static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
212 #define CLANG_ATTR_IDENTIFIER_ARG_LIST
213 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
214 #include "clang/Parse/AttrParserStringSwitches.inc"
216 #undef CLANG_ATTR_IDENTIFIER_ARG_LIST
219 /// \brief Determine whether the given attribute parses a type argument.
220 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
221 #define CLANG_ATTR_TYPE_ARG_LIST
222 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
223 #include "clang/Parse/AttrParserStringSwitches.inc"
225 #undef CLANG_ATTR_TYPE_ARG_LIST
228 /// \brief Determine whether the given attribute requires parsing its arguments
229 /// in an unevaluated context or not.
230 static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
231 #define CLANG_ATTR_ARG_CONTEXT_LIST
232 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
233 #include "clang/Parse/AttrParserStringSwitches.inc"
235 #undef CLANG_ATTR_ARG_CONTEXT_LIST
238 IdentifierLoc *Parser::ParseIdentifierLoc() {
239 assert(Tok.is(tok::identifier) && "expected an identifier");
240 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
242 Tok.getIdentifierInfo());
247 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
248 SourceLocation AttrNameLoc,
249 ParsedAttributes &Attrs,
250 SourceLocation *EndLoc,
251 IdentifierInfo *ScopeName,
252 SourceLocation ScopeLoc,
253 AttributeList::Syntax Syntax) {
254 BalancedDelimiterTracker Parens(*this, tok::l_paren);
255 Parens.consumeOpen();
258 if (Tok.isNot(tok::r_paren))
261 if (Parens.consumeClose())
268 Attrs.addNewTypeAttr(&AttrName,
269 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
270 ScopeName, ScopeLoc, T.get(), Syntax);
272 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
273 ScopeName, ScopeLoc, nullptr, 0, Syntax);
276 unsigned Parser::ParseAttributeArgsCommon(
277 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
278 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
279 SourceLocation ScopeLoc, AttributeList::Syntax Syntax) {
280 // Ignore the left paren location for now.
284 if (Tok.is(tok::identifier)) {
285 // If this attribute wants an 'identifier' argument, make it so.
286 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName);
287 AttributeList::Kind AttrKind =
288 AttributeList::getKind(AttrName, ScopeName, Syntax);
290 // If we don't know how to parse this attribute, but this is the only
291 // token in this argument, assume it's meant to be an identifier.
292 if (AttrKind == AttributeList::UnknownAttribute ||
293 AttrKind == AttributeList::IgnoredAttribute) {
294 const Token &Next = NextToken();
295 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
299 ArgExprs.push_back(ParseIdentifierLoc());
302 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
304 if (!ArgExprs.empty())
307 // Parse the non-empty comma-separated list of expressions.
309 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
310 EnterExpressionEvaluationContext Unevaluated(
311 Actions, Uneval ? Sema::Unevaluated : Sema::ConstantEvaluated,
312 /*LambdaContextDecl=*/nullptr,
313 /*IsDecltype=*/false);
316 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
317 if (ArgExpr.isInvalid()) {
318 SkipUntil(tok::r_paren, StopAtSemi);
321 ArgExprs.push_back(ArgExpr.get());
322 // Eat the comma, move to the next argument
323 } while (TryConsumeToken(tok::comma));
326 SourceLocation RParen = Tok.getLocation();
327 if (!ExpectAndConsume(tok::r_paren)) {
328 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
329 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
330 ArgExprs.data(), ArgExprs.size(), Syntax);
336 return static_cast<unsigned>(ArgExprs.size());
339 /// Parse the arguments to a parameterized GNU attribute or
340 /// a C++11 attribute in "gnu" namespace.
341 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
342 SourceLocation AttrNameLoc,
343 ParsedAttributes &Attrs,
344 SourceLocation *EndLoc,
345 IdentifierInfo *ScopeName,
346 SourceLocation ScopeLoc,
347 AttributeList::Syntax Syntax,
350 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
352 AttributeList::Kind AttrKind =
353 AttributeList::getKind(AttrName, ScopeName, Syntax);
355 if (AttrKind == AttributeList::AT_Availability) {
356 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
359 } else if (AttrKind == AttributeList::AT_ObjCBridgeRelated) {
360 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
361 ScopeName, ScopeLoc, Syntax);
363 } else if (AttrKind == AttributeList::AT_TypeTagForDatatype) {
364 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
365 ScopeName, ScopeLoc, Syntax);
367 } else if (attributeIsTypeArgAttr(*AttrName)) {
368 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
373 // These may refer to the function arguments, but need to be parsed early to
374 // participate in determining whether it's a redeclaration.
375 llvm::Optional<ParseScope> PrototypeScope;
376 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
377 D && D->isFunctionDeclarator()) {
378 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
379 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
380 Scope::FunctionDeclarationScope |
382 for (unsigned i = 0; i != FTI.NumParams; ++i) {
383 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
384 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
388 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
392 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
393 SourceLocation AttrNameLoc,
394 ParsedAttributes &Attrs) {
395 // If the attribute isn't known, we will not attempt to parse any
397 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
398 getTargetInfo(), getLangOpts())) {
399 // Eat the left paren, then skip to the ending right paren.
401 SkipUntil(tok::r_paren);
405 SourceLocation OpenParenLoc = Tok.getLocation();
407 if (AttrName->getName() == "property") {
408 // The property declspec is more complex in that it can take one or two
409 // assignment expressions as a parameter, but the lhs of the assignment
410 // must be named get or put.
412 BalancedDelimiterTracker T(*this, tok::l_paren);
413 T.expectAndConsume(diag::err_expected_lparen_after,
414 AttrName->getNameStart(), tok::r_paren);
419 AK_Get = 1 // indices into AccessorNames
421 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
422 bool HasInvalidAccessor = false;
424 // Parse the accessor specifications.
426 // Stop if this doesn't look like an accessor spec.
427 if (!Tok.is(tok::identifier)) {
428 // If the user wrote a completely empty list, use a special diagnostic.
429 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
430 AccessorNames[AK_Put] == nullptr &&
431 AccessorNames[AK_Get] == nullptr) {
432 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
436 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
441 SourceLocation KindLoc = Tok.getLocation();
442 StringRef KindStr = Tok.getIdentifierInfo()->getName();
443 if (KindStr == "get") {
445 } else if (KindStr == "put") {
448 // Recover from the common mistake of using 'set' instead of 'put'.
449 } else if (KindStr == "set") {
450 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
451 << FixItHint::CreateReplacement(KindLoc, "put");
454 // Handle the mistake of forgetting the accessor kind by skipping
456 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
457 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
459 HasInvalidAccessor = true;
460 goto next_property_accessor;
462 // Otherwise, complain about the unknown accessor kind.
464 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
465 HasInvalidAccessor = true;
468 // Try to keep parsing unless it doesn't look like an accessor spec.
469 if (!NextToken().is(tok::equal))
473 // Consume the identifier.
477 if (!TryConsumeToken(tok::equal)) {
478 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
483 // Expect the method name.
484 if (!Tok.is(tok::identifier)) {
485 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
489 if (Kind == AK_Invalid) {
490 // Just drop invalid accessors.
491 } else if (AccessorNames[Kind] != nullptr) {
492 // Complain about the repeated accessor, ignore it, and keep parsing.
493 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
495 AccessorNames[Kind] = Tok.getIdentifierInfo();
499 next_property_accessor:
500 // Keep processing accessors until we run out.
501 if (TryConsumeToken(tok::comma))
504 // If we run into the ')', stop without consuming it.
505 if (Tok.is(tok::r_paren))
508 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
512 // Only add the property attribute if it was well-formed.
513 if (!HasInvalidAccessor)
514 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
515 AccessorNames[AK_Get], AccessorNames[AK_Put],
516 AttributeList::AS_Declspec);
518 return !HasInvalidAccessor;
522 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
523 SourceLocation(), AttributeList::AS_Declspec);
525 // If this attribute's args were parsed, and it was expected to have
526 // arguments but none were provided, emit a diagnostic.
527 const AttributeList *Attr = Attrs.getList();
528 if (Attr && Attr->getMaxArgs() && !NumArgs) {
529 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
535 /// [MS] decl-specifier:
536 /// __declspec ( extended-decl-modifier-seq )
538 /// [MS] extended-decl-modifier-seq:
539 /// extended-decl-modifier[opt]
540 /// extended-decl-modifier extended-decl-modifier-seq
541 void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
542 SourceLocation *End) {
543 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
544 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
546 while (Tok.is(tok::kw___declspec)) {
548 BalancedDelimiterTracker T(*this, tok::l_paren);
549 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
553 // An empty declspec is perfectly legal and should not warn. Additionally,
554 // you can specify multiple attributes per declspec.
555 while (Tok.isNot(tok::r_paren)) {
556 // Attribute not present.
557 if (TryConsumeToken(tok::comma))
560 // We expect either a well-known identifier or a generic string. Anything
561 // else is a malformed declspec.
562 bool IsString = Tok.getKind() == tok::string_literal;
563 if (!IsString && Tok.getKind() != tok::identifier &&
564 Tok.getKind() != tok::kw_restrict) {
565 Diag(Tok, diag::err_ms_declspec_type);
570 IdentifierInfo *AttrName;
571 SourceLocation AttrNameLoc;
573 SmallString<8> StrBuffer;
574 bool Invalid = false;
575 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
580 AttrName = PP.getIdentifierInfo(Str);
581 AttrNameLoc = ConsumeStringToken();
583 AttrName = Tok.getIdentifierInfo();
584 AttrNameLoc = ConsumeToken();
587 bool AttrHandled = false;
589 // Parse attribute arguments.
590 if (Tok.is(tok::l_paren))
591 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
592 else if (AttrName->getName() == "property")
593 // The property attribute must have an argument list.
594 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
595 << AttrName->getName();
598 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
599 AttributeList::AS_Declspec);
603 *End = T.getCloseLocation();
607 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
608 // Treat these like attributes
610 switch (Tok.getKind()) {
611 case tok::kw___fastcall:
612 case tok::kw___stdcall:
613 case tok::kw___thiscall:
614 case tok::kw___regcall:
615 case tok::kw___cdecl:
616 case tok::kw___vectorcall:
617 case tok::kw___ptr64:
619 case tok::kw___ptr32:
621 case tok::kw___uptr: {
622 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
623 SourceLocation AttrNameLoc = ConsumeToken();
624 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
625 AttributeList::AS_Keyword);
634 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
635 SourceLocation StartLoc = Tok.getLocation();
636 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
638 if (EndLoc.isValid()) {
639 SourceRange Range(StartLoc, EndLoc);
640 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
644 SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
645 SourceLocation EndLoc;
648 switch (Tok.getKind()) {
650 case tok::kw_volatile:
651 case tok::kw___fastcall:
652 case tok::kw___stdcall:
653 case tok::kw___thiscall:
654 case tok::kw___cdecl:
655 case tok::kw___vectorcall:
656 case tok::kw___ptr32:
657 case tok::kw___ptr64:
659 case tok::kw___unaligned:
662 EndLoc = ConsumeToken();
670 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
671 // Treat these like attributes
672 while (Tok.is(tok::kw___pascal)) {
673 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
674 SourceLocation AttrNameLoc = ConsumeToken();
675 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
676 AttributeList::AS_Keyword);
680 void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
681 // Treat these like attributes
682 while (Tok.is(tok::kw___kernel)) {
683 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
684 SourceLocation AttrNameLoc = ConsumeToken();
685 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
686 AttributeList::AS_Keyword);
690 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
691 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
692 SourceLocation AttrNameLoc = Tok.getLocation();
693 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
694 AttributeList::AS_Keyword);
697 void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
698 // Treat these like attributes, even though they're type specifiers.
700 switch (Tok.getKind()) {
701 case tok::kw__Nonnull:
702 case tok::kw__Nullable:
703 case tok::kw__Null_unspecified: {
704 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
705 SourceLocation AttrNameLoc = ConsumeToken();
706 if (!getLangOpts().ObjC1)
707 Diag(AttrNameLoc, diag::ext_nullability)
709 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
710 AttributeList::AS_Keyword);
719 static bool VersionNumberSeparator(const char Separator) {
720 return (Separator == '.' || Separator == '_');
723 /// \brief Parse a version number.
727 /// simple-integer ',' simple-integer
728 /// simple-integer ',' simple-integer ',' simple-integer
729 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
730 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
732 if (!Tok.is(tok::numeric_constant)) {
733 Diag(Tok, diag::err_expected_version);
734 SkipUntil(tok::comma, tok::r_paren,
735 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
736 return VersionTuple();
739 // Parse the major (and possibly minor and subminor) versions, which
740 // are stored in the numeric constant. We utilize a quirk of the
741 // lexer, which is that it handles something like 1.2.3 as a single
742 // numeric constant, rather than two separate tokens.
743 SmallString<512> Buffer;
744 Buffer.resize(Tok.getLength()+1);
745 const char *ThisTokBegin = &Buffer[0];
747 // Get the spelling of the token, which eliminates trigraphs, etc.
748 bool Invalid = false;
749 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
751 return VersionTuple();
753 // Parse the major version.
754 unsigned AfterMajor = 0;
756 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
757 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
761 if (AfterMajor == 0) {
762 Diag(Tok, diag::err_expected_version);
763 SkipUntil(tok::comma, tok::r_paren,
764 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
765 return VersionTuple();
768 if (AfterMajor == ActualLength) {
771 // We only had a single version component.
773 Diag(Tok, diag::err_zero_version);
774 return VersionTuple();
777 return VersionTuple(Major);
780 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
781 if (!VersionNumberSeparator(AfterMajorSeparator)
782 || (AfterMajor + 1 == ActualLength)) {
783 Diag(Tok, diag::err_expected_version);
784 SkipUntil(tok::comma, tok::r_paren,
785 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
786 return VersionTuple();
789 // Parse the minor version.
790 unsigned AfterMinor = AfterMajor + 1;
792 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
793 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
797 if (AfterMinor == ActualLength) {
800 // We had major.minor.
801 if (Major == 0 && Minor == 0) {
802 Diag(Tok, diag::err_zero_version);
803 return VersionTuple();
806 return VersionTuple(Major, Minor, (AfterMajorSeparator == '_'));
809 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
810 // If what follows is not a '.' or '_', we have a problem.
811 if (!VersionNumberSeparator(AfterMinorSeparator)) {
812 Diag(Tok, diag::err_expected_version);
813 SkipUntil(tok::comma, tok::r_paren,
814 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
815 return VersionTuple();
818 // Warn if separators, be it '.' or '_', do not match.
819 if (AfterMajorSeparator != AfterMinorSeparator)
820 Diag(Tok, diag::warn_expected_consistent_version_separator);
822 // Parse the subminor version.
823 unsigned AfterSubminor = AfterMinor + 1;
824 unsigned Subminor = 0;
825 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
826 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
830 if (AfterSubminor != ActualLength) {
831 Diag(Tok, diag::err_expected_version);
832 SkipUntil(tok::comma, tok::r_paren,
833 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
834 return VersionTuple();
837 return VersionTuple(Major, Minor, Subminor, (AfterMajorSeparator == '_'));
840 /// \brief Parse the contents of the "availability" attribute.
842 /// availability-attribute:
843 /// 'availability' '(' platform ',' opt-strict version-arg-list,
844 /// opt-replacement, opt-message')'
852 /// version-arg-list:
854 /// version-arg ',' version-arg-list
857 /// 'introduced' '=' version
858 /// 'deprecated' '=' version
859 /// 'obsoleted' = version
862 /// 'replacement' '=' <string>
864 /// 'message' '=' <string>
865 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
866 SourceLocation AvailabilityLoc,
867 ParsedAttributes &attrs,
868 SourceLocation *endLoc,
869 IdentifierInfo *ScopeName,
870 SourceLocation ScopeLoc,
871 AttributeList::Syntax Syntax) {
872 enum { Introduced, Deprecated, Obsoleted, Unknown };
873 AvailabilityChange Changes[Unknown];
874 ExprResult MessageExpr, ReplacementExpr;
877 BalancedDelimiterTracker T(*this, tok::l_paren);
878 if (T.consumeOpen()) {
879 Diag(Tok, diag::err_expected) << tok::l_paren;
883 // Parse the platform name.
884 if (Tok.isNot(tok::identifier)) {
885 Diag(Tok, diag::err_availability_expected_platform);
886 SkipUntil(tok::r_paren, StopAtSemi);
889 IdentifierLoc *Platform = ParseIdentifierLoc();
890 // Canonicalize platform name from "macosx" to "macos".
891 if (Platform->Ident && Platform->Ident->getName() == "macosx")
892 Platform->Ident = PP.getIdentifierInfo("macos");
893 // Canonicalize platform name from "macosx_app_extension" to
894 // "macos_app_extension".
895 if (Platform->Ident && Platform->Ident->getName() == "macosx_app_extension")
896 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
898 // Parse the ',' following the platform name.
899 if (ExpectAndConsume(tok::comma)) {
900 SkipUntil(tok::r_paren, StopAtSemi);
904 // If we haven't grabbed the pointers for the identifiers
905 // "introduced", "deprecated", and "obsoleted", do so now.
906 if (!Ident_introduced) {
907 Ident_introduced = PP.getIdentifierInfo("introduced");
908 Ident_deprecated = PP.getIdentifierInfo("deprecated");
909 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
910 Ident_unavailable = PP.getIdentifierInfo("unavailable");
911 Ident_message = PP.getIdentifierInfo("message");
912 Ident_strict = PP.getIdentifierInfo("strict");
913 Ident_replacement = PP.getIdentifierInfo("replacement");
916 // Parse the optional "strict", the optional "replacement" and the set of
917 // introductions/deprecations/removals.
918 SourceLocation UnavailableLoc, StrictLoc;
920 if (Tok.isNot(tok::identifier)) {
921 Diag(Tok, diag::err_availability_expected_change);
922 SkipUntil(tok::r_paren, StopAtSemi);
925 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
926 SourceLocation KeywordLoc = ConsumeToken();
928 if (Keyword == Ident_strict) {
929 if (StrictLoc.isValid()) {
930 Diag(KeywordLoc, diag::err_availability_redundant)
931 << Keyword << SourceRange(StrictLoc);
933 StrictLoc = KeywordLoc;
937 if (Keyword == Ident_unavailable) {
938 if (UnavailableLoc.isValid()) {
939 Diag(KeywordLoc, diag::err_availability_redundant)
940 << Keyword << SourceRange(UnavailableLoc);
942 UnavailableLoc = KeywordLoc;
946 if (Tok.isNot(tok::equal)) {
947 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
948 SkipUntil(tok::r_paren, StopAtSemi);
952 if (Keyword == Ident_message || Keyword == Ident_replacement) {
953 if (Tok.isNot(tok::string_literal)) {
954 Diag(Tok, diag::err_expected_string_literal)
955 << /*Source='availability attribute'*/2;
956 SkipUntil(tok::r_paren, StopAtSemi);
959 if (Keyword == Ident_message)
960 MessageExpr = ParseStringLiteralExpression();
962 ReplacementExpr = ParseStringLiteralExpression();
963 // Also reject wide string literals.
964 if (StringLiteral *MessageStringLiteral =
965 cast_or_null<StringLiteral>(MessageExpr.get())) {
966 if (MessageStringLiteral->getCharByteWidth() != 1) {
967 Diag(MessageStringLiteral->getSourceRange().getBegin(),
968 diag::err_expected_string_literal)
969 << /*Source='availability attribute'*/ 2;
970 SkipUntil(tok::r_paren, StopAtSemi);
974 if (Keyword == Ident_message)
980 // Special handling of 'NA' only when applied to introduced or
982 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
983 Tok.is(tok::identifier)) {
984 IdentifierInfo *NA = Tok.getIdentifierInfo();
985 if (NA->getName() == "NA") {
987 if (Keyword == Ident_introduced)
988 UnavailableLoc = KeywordLoc;
993 SourceRange VersionRange;
994 VersionTuple Version = ParseVersionTuple(VersionRange);
996 if (Version.empty()) {
997 SkipUntil(tok::r_paren, StopAtSemi);
1002 if (Keyword == Ident_introduced)
1004 else if (Keyword == Ident_deprecated)
1006 else if (Keyword == Ident_obsoleted)
1011 if (Index < Unknown) {
1012 if (!Changes[Index].KeywordLoc.isInvalid()) {
1013 Diag(KeywordLoc, diag::err_availability_redundant)
1015 << SourceRange(Changes[Index].KeywordLoc,
1016 Changes[Index].VersionRange.getEnd());
1019 Changes[Index].KeywordLoc = KeywordLoc;
1020 Changes[Index].Version = Version;
1021 Changes[Index].VersionRange = VersionRange;
1023 Diag(KeywordLoc, diag::err_availability_unknown_change)
1024 << Keyword << VersionRange;
1027 } while (TryConsumeToken(tok::comma));
1030 if (T.consumeClose())
1034 *endLoc = T.getCloseLocation();
1036 // The 'unavailable' availability cannot be combined with any other
1037 // availability changes. Make sure that hasn't happened.
1038 if (UnavailableLoc.isValid()) {
1039 bool Complained = false;
1040 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1041 if (Changes[Index].KeywordLoc.isValid()) {
1043 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1044 << SourceRange(Changes[Index].KeywordLoc,
1045 Changes[Index].VersionRange.getEnd());
1049 // Clear out the availability.
1050 Changes[Index] = AvailabilityChange();
1055 // Record this attribute
1056 attrs.addNew(&Availability,
1057 SourceRange(AvailabilityLoc, T.getCloseLocation()),
1058 ScopeName, ScopeLoc,
1060 Changes[Introduced],
1061 Changes[Deprecated],
1063 UnavailableLoc, MessageExpr.get(),
1064 Syntax, StrictLoc, ReplacementExpr.get());
1067 /// \brief Parse the contents of the "objc_bridge_related" attribute.
1068 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1072 /// opt-class_method:
1073 /// Identifier: | <empty>
1075 /// opt-instance_method:
1076 /// Identifier | <empty>
1078 void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1079 SourceLocation ObjCBridgeRelatedLoc,
1080 ParsedAttributes &attrs,
1081 SourceLocation *endLoc,
1082 IdentifierInfo *ScopeName,
1083 SourceLocation ScopeLoc,
1084 AttributeList::Syntax Syntax) {
1086 BalancedDelimiterTracker T(*this, tok::l_paren);
1087 if (T.consumeOpen()) {
1088 Diag(Tok, diag::err_expected) << tok::l_paren;
1092 // Parse the related class name.
1093 if (Tok.isNot(tok::identifier)) {
1094 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1095 SkipUntil(tok::r_paren, StopAtSemi);
1098 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1099 if (ExpectAndConsume(tok::comma)) {
1100 SkipUntil(tok::r_paren, StopAtSemi);
1104 // Parse optional class method name.
1105 IdentifierLoc *ClassMethod = nullptr;
1106 if (Tok.is(tok::identifier)) {
1107 ClassMethod = ParseIdentifierLoc();
1108 if (!TryConsumeToken(tok::colon)) {
1109 Diag(Tok, diag::err_objcbridge_related_selector_name);
1110 SkipUntil(tok::r_paren, StopAtSemi);
1114 if (!TryConsumeToken(tok::comma)) {
1115 if (Tok.is(tok::colon))
1116 Diag(Tok, diag::err_objcbridge_related_selector_name);
1118 Diag(Tok, diag::err_expected) << tok::comma;
1119 SkipUntil(tok::r_paren, StopAtSemi);
1123 // Parse optional instance method name.
1124 IdentifierLoc *InstanceMethod = nullptr;
1125 if (Tok.is(tok::identifier))
1126 InstanceMethod = ParseIdentifierLoc();
1127 else if (Tok.isNot(tok::r_paren)) {
1128 Diag(Tok, diag::err_expected) << tok::r_paren;
1129 SkipUntil(tok::r_paren, StopAtSemi);
1134 if (T.consumeClose())
1138 *endLoc = T.getCloseLocation();
1140 // Record this attribute
1141 attrs.addNew(&ObjCBridgeRelated,
1142 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1143 ScopeName, ScopeLoc,
1150 // Late Parsed Attributes:
1151 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1153 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1155 void Parser::LateParsedClass::ParseLexedAttributes() {
1156 Self->ParseLexedAttributes(*Class);
1159 void Parser::LateParsedAttribute::ParseLexedAttributes() {
1160 Self->ParseLexedAttribute(*this, true, false);
1163 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1164 /// scope appropriately.
1165 void Parser::ParseLexedAttributes(ParsingClass &Class) {
1166 // Deal with templates
1167 // FIXME: Test cases to make sure this does the right thing for templates.
1168 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1169 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1171 if (HasTemplateScope)
1172 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1174 // Set or update the scope flags.
1175 bool AlreadyHasClassScope = Class.TopLevelClass;
1176 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
1177 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1178 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1180 // Enter the scope of nested classes
1181 if (!AlreadyHasClassScope)
1182 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1183 Class.TagOrTemplate);
1184 if (!Class.LateParsedDeclarations.empty()) {
1185 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1186 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1190 if (!AlreadyHasClassScope)
1191 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1192 Class.TagOrTemplate);
1195 /// \brief Parse all attributes in LAs, and attach them to Decl D.
1196 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1197 bool EnterScope, bool OnDefinition) {
1198 assert(LAs.parseSoon() &&
1199 "Attribute list should be marked for immediate parsing.");
1200 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1203 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1209 /// \brief Finish parsing an attribute for which parsing was delayed.
1210 /// This will be called at the end of parsing a class declaration
1211 /// for each LateParsedAttribute. We consume the saved tokens and
1212 /// create an attribute with the arguments filled in. We add this
1213 /// to the Attribute list for the decl.
1214 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1215 bool EnterScope, bool OnDefinition) {
1216 // Create a fake EOF so that attribute parsing won't go off the end of the
1219 AttrEnd.startToken();
1220 AttrEnd.setKind(tok::eof);
1221 AttrEnd.setLocation(Tok.getLocation());
1222 AttrEnd.setEofData(LA.Toks.data());
1223 LA.Toks.push_back(AttrEnd);
1225 // Append the current token at the end of the new token stream so that it
1226 // doesn't get lost.
1227 LA.Toks.push_back(Tok);
1228 PP.EnterTokenStream(LA.Toks, true);
1229 // Consume the previously pushed token.
1230 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1232 ParsedAttributes Attrs(AttrFactory);
1233 SourceLocation endLoc;
1235 if (LA.Decls.size() > 0) {
1236 Decl *D = LA.Decls[0];
1237 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1238 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1240 // Allow 'this' within late-parsed attributes.
1241 Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0,
1242 ND && ND->isCXXInstanceMember());
1244 if (LA.Decls.size() == 1) {
1245 // If the Decl is templatized, add template parameters to scope.
1246 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1247 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1248 if (HasTemplateScope)
1249 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1251 // If the Decl is on a function, add function parameters to the scope.
1252 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1253 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunScope);
1255 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1257 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1258 nullptr, SourceLocation(), AttributeList::AS_GNU,
1262 Actions.ActOnExitFunctionContext();
1263 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1265 if (HasTemplateScope) {
1269 // If there are multiple decls, then the decl cannot be within the
1271 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1272 nullptr, SourceLocation(), AttributeList::AS_GNU,
1276 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1279 const AttributeList *AL = Attrs.getList();
1280 if (OnDefinition && AL && !AL->isCXX11Attribute() &&
1282 Diag(Tok, diag::warn_attribute_on_function_definition)
1285 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
1286 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1288 // Due to a parsing error, we either went over the cached tokens or
1289 // there are still cached tokens left, so we skip the leftover tokens.
1290 while (Tok.isNot(tok::eof))
1293 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1297 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1298 SourceLocation AttrNameLoc,
1299 ParsedAttributes &Attrs,
1300 SourceLocation *EndLoc,
1301 IdentifierInfo *ScopeName,
1302 SourceLocation ScopeLoc,
1303 AttributeList::Syntax Syntax) {
1304 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1306 BalancedDelimiterTracker T(*this, tok::l_paren);
1309 if (Tok.isNot(tok::identifier)) {
1310 Diag(Tok, diag::err_expected) << tok::identifier;
1314 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1316 if (ExpectAndConsume(tok::comma)) {
1321 SourceRange MatchingCTypeRange;
1322 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1323 if (MatchingCType.isInvalid()) {
1328 bool LayoutCompatible = false;
1329 bool MustBeNull = false;
1330 while (TryConsumeToken(tok::comma)) {
1331 if (Tok.isNot(tok::identifier)) {
1332 Diag(Tok, diag::err_expected) << tok::identifier;
1336 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1337 if (Flag->isStr("layout_compatible"))
1338 LayoutCompatible = true;
1339 else if (Flag->isStr("must_be_null"))
1342 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1346 ConsumeToken(); // consume flag
1349 if (!T.consumeClose()) {
1350 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1351 ArgumentKind, MatchingCType.get(),
1352 LayoutCompatible, MustBeNull, Syntax);
1356 *EndLoc = T.getCloseLocation();
1359 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1360 /// of a C++11 attribute-specifier in a location where an attribute is not
1361 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1364 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1365 /// this doesn't appear to actually be an attribute-specifier, and the caller
1366 /// should try to parse it.
1367 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1368 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1370 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1371 case CAK_NotAttributeSpecifier:
1372 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1375 case CAK_InvalidAttributeSpecifier:
1376 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1379 case CAK_AttributeSpecifier:
1380 // Parse and discard the attributes.
1381 SourceLocation BeginLoc = ConsumeBracket();
1383 SkipUntil(tok::r_square);
1384 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1385 SourceLocation EndLoc = ConsumeBracket();
1386 Diag(BeginLoc, diag::err_attributes_not_allowed)
1387 << SourceRange(BeginLoc, EndLoc);
1390 llvm_unreachable("All cases handled above.");
1393 /// \brief We have found the opening square brackets of a C++11
1394 /// attribute-specifier in a location where an attribute is not permitted, but
1395 /// we know where the attributes ought to be written. Parse them anyway, and
1396 /// provide a fixit moving them to the right place.
1397 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1398 SourceLocation CorrectLocation) {
1399 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1400 Tok.is(tok::kw_alignas));
1402 // Consume the attributes.
1403 SourceLocation Loc = Tok.getLocation();
1404 ParseCXX11Attributes(Attrs);
1405 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1407 Diag(Loc, diag::err_attributes_not_allowed)
1408 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1409 << FixItHint::CreateRemoval(AttrRange);
1412 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
1413 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
1417 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1419 for (AttributeList *Attr = Attrs.getList(); Attr; Attr = Attr->getNext()) {
1420 if (!Attr->isCXX11Attribute())
1422 if (Attr->getKind() == AttributeList::UnknownAttribute)
1423 Diag(Attr->getLoc(), diag::warn_unknown_attribute_ignored)
1426 Diag(Attr->getLoc(), DiagID)
1433 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1434 // applies to var, not the type Foo.
1435 // As an exception to the rule, __declspec(align(...)) before the
1436 // class-key affects the type instead of the variable.
1437 // Also, Microsoft-style [attributes] seem to affect the type instead of the
1439 // This function moves attributes that should apply to the type off DS to Attrs.
1440 void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1442 Sema::TagUseKind TUK) {
1443 if (TUK == Sema::TUK_Reference)
1446 ParsedAttributes &PA = DS.getAttributes();
1447 AttributeList *AL = PA.getList();
1448 AttributeList *Prev = nullptr;
1449 AttributeList *TypeAttrHead = nullptr;
1450 AttributeList *TypeAttrTail = nullptr;
1452 AttributeList *Next = AL->getNext();
1454 if ((AL->getKind() == AttributeList::AT_Aligned &&
1455 AL->isDeclspecAttribute()) ||
1456 AL->isMicrosoftAttribute()) {
1457 // Stitch the attribute into the tag's attribute list.
1459 TypeAttrTail->setNext(AL);
1463 TypeAttrTail->setNext(nullptr);
1465 // Remove the attribute from the variable's attribute list.
1467 // Set the last variable attribute's next attribute to be the attribute
1468 // after the current one.
1469 Prev->setNext(Next);
1471 // Removing the head of the list requires us to reset the head to the
1482 // Find end of type attributes Attrs and add NewTypeAttributes in the same
1483 // order they were in originally. (Remember, in AttributeList things earlier
1484 // in source order are later in the list, since new attributes are added to
1485 // the front of the list.)
1486 Attrs.addAllAtEnd(TypeAttrHead);
1489 /// ParseDeclaration - Parse a full 'declaration', which consists of
1490 /// declaration-specifiers, some number of declarators, and a semicolon.
1491 /// 'Context' should be a Declarator::TheContext value. This returns the
1492 /// location of the semicolon in DeclEnd.
1494 /// declaration: [C99 6.7]
1495 /// block-declaration ->
1496 /// simple-declaration
1498 /// [C++] template-declaration
1499 /// [C++] namespace-definition
1500 /// [C++] using-directive
1501 /// [C++] using-declaration
1502 /// [C++11/C11] static_assert-declaration
1503 /// others... [FIXME]
1505 Parser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context,
1506 SourceLocation &DeclEnd,
1507 ParsedAttributesWithRange &attrs) {
1508 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1509 // Must temporarily exit the objective-c container scope for
1510 // parsing c none objective-c decls.
1511 ObjCDeclContextSwitch ObjCDC(*this);
1513 Decl *SingleDecl = nullptr;
1514 switch (Tok.getKind()) {
1515 case tok::kw_template:
1516 case tok::kw_export:
1517 ProhibitAttributes(attrs);
1518 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
1520 case tok::kw_inline:
1521 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1522 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1523 ProhibitAttributes(attrs);
1524 SourceLocation InlineLoc = ConsumeToken();
1525 return ParseNamespace(Context, DeclEnd, InlineLoc);
1527 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
1529 case tok::kw_namespace:
1530 ProhibitAttributes(attrs);
1531 return ParseNamespace(Context, DeclEnd);
1533 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1535 case tok::kw_static_assert:
1536 case tok::kw__Static_assert:
1537 ProhibitAttributes(attrs);
1538 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1541 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
1544 // This routine returns a DeclGroup, if the thing we parsed only contains a
1545 // single decl, convert it now.
1546 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1549 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1550 /// declaration-specifiers init-declarator-list[opt] ';'
1551 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1552 /// init-declarator-list ';'
1553 ///[C90/C++]init-declarator-list ';' [TODO]
1554 /// [OMP] threadprivate-directive [TODO]
1556 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1557 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1559 /// If RequireSemi is false, this does not check for a ';' at the end of the
1560 /// declaration. If it is true, it checks for and eats it.
1562 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1563 /// of a simple-declaration. If we find that we are, we also parse the
1564 /// for-range-initializer, and place it here.
1565 Parser::DeclGroupPtrTy
1566 Parser::ParseSimpleDeclaration(unsigned Context,
1567 SourceLocation &DeclEnd,
1568 ParsedAttributesWithRange &Attrs,
1569 bool RequireSemi, ForRangeInit *FRI) {
1570 // Parse the common declaration-specifiers piece.
1571 ParsingDeclSpec DS(*this);
1573 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1574 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1576 // If we had a free-standing type definition with a missing semicolon, we
1577 // may get this far before the problem becomes obvious.
1578 if (DS.hasTagDefinition() &&
1579 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1582 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1583 // declaration-specifiers init-declarator-list[opt] ';'
1584 if (Tok.is(tok::semi)) {
1585 ProhibitAttributes(Attrs);
1586 DeclEnd = Tok.getLocation();
1587 if (RequireSemi) ConsumeToken();
1588 RecordDecl *AnonRecord = nullptr;
1589 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1591 DS.complete(TheDecl);
1593 Decl* decls[] = {AnonRecord, TheDecl};
1594 return Actions.BuildDeclaratorGroup(decls);
1596 return Actions.ConvertDeclToDeclGroup(TheDecl);
1599 DS.takeAttributesFrom(Attrs);
1600 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1603 /// Returns true if this might be the start of a declarator, or a common typo
1604 /// for a declarator.
1605 bool Parser::MightBeDeclarator(unsigned Context) {
1606 switch (Tok.getKind()) {
1607 case tok::annot_cxxscope:
1608 case tok::annot_template_id:
1610 case tok::code_completion:
1611 case tok::coloncolon:
1613 case tok::kw___attribute:
1614 case tok::kw_operator:
1621 return getLangOpts().CPlusPlus;
1623 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1624 return Context == Declarator::MemberContext && getLangOpts().CPlusPlus11 &&
1625 NextToken().is(tok::l_square);
1627 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1628 return Context == Declarator::MemberContext || getLangOpts().CPlusPlus;
1630 case tok::identifier:
1631 switch (NextToken().getKind()) {
1632 case tok::code_completion:
1633 case tok::coloncolon:
1636 case tok::equalequal: // Might be a typo for '='.
1637 case tok::kw_alignas:
1639 case tok::kw___attribute:
1651 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1652 // and in block scope it's probably a label. Inside a class definition,
1653 // this is a bit-field.
1654 return Context == Declarator::MemberContext ||
1655 (getLangOpts().CPlusPlus && Context == Declarator::FileContext);
1657 case tok::identifier: // Possible virt-specifier.
1658 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1669 /// Skip until we reach something which seems like a sensible place to pick
1670 /// up parsing after a malformed declaration. This will sometimes stop sooner
1671 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1672 void Parser::SkipMalformedDecl() {
1674 switch (Tok.getKind()) {
1676 // Skip until matching }, then stop. We've probably skipped over
1677 // a malformed class or function definition or similar.
1679 SkipUntil(tok::r_brace);
1680 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1681 // This declaration isn't over yet. Keep skipping.
1684 TryConsumeToken(tok::semi);
1689 SkipUntil(tok::r_square);
1694 SkipUntil(tok::r_paren);
1704 case tok::kw_inline:
1705 // 'inline namespace' at the start of a line is almost certainly
1706 // a good place to pick back up parsing, except in an Objective-C
1707 // @interface context.
1708 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1709 (!ParsingInObjCContainer || CurParsedObjCImpl))
1713 case tok::kw_namespace:
1714 // 'namespace' at the start of a line is almost certainly a good
1715 // place to pick back up parsing, except in an Objective-C
1716 // @interface context.
1717 if (Tok.isAtStartOfLine() &&
1718 (!ParsingInObjCContainer || CurParsedObjCImpl))
1723 // @end is very much like } in Objective-C contexts.
1724 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1725 ParsingInObjCContainer)
1731 // - and + probably start new method declarations in Objective-C contexts.
1732 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1737 case tok::annot_module_begin:
1738 case tok::annot_module_end:
1739 case tok::annot_module_include:
1750 /// ParseDeclGroup - Having concluded that this is either a function
1751 /// definition or a group of object declarations, actually parse the
1753 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1755 SourceLocation *DeclEnd,
1756 ForRangeInit *FRI) {
1757 // Parse the first declarator.
1758 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
1761 // Bail out if the first declarator didn't seem well-formed.
1762 if (!D.hasName() && !D.mayOmitIdentifier()) {
1763 SkipMalformedDecl();
1767 // Save late-parsed attributes for now; they need to be parsed in the
1768 // appropriate function scope after the function Decl has been constructed.
1769 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1770 LateParsedAttrList LateParsedAttrs(true);
1771 if (D.isFunctionDeclarator()) {
1772 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1774 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1775 // attribute. If we find the keyword here, tell the user to put it
1776 // at the start instead.
1777 if (Tok.is(tok::kw__Noreturn)) {
1778 SourceLocation Loc = ConsumeToken();
1779 const char *PrevSpec;
1782 // We can offer a fixit if it's valid to mark this function as _Noreturn
1783 // and we don't have any other declarators in this declaration.
1784 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1785 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1786 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
1788 Diag(Loc, diag::err_c11_noreturn_misplaced)
1789 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
1790 << (Fixit ? FixItHint::CreateInsertion(D.getLocStart(), "_Noreturn ")
1795 // Check to see if we have a function *definition* which must have a body.
1796 if (D.isFunctionDeclarator() &&
1797 // Look at the next token to make sure that this isn't a function
1798 // declaration. We have to check this because __attribute__ might be the
1799 // start of a function definition in GCC-extended K&R C.
1800 !isDeclarationAfterDeclarator()) {
1802 // Function definitions are only allowed at file scope and in C++ classes.
1803 // The C++ inline method definition case is handled elsewhere, so we only
1804 // need to handle the file scope definition case.
1805 if (Context == Declarator::FileContext) {
1806 if (isStartOfFunctionDefinition(D)) {
1807 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1808 Diag(Tok, diag::err_function_declared_typedef);
1810 // Recover by treating the 'typedef' as spurious.
1811 DS.ClearStorageClassSpecs();
1815 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1816 return Actions.ConvertDeclToDeclGroup(TheDecl);
1819 if (isDeclarationSpecifier()) {
1820 // If there is an invalid declaration specifier right after the
1821 // function prototype, then we must be in a missing semicolon case
1822 // where this isn't actually a body. Just fall through into the code
1823 // that handles it as a prototype, and let the top-level code handle
1824 // the erroneous declspec where it would otherwise expect a comma or
1827 Diag(Tok, diag::err_expected_fn_body);
1828 SkipUntil(tok::semi);
1832 if (Tok.is(tok::l_brace)) {
1833 Diag(Tok, diag::err_function_definition_not_allowed);
1834 SkipMalformedDecl();
1840 if (ParseAsmAttributesAfterDeclarator(D))
1843 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1844 // must parse and analyze the for-range-initializer before the declaration is
1847 // Handle the Objective-C for-in loop variable similarly, although we
1848 // don't need to parse the container in advance.
1849 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
1850 bool IsForRangeLoop = false;
1851 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
1852 IsForRangeLoop = true;
1853 if (Tok.is(tok::l_brace))
1854 FRI->RangeExpr = ParseBraceInitializer();
1856 FRI->RangeExpr = ParseExpression();
1859 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1861 Actions.ActOnCXXForRangeDecl(ThisDecl);
1862 Actions.FinalizeDeclaration(ThisDecl);
1863 D.complete(ThisDecl);
1864 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
1867 SmallVector<Decl *, 8> DeclsInGroup;
1868 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
1869 D, ParsedTemplateInfo(), FRI);
1870 if (LateParsedAttrs.size() > 0)
1871 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
1872 D.complete(FirstDecl);
1874 DeclsInGroup.push_back(FirstDecl);
1876 bool ExpectSemi = Context != Declarator::ForContext;
1878 // If we don't have a comma, it is either the end of the list (a ';') or an
1880 SourceLocation CommaLoc;
1881 while (TryConsumeToken(tok::comma, CommaLoc)) {
1882 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
1883 // This comma was followed by a line-break and something which can't be
1884 // the start of a declarator. The comma was probably a typo for a
1886 Diag(CommaLoc, diag::err_expected_semi_declaration)
1887 << FixItHint::CreateReplacement(CommaLoc, ";");
1892 // Parse the next declarator.
1894 D.setCommaLoc(CommaLoc);
1896 // Accept attributes in an init-declarator. In the first declarator in a
1897 // declaration, these would be part of the declspec. In subsequent
1898 // declarators, they become part of the declarator itself, so that they
1899 // don't apply to declarators after *this* one. Examples:
1900 // short __attribute__((common)) var; -> declspec
1901 // short var __attribute__((common)); -> declarator
1902 // short x, __attribute__((common)) var; -> declarator
1903 MaybeParseGNUAttributes(D);
1905 // MSVC parses but ignores qualifiers after the comma as an extension.
1906 if (getLangOpts().MicrosoftExt)
1907 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
1910 if (!D.isInvalidType()) {
1911 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
1912 D.complete(ThisDecl);
1914 DeclsInGroup.push_back(ThisDecl);
1919 *DeclEnd = Tok.getLocation();
1922 ExpectAndConsumeSemi(Context == Declarator::FileContext
1923 ? diag::err_invalid_token_after_toplevel_declarator
1924 : diag::err_expected_semi_declaration)) {
1925 // Okay, there was no semicolon and one was expected. If we see a
1926 // declaration specifier, just assume it was missing and continue parsing.
1927 // Otherwise things are very confused and we skip to recover.
1928 if (!isDeclarationSpecifier()) {
1929 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1930 TryConsumeToken(tok::semi);
1934 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
1937 /// Parse an optional simple-asm-expr and attributes, and attach them to a
1938 /// declarator. Returns true on an error.
1939 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
1940 // If a simple-asm-expr is present, parse it.
1941 if (Tok.is(tok::kw_asm)) {
1943 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1944 if (AsmLabel.isInvalid()) {
1945 SkipUntil(tok::semi, StopBeforeMatch);
1949 D.setAsmLabel(AsmLabel.get());
1953 MaybeParseGNUAttributes(D);
1957 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
1958 /// declarator'. This method parses the remainder of the declaration
1959 /// (including any attributes or initializer, among other things) and
1960 /// finalizes the declaration.
1962 /// init-declarator: [C99 6.7]
1964 /// declarator '=' initializer
1965 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
1966 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
1967 /// [C++] declarator initializer[opt]
1969 /// [C++] initializer:
1970 /// [C++] '=' initializer-clause
1971 /// [C++] '(' expression-list ')'
1972 /// [C++0x] '=' 'default' [TODO]
1973 /// [C++0x] '=' 'delete'
1974 /// [C++0x] braced-init-list
1976 /// According to the standard grammar, =default and =delete are function
1977 /// definitions, but that definitely doesn't fit with the parser here.
1979 Decl *Parser::ParseDeclarationAfterDeclarator(
1980 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
1981 if (ParseAsmAttributesAfterDeclarator(D))
1984 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
1987 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
1988 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
1989 // Inform the current actions module that we just parsed this declarator.
1990 Decl *ThisDecl = nullptr;
1991 switch (TemplateInfo.Kind) {
1992 case ParsedTemplateInfo::NonTemplate:
1993 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1996 case ParsedTemplateInfo::Template:
1997 case ParsedTemplateInfo::ExplicitSpecialization: {
1998 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
1999 *TemplateInfo.TemplateParams,
2001 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
2002 // Re-direct this decl to refer to the templated decl so that we can
2004 ThisDecl = VT->getTemplatedDecl();
2007 case ParsedTemplateInfo::ExplicitInstantiation: {
2008 if (Tok.is(tok::semi)) {
2009 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2010 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2011 if (ThisRes.isInvalid()) {
2012 SkipUntil(tok::semi, StopBeforeMatch);
2015 ThisDecl = ThisRes.get();
2017 // FIXME: This check should be for a variable template instantiation only.
2019 // Check that this is a valid instantiation
2020 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
2021 // If the declarator-id is not a template-id, issue a diagnostic and
2022 // recover by ignoring the 'template' keyword.
2023 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2024 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2025 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2027 SourceLocation LAngleLoc =
2028 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2029 Diag(D.getIdentifierLoc(),
2030 diag::err_explicit_instantiation_with_definition)
2031 << SourceRange(TemplateInfo.TemplateLoc)
2032 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2034 // Recover as if it were an explicit specialization.
2035 TemplateParameterLists FakedParamLists;
2036 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2037 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
2038 LAngleLoc, nullptr));
2041 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2048 // Parse declarator '=' initializer.
2049 // If a '==' or '+=' is found, suggest a fixit to '='.
2050 if (isTokenEqualOrEqualTypo()) {
2051 SourceLocation EqualLoc = ConsumeToken();
2053 if (Tok.is(tok::kw_delete)) {
2054 if (D.isFunctionDeclarator())
2055 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2058 Diag(ConsumeToken(), diag::err_deleted_non_function);
2059 } else if (Tok.is(tok::kw_default)) {
2060 if (D.isFunctionDeclarator())
2061 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2064 Diag(ConsumeToken(), diag::err_default_special_members);
2066 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2068 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
2071 if (Tok.is(tok::code_completion)) {
2072 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2073 Actions.FinalizeDeclaration(ThisDecl);
2078 ExprResult Init(ParseInitializer());
2080 // If this is the only decl in (possibly) range based for statement,
2081 // our best guess is that the user meant ':' instead of '='.
2082 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2083 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2084 << FixItHint::CreateReplacement(EqualLoc, ":");
2085 // We are trying to stop parser from looking for ';' in this for
2086 // statement, therefore preventing spurious errors to be issued.
2087 FRI->ColonLoc = EqualLoc;
2089 FRI->RangeExpr = Init;
2092 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2093 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2097 if (Init.isInvalid()) {
2098 SmallVector<tok::TokenKind, 2> StopTokens;
2099 StopTokens.push_back(tok::comma);
2100 if (D.getContext() == Declarator::ForContext ||
2101 D.getContext() == Declarator::InitStmtContext)
2102 StopTokens.push_back(tok::r_paren);
2103 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2104 Actions.ActOnInitializerError(ThisDecl);
2106 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2107 /*DirectInit=*/false);
2109 } else if (Tok.is(tok::l_paren)) {
2110 // Parse C++ direct initializer: '(' expression-list ')'
2111 BalancedDelimiterTracker T(*this, tok::l_paren);
2115 CommaLocsTy CommaLocs;
2117 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2119 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
2122 if (ParseExpressionList(Exprs, CommaLocs, [&] {
2123 Actions.CodeCompleteConstructor(getCurScope(),
2124 cast<VarDecl>(ThisDecl)->getType()->getCanonicalTypeInternal(),
2125 ThisDecl->getLocation(), Exprs);
2127 Actions.ActOnInitializerError(ThisDecl);
2128 SkipUntil(tok::r_paren, StopAtSemi);
2130 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2131 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2138 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2139 "Unexpected number of commas!");
2141 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2142 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2146 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2147 T.getCloseLocation(),
2149 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2150 /*DirectInit=*/true);
2152 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2153 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
2154 // Parse C++0x braced-init-list.
2155 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2157 if (D.getCXXScopeSpec().isSet()) {
2159 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
2162 ExprResult Init(ParseBraceInitializer());
2164 if (D.getCXXScopeSpec().isSet()) {
2165 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2169 if (Init.isInvalid()) {
2170 Actions.ActOnInitializerError(ThisDecl);
2172 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2175 Actions.ActOnUninitializedDecl(ThisDecl);
2178 Actions.FinalizeDeclaration(ThisDecl);
2183 /// ParseSpecifierQualifierList
2184 /// specifier-qualifier-list:
2185 /// type-specifier specifier-qualifier-list[opt]
2186 /// type-qualifier specifier-qualifier-list[opt]
2187 /// [GNU] attributes specifier-qualifier-list[opt]
2189 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2190 DeclSpecContext DSC) {
2191 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2192 /// parse declaration-specifiers and complain about extra stuff.
2193 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2194 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2196 // Validate declspec for type-name.
2197 unsigned Specs = DS.getParsedSpecifiers();
2198 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2199 Diag(Tok, diag::err_expected_type);
2200 DS.SetTypeSpecError();
2201 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2202 Diag(Tok, diag::err_typename_requires_specqual);
2203 if (!DS.hasTypeSpecifier())
2204 DS.SetTypeSpecError();
2207 // Issue diagnostic and remove storage class if present.
2208 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2209 if (DS.getStorageClassSpecLoc().isValid())
2210 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2212 Diag(DS.getThreadStorageClassSpecLoc(),
2213 diag::err_typename_invalid_storageclass);
2214 DS.ClearStorageClassSpecs();
2217 // Issue diagnostic and remove function specifier if present.
2218 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2219 if (DS.isInlineSpecified())
2220 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2221 if (DS.isVirtualSpecified())
2222 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2223 if (DS.isExplicitSpecified())
2224 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2225 DS.ClearFunctionSpecs();
2228 // Issue diagnostic and remove constexpr specfier if present.
2229 if (DS.isConstexprSpecified() && DSC != DSC_condition) {
2230 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2231 DS.ClearConstexprSpec();
2235 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2236 /// specified token is valid after the identifier in a declarator which
2237 /// immediately follows the declspec. For example, these things are valid:
2239 /// int x [ 4]; // direct-declarator
2240 /// int x ( int y); // direct-declarator
2241 /// int(int x ) // direct-declarator
2242 /// int x ; // simple-declaration
2243 /// int x = 17; // init-declarator-list
2244 /// int x , y; // init-declarator-list
2245 /// int x __asm__ ("foo"); // init-declarator-list
2246 /// int x : 4; // struct-declarator
2247 /// int x { 5}; // C++'0x unified initializers
2249 /// This is not, because 'x' does not immediately follow the declspec (though
2250 /// ')' happens to be valid anyway).
2253 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2254 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2255 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2259 /// ParseImplicitInt - This method is called when we have an non-typename
2260 /// identifier in a declspec (which normally terminates the decl spec) when
2261 /// the declspec has no type specifier. In this case, the declspec is either
2262 /// malformed or is "implicit int" (in K&R and C89).
2264 /// This method handles diagnosing this prettily and returns false if the
2265 /// declspec is done being processed. If it recovers and thinks there may be
2266 /// other pieces of declspec after it, it returns true.
2268 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2269 const ParsedTemplateInfo &TemplateInfo,
2270 AccessSpecifier AS, DeclSpecContext DSC,
2271 ParsedAttributesWithRange &Attrs) {
2272 assert(Tok.is(tok::identifier) && "should have identifier");
2274 SourceLocation Loc = Tok.getLocation();
2275 // If we see an identifier that is not a type name, we normally would
2276 // parse it as the identifer being declared. However, when a typename
2277 // is typo'd or the definition is not included, this will incorrectly
2278 // parse the typename as the identifier name and fall over misparsing
2279 // later parts of the diagnostic.
2281 // As such, we try to do some look-ahead in cases where this would
2282 // otherwise be an "implicit-int" case to see if this is invalid. For
2283 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2284 // an identifier with implicit int, we'd get a parse error because the
2285 // next token is obviously invalid for a type. Parse these as a case
2286 // with an invalid type specifier.
2287 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2289 // Since we know that this either implicit int (which is rare) or an
2290 // error, do lookahead to try to do better recovery. This never applies
2291 // within a type specifier. Outside of C++, we allow this even if the
2292 // language doesn't "officially" support implicit int -- we support
2293 // implicit int as an extension in C99 and C11.
2294 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2295 isValidAfterIdentifierInDeclarator(NextToken())) {
2296 // If this token is valid for implicit int, e.g. "static x = 4", then
2297 // we just avoid eating the identifier, so it will be parsed as the
2298 // identifier in the declarator.
2302 if (getLangOpts().CPlusPlus &&
2303 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2304 // Don't require a type specifier if we have the 'auto' storage class
2305 // specifier in C++98 -- we'll promote it to a type specifier.
2307 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2311 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2312 getLangOpts().MSVCCompat) {
2313 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2314 // Give Sema a chance to recover if we are in a template with dependent base
2316 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2317 *Tok.getIdentifierInfo(), Tok.getLocation(),
2318 DSC == DSC_template_type_arg)) {
2319 const char *PrevSpec;
2321 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2322 Actions.getASTContext().getPrintingPolicy());
2323 DS.SetRangeEnd(Tok.getLocation());
2329 // Otherwise, if we don't consume this token, we are going to emit an
2330 // error anyway. Try to recover from various common problems. Check
2331 // to see if this was a reference to a tag name without a tag specified.
2332 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2334 // C++ doesn't need this, and isTagName doesn't take SS.
2335 if (SS == nullptr) {
2336 const char *TagName = nullptr, *FixitTagName = nullptr;
2337 tok::TokenKind TagKind = tok::unknown;
2339 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2341 case DeclSpec::TST_enum:
2342 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2343 case DeclSpec::TST_union:
2344 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2345 case DeclSpec::TST_struct:
2346 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2347 case DeclSpec::TST_interface:
2348 TagName="__interface"; FixitTagName = "__interface ";
2349 TagKind=tok::kw___interface;break;
2350 case DeclSpec::TST_class:
2351 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2355 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2356 LookupResult R(Actions, TokenName, SourceLocation(),
2357 Sema::LookupOrdinaryName);
2359 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2360 << TokenName << TagName << getLangOpts().CPlusPlus
2361 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2363 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2364 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2366 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2367 << TokenName << TagName;
2370 // Parse this as a tag as if the missing tag were present.
2371 if (TagKind == tok::kw_enum)
2372 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
2374 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2375 /*EnteringContext*/ false, DSC_normal, Attrs);
2380 // Determine whether this identifier could plausibly be the name of something
2381 // being declared (with a missing type).
2382 if (!isTypeSpecifier(DSC) &&
2383 (!SS || DSC == DSC_top_level || DSC == DSC_class)) {
2384 // Look ahead to the next token to try to figure out what this declaration
2385 // was supposed to be.
2386 switch (NextToken().getKind()) {
2387 case tok::l_paren: {
2388 // static x(4); // 'x' is not a type
2389 // x(int n); // 'x' is not a type
2390 // x (*p)[]; // 'x' is a type
2392 // Since we're in an error case, we can afford to perform a tentative
2393 // parse to determine which case we're in.
2394 TentativeParsingAction PA(*this);
2396 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2399 if (TPR != TPResult::False) {
2400 // The identifier is followed by a parenthesized declarator.
2401 // It's supposed to be a type.
2405 // If we're in a context where we could be declaring a constructor,
2406 // check whether this is a constructor declaration with a bogus name.
2407 if (DSC == DSC_class || (DSC == DSC_top_level && SS)) {
2408 IdentifierInfo *II = Tok.getIdentifierInfo();
2409 if (Actions.isCurrentClassNameTypo(II, SS)) {
2410 Diag(Loc, diag::err_constructor_bad_name)
2411 << Tok.getIdentifierInfo() << II
2412 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2413 Tok.setIdentifierInfo(II);
2424 // This looks like a variable or function declaration. The type is
2425 // probably missing. We're done parsing decl-specifiers.
2427 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2431 // This is probably supposed to be a type. This includes cases like:
2433 // struct S { unsinged : 4; };
2438 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2439 // and attempt to recover.
2441 IdentifierInfo *II = Tok.getIdentifierInfo();
2442 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2443 getLangOpts().CPlusPlus &&
2444 NextToken().is(tok::less));
2446 // The action has suggested that the type T could be used. Set that as
2447 // the type in the declaration specifiers, consume the would-be type
2448 // name token, and we're done.
2449 const char *PrevSpec;
2451 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2452 Actions.getASTContext().getPrintingPolicy());
2453 DS.SetRangeEnd(Tok.getLocation());
2455 // There may be other declaration specifiers after this.
2457 } else if (II != Tok.getIdentifierInfo()) {
2458 // If no type was suggested, the correction is to a keyword
2459 Tok.setKind(II->getTokenID());
2460 // There may be other declaration specifiers after this.
2464 // Otherwise, the action had no suggestion for us. Mark this as an error.
2465 DS.SetTypeSpecError();
2466 DS.SetRangeEnd(Tok.getLocation());
2469 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2470 // avoid rippling error messages on subsequent uses of the same type,
2471 // could be useful if #include was forgotten.
2475 /// \brief Determine the declaration specifier context from the declarator
2478 /// \param Context the declarator context, which is one of the
2479 /// Declarator::TheContext enumerator values.
2480 Parser::DeclSpecContext
2481 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
2482 if (Context == Declarator::MemberContext)
2484 if (Context == Declarator::FileContext)
2485 return DSC_top_level;
2486 if (Context == Declarator::TemplateTypeArgContext)
2487 return DSC_template_type_arg;
2488 if (Context == Declarator::TrailingReturnContext)
2489 return DSC_trailing;
2490 if (Context == Declarator::AliasDeclContext ||
2491 Context == Declarator::AliasTemplateContext)
2492 return DSC_alias_declaration;
2496 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2498 /// FIXME: Simply returns an alignof() expression if the argument is a
2499 /// type. Ideally, the type should be propagated directly into Sema.
2502 /// [C11] constant-expression
2503 /// [C++0x] type-id ...[opt]
2504 /// [C++0x] assignment-expression ...[opt]
2505 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2506 SourceLocation &EllipsisLoc) {
2508 if (isTypeIdInParens()) {
2509 SourceLocation TypeLoc = Tok.getLocation();
2510 ParsedType Ty = ParseTypeName().get();
2511 SourceRange TypeRange(Start, Tok.getLocation());
2512 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2513 Ty.getAsOpaquePtr(), TypeRange);
2515 ER = ParseConstantExpression();
2517 if (getLangOpts().CPlusPlus11)
2518 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2523 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2524 /// attribute to Attrs.
2526 /// alignment-specifier:
2527 /// [C11] '_Alignas' '(' type-id ')'
2528 /// [C11] '_Alignas' '(' constant-expression ')'
2529 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2530 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2531 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2532 SourceLocation *EndLoc) {
2533 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2534 "Not an alignment-specifier!");
2536 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2537 SourceLocation KWLoc = ConsumeToken();
2539 BalancedDelimiterTracker T(*this, tok::l_paren);
2540 if (T.expectAndConsume())
2543 SourceLocation EllipsisLoc;
2544 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2545 if (ArgExpr.isInvalid()) {
2552 *EndLoc = T.getCloseLocation();
2554 ArgsVector ArgExprs;
2555 ArgExprs.push_back(ArgExpr.get());
2556 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2557 AttributeList::AS_Keyword, EllipsisLoc);
2560 /// Determine whether we're looking at something that might be a declarator
2561 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2562 /// diagnose a missing semicolon after a prior tag definition in the decl
2565 /// \return \c true if an error occurred and this can't be any kind of
2568 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2569 DeclSpecContext DSContext,
2570 LateParsedAttrList *LateAttrs) {
2571 assert(DS.hasTagDefinition() && "shouldn't call this");
2573 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2575 if (getLangOpts().CPlusPlus &&
2576 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2577 tok::annot_template_id) &&
2578 TryAnnotateCXXScopeToken(EnteringContext)) {
2579 SkipMalformedDecl();
2583 bool HasScope = Tok.is(tok::annot_cxxscope);
2584 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2585 Token AfterScope = HasScope ? NextToken() : Tok;
2587 // Determine whether the following tokens could possibly be a
2589 bool MightBeDeclarator = true;
2590 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2591 // A declarator-id can't start with 'typename'.
2592 MightBeDeclarator = false;
2593 } else if (AfterScope.is(tok::annot_template_id)) {
2594 // If we have a type expressed as a template-id, this cannot be a
2595 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2596 TemplateIdAnnotation *Annot =
2597 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2598 if (Annot->Kind == TNK_Type_template)
2599 MightBeDeclarator = false;
2600 } else if (AfterScope.is(tok::identifier)) {
2601 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2603 // These tokens cannot come after the declarator-id in a
2604 // simple-declaration, and are likely to come after a type-specifier.
2605 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2606 tok::annot_cxxscope, tok::coloncolon)) {
2607 // Missing a semicolon.
2608 MightBeDeclarator = false;
2609 } else if (HasScope) {
2610 // If the declarator-id has a scope specifier, it must redeclare a
2611 // previously-declared entity. If that's a type (and this is not a
2612 // typedef), that's an error.
2614 Actions.RestoreNestedNameSpecifierAnnotation(
2615 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2616 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2617 Sema::NameClassification Classification = Actions.ClassifyName(
2618 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2619 /*IsAddressOfOperand*/false);
2620 switch (Classification.getKind()) {
2621 case Sema::NC_Error:
2622 SkipMalformedDecl();
2625 case Sema::NC_Keyword:
2626 case Sema::NC_NestedNameSpecifier:
2627 llvm_unreachable("typo correction and nested name specifiers not "
2631 case Sema::NC_TypeTemplate:
2632 // Not a previously-declared non-type entity.
2633 MightBeDeclarator = false;
2636 case Sema::NC_Unknown:
2637 case Sema::NC_Expression:
2638 case Sema::NC_VarTemplate:
2639 case Sema::NC_FunctionTemplate:
2640 // Might be a redeclaration of a prior entity.
2646 if (MightBeDeclarator)
2649 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2650 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()),
2651 diag::err_expected_after)
2652 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2654 // Try to recover from the typo, by dropping the tag definition and parsing
2655 // the problematic tokens as a type.
2657 // FIXME: Split the DeclSpec into pieces for the standalone
2658 // declaration and pieces for the following declaration, instead
2659 // of assuming that all the other pieces attach to new declaration,
2660 // and call ParsedFreeStandingDeclSpec as appropriate.
2661 DS.ClearTypeSpecType();
2662 ParsedTemplateInfo NotATemplate;
2663 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2667 /// ParseDeclarationSpecifiers
2668 /// declaration-specifiers: [C99 6.7]
2669 /// storage-class-specifier declaration-specifiers[opt]
2670 /// type-specifier declaration-specifiers[opt]
2671 /// [C99] function-specifier declaration-specifiers[opt]
2672 /// [C11] alignment-specifier declaration-specifiers[opt]
2673 /// [GNU] attributes declaration-specifiers[opt]
2674 /// [Clang] '__module_private__' declaration-specifiers[opt]
2675 /// [ObjC1] '__kindof' declaration-specifiers[opt]
2677 /// storage-class-specifier: [C99 6.7.1]
2684 /// [C++11] 'thread_local'
2685 /// [C11] '_Thread_local'
2686 /// [GNU] '__thread'
2687 /// function-specifier: [C99 6.7.4]
2690 /// [C++] 'explicit'
2691 /// [OpenCL] '__kernel'
2692 /// 'friend': [C++ dcl.friend]
2693 /// 'constexpr': [C++0x dcl.constexpr]
2694 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2695 const ParsedTemplateInfo &TemplateInfo,
2697 DeclSpecContext DSContext,
2698 LateParsedAttrList *LateAttrs) {
2699 if (DS.getSourceRange().isInvalid()) {
2700 // Start the range at the current token but make the end of the range
2701 // invalid. This will make the entire range invalid unless we successfully
2703 DS.SetRangeStart(Tok.getLocation());
2704 DS.SetRangeEnd(SourceLocation());
2707 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2708 bool AttrsLastTime = false;
2709 ParsedAttributesWithRange attrs(AttrFactory);
2710 // We use Sema's policy to get bool macros right.
2711 PrintingPolicy Policy = Actions.getPrintingPolicy();
2713 bool isInvalid = false;
2714 bool isStorageClass = false;
2715 const char *PrevSpec = nullptr;
2716 unsigned DiagID = 0;
2718 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2719 // implementation for VS2013 uses _Atomic as an identifier for one of the
2720 // classes in <atomic>.
2722 // A typedef declaration containing _Atomic<...> is among the places where
2723 // the class is used. If we are currently parsing such a declaration, treat
2724 // the token as an identifier.
2725 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2726 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
2727 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
2728 Tok.setKind(tok::identifier);
2730 SourceLocation Loc = Tok.getLocation();
2732 switch (Tok.getKind()) {
2736 ProhibitAttributes(attrs);
2738 // Reject C++11 attributes that appertain to decl specifiers as
2739 // we don't support any C++11 attributes that appertain to decl
2740 // specifiers. This also conforms to what g++ 4.8 is doing.
2741 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
2743 DS.takeAttributesFrom(attrs);
2746 // If this is not a declaration specifier token, we're done reading decl
2747 // specifiers. First verify that DeclSpec's are consistent.
2748 DS.Finish(Actions, Policy);
2752 case tok::kw_alignas:
2753 if (!getLangOpts().CPlusPlus11 || !isCXX11AttributeSpecifier())
2754 goto DoneWithDeclSpec;
2756 ProhibitAttributes(attrs);
2757 // FIXME: It would be good to recover by accepting the attributes,
2758 // but attempting to do that now would cause serious
2759 // madness in terms of diagnostics.
2761 attrs.Range = SourceRange();
2763 ParseCXX11Attributes(attrs);
2764 AttrsLastTime = true;
2767 case tok::code_completion: {
2768 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2769 if (DS.hasTypeSpecifier()) {
2770 bool AllowNonIdentifiers
2771 = (getCurScope()->getFlags() & (Scope::ControlScope |
2773 Scope::TemplateParamScope |
2774 Scope::FunctionPrototypeScope |
2775 Scope::AtCatchScope)) == 0;
2776 bool AllowNestedNameSpecifiers
2777 = DSContext == DSC_top_level ||
2778 (DSContext == DSC_class && DS.isFriendSpecified());
2780 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
2781 AllowNonIdentifiers,
2782 AllowNestedNameSpecifiers);
2783 return cutOffParsing();
2786 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
2787 CCC = Sema::PCC_LocalDeclarationSpecifiers;
2788 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
2789 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
2790 : Sema::PCC_Template;
2791 else if (DSContext == DSC_class)
2792 CCC = Sema::PCC_Class;
2793 else if (CurParsedObjCImpl)
2794 CCC = Sema::PCC_ObjCImplementation;
2796 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
2797 return cutOffParsing();
2800 case tok::coloncolon: // ::foo::bar
2801 // C++ scope specifier. Annotate and loop, or bail out on error.
2802 if (TryAnnotateCXXScopeToken(EnteringContext)) {
2803 if (!DS.hasTypeSpecifier())
2804 DS.SetTypeSpecError();
2805 goto DoneWithDeclSpec;
2807 if (Tok.is(tok::coloncolon)) // ::new or ::delete
2808 goto DoneWithDeclSpec;
2811 case tok::annot_cxxscope: {
2812 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
2813 goto DoneWithDeclSpec;
2816 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2817 Tok.getAnnotationRange(),
2820 // We are looking for a qualified typename.
2821 Token Next = NextToken();
2822 if (Next.is(tok::annot_template_id) &&
2823 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
2824 ->Kind == TNK_Type_template) {
2825 // We have a qualified template-id, e.g., N::A<int>
2827 // C++ [class.qual]p2:
2828 // In a lookup in which the constructor is an acceptable lookup
2829 // result and the nested-name-specifier nominates a class C:
2831 // - if the name specified after the
2832 // nested-name-specifier, when looked up in C, is the
2833 // injected-class-name of C (Clause 9), or
2835 // - if the name specified after the nested-name-specifier
2836 // is the same as the identifier or the
2837 // simple-template-id's template-name in the last
2838 // component of the nested-name-specifier,
2840 // the name is instead considered to name the constructor of
2843 // Thus, if the template-name is actually the constructor
2844 // name, then the code is ill-formed; this interpretation is
2845 // reinforced by the NAD status of core issue 635.
2846 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
2847 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2849 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2850 if (isConstructorDeclarator(/*Unqualified*/false)) {
2851 // The user meant this to be an out-of-line constructor
2852 // definition, but template arguments are not allowed
2853 // there. Just allow this as a constructor; we'll
2854 // complain about it later.
2855 goto DoneWithDeclSpec;
2858 // The user meant this to name a type, but it actually names
2859 // a constructor with some extraneous template
2860 // arguments. Complain, then parse it as a type as the user
2862 Diag(TemplateId->TemplateNameLoc,
2863 diag::err_out_of_line_template_id_type_names_constructor)
2864 << TemplateId->Name << 0 /* template name */;
2867 DS.getTypeSpecScope() = SS;
2868 ConsumeToken(); // The C++ scope.
2869 assert(Tok.is(tok::annot_template_id) &&
2870 "ParseOptionalCXXScopeSpecifier not working");
2871 AnnotateTemplateIdTokenAsType();
2875 if (Next.is(tok::annot_typename)) {
2876 DS.getTypeSpecScope() = SS;
2877 ConsumeToken(); // The C++ scope.
2878 if (Tok.getAnnotationValue()) {
2879 ParsedType T = getTypeAnnotation(Tok);
2880 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
2881 Tok.getAnnotationEndLoc(),
2882 PrevSpec, DiagID, T, Policy);
2887 DS.SetTypeSpecError();
2888 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2889 ConsumeToken(); // The typename
2892 if (Next.isNot(tok::identifier))
2893 goto DoneWithDeclSpec;
2895 // If we're in a context where the identifier could be a class name,
2896 // check whether this is a constructor declaration.
2897 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2898 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
2900 if (isConstructorDeclarator(/*Unqualified*/false))
2901 goto DoneWithDeclSpec;
2903 // As noted in C++ [class.qual]p2 (cited above), when the name
2904 // of the class is qualified in a context where it could name
2905 // a constructor, its a constructor name. However, we've
2906 // looked at the declarator, and the user probably meant this
2907 // to be a type. Complain that it isn't supposed to be treated
2908 // as a type, then proceed to parse it as a type.
2909 Diag(Next.getLocation(),
2910 diag::err_out_of_line_template_id_type_names_constructor)
2911 << Next.getIdentifierInfo() << 1 /* type */;
2914 ParsedType TypeRep =
2915 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
2916 getCurScope(), &SS, false, false, nullptr,
2917 /*IsCtorOrDtorName=*/false,
2918 /*NonTrivialSourceInfo=*/true);
2920 // If the referenced identifier is not a type, then this declspec is
2921 // erroneous: We already checked about that it has no type specifier, and
2922 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
2925 ConsumeToken(); // Eat the scope spec so the identifier is current.
2926 ParsedAttributesWithRange Attrs(AttrFactory);
2927 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
2928 if (!Attrs.empty()) {
2929 AttrsLastTime = true;
2930 attrs.takeAllFrom(Attrs);
2934 goto DoneWithDeclSpec;
2937 DS.getTypeSpecScope() = SS;
2938 ConsumeToken(); // The C++ scope.
2940 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2941 DiagID, TypeRep, Policy);
2945 DS.SetRangeEnd(Tok.getLocation());
2946 ConsumeToken(); // The typename.
2951 case tok::annot_typename: {
2952 // If we've previously seen a tag definition, we were almost surely
2953 // missing a semicolon after it.
2954 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
2955 goto DoneWithDeclSpec;
2957 if (Tok.getAnnotationValue()) {
2958 ParsedType T = getTypeAnnotation(Tok);
2959 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2962 DS.SetTypeSpecError();
2967 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2968 ConsumeToken(); // The typename
2973 case tok::kw___is_signed:
2974 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
2975 // typically treats it as a trait. If we see __is_signed as it appears
2976 // in libstdc++, e.g.,
2978 // static const bool __is_signed;
2980 // then treat __is_signed as an identifier rather than as a keyword.
2981 if (DS.getTypeSpecType() == TST_bool &&
2982 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
2983 DS.getStorageClassSpec() == DeclSpec::SCS_static)
2984 TryKeywordIdentFallback(true);
2986 // We're done with the declaration-specifiers.
2987 goto DoneWithDeclSpec;
2990 case tok::kw___super:
2991 case tok::kw_decltype:
2992 case tok::identifier: {
2993 // This identifier can only be a typedef name if we haven't already seen
2994 // a type-specifier. Without this check we misparse:
2995 // typedef int X; struct Y { short X; }; as 'short int'.
2996 if (DS.hasTypeSpecifier())
2997 goto DoneWithDeclSpec;
2999 // In C++, check to see if this is a scope specifier like foo::bar::, if
3000 // so handle it as such. This is important for ctor parsing.
3001 if (getLangOpts().CPlusPlus) {
3002 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3003 DS.SetTypeSpecError();
3004 goto DoneWithDeclSpec;
3006 if (!Tok.is(tok::identifier))
3010 // Check for need to substitute AltiVec keyword tokens.
3011 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3014 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3015 // allow the use of a typedef name as a type specifier.
3016 if (DS.isTypeAltiVecVector())
3017 goto DoneWithDeclSpec;
3019 if (DSContext == DSC_objc_method_result && isObjCInstancetype()) {
3020 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3022 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3023 DiagID, TypeRep, Policy);
3027 DS.SetRangeEnd(Loc);
3032 ParsedType TypeRep =
3033 Actions.getTypeName(*Tok.getIdentifierInfo(),
3034 Tok.getLocation(), getCurScope());
3036 // If this is not a typedef name, don't parse it as part of the declspec,
3037 // it must be an implicit int or an error.
3039 ParsedAttributesWithRange Attrs(AttrFactory);
3040 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3041 if (!Attrs.empty()) {
3042 AttrsLastTime = true;
3043 attrs.takeAllFrom(Attrs);
3047 goto DoneWithDeclSpec;
3050 // If we're in a context where the identifier could be a class name,
3051 // check whether this is a constructor declaration.
3052 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
3053 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3054 isConstructorDeclarator(/*Unqualified*/true))
3055 goto DoneWithDeclSpec;
3057 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3058 DiagID, TypeRep, Policy);
3062 DS.SetRangeEnd(Tok.getLocation());
3063 ConsumeToken(); // The identifier
3065 // Objective-C supports type arguments and protocol references
3066 // following an Objective-C object or object pointer
3067 // type. Handle either one of them.
3068 if (Tok.is(tok::less) && getLangOpts().ObjC1) {
3069 SourceLocation NewEndLoc;
3070 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3071 Loc, TypeRep, /*consumeLastToken=*/true,
3073 if (NewTypeRep.isUsable()) {
3074 DS.UpdateTypeRep(NewTypeRep.get());
3075 DS.SetRangeEnd(NewEndLoc);
3079 // Need to support trailing type qualifiers (e.g. "id<p> const").
3080 // If a type specifier follows, it will be diagnosed elsewhere.
3085 case tok::annot_template_id: {
3086 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3087 if (TemplateId->Kind != TNK_Type_template) {
3088 // This template-id does not refer to a type name, so we're
3089 // done with the type-specifiers.
3090 goto DoneWithDeclSpec;
3093 // If we're in a context where the template-id could be a
3094 // constructor name or specialization, check whether this is a
3095 // constructor declaration.
3096 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
3097 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3098 isConstructorDeclarator(TemplateId->SS.isEmpty()))
3099 goto DoneWithDeclSpec;
3101 // Turn the template-id annotation token into a type annotation
3102 // token, then try again to parse it as a type-specifier.
3103 AnnotateTemplateIdTokenAsType();
3107 // GNU attributes support.
3108 case tok::kw___attribute:
3109 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3112 // Microsoft declspec support.
3113 case tok::kw___declspec:
3114 ParseMicrosoftDeclSpecs(DS.getAttributes());
3117 // Microsoft single token adornments.
3118 case tok::kw___forceinline: {
3119 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3120 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3121 SourceLocation AttrNameLoc = Tok.getLocation();
3122 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3123 nullptr, 0, AttributeList::AS_Keyword);
3127 case tok::kw___unaligned:
3128 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3132 case tok::kw___sptr:
3133 case tok::kw___uptr:
3134 case tok::kw___ptr64:
3135 case tok::kw___ptr32:
3137 case tok::kw___cdecl:
3138 case tok::kw___stdcall:
3139 case tok::kw___fastcall:
3140 case tok::kw___thiscall:
3141 case tok::kw___regcall:
3142 case tok::kw___vectorcall:
3143 ParseMicrosoftTypeAttributes(DS.getAttributes());
3146 // Borland single token adornments.
3147 case tok::kw___pascal:
3148 ParseBorlandTypeAttributes(DS.getAttributes());
3151 // OpenCL single token adornments.
3152 case tok::kw___kernel:
3153 ParseOpenCLKernelAttributes(DS.getAttributes());
3156 // Nullability type specifiers.
3157 case tok::kw__Nonnull:
3158 case tok::kw__Nullable:
3159 case tok::kw__Null_unspecified:
3160 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3163 // Objective-C 'kindof' types.
3164 case tok::kw___kindof:
3165 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3166 nullptr, 0, AttributeList::AS_Keyword);
3167 (void)ConsumeToken();
3170 // storage-class-specifier
3171 case tok::kw_typedef:
3172 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3173 PrevSpec, DiagID, Policy);
3174 isStorageClass = true;
3176 case tok::kw_extern:
3177 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3178 Diag(Tok, diag::ext_thread_before) << "extern";
3179 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3180 PrevSpec, DiagID, Policy);
3181 isStorageClass = true;
3183 case tok::kw___private_extern__:
3184 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3185 Loc, PrevSpec, DiagID, Policy);
3186 isStorageClass = true;
3188 case tok::kw_static:
3189 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3190 Diag(Tok, diag::ext_thread_before) << "static";
3191 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3192 PrevSpec, DiagID, Policy);
3193 isStorageClass = true;
3196 if (getLangOpts().CPlusPlus11) {
3197 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3198 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3199 PrevSpec, DiagID, Policy);
3201 Diag(Tok, diag::ext_auto_storage_class)
3202 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3204 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3207 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3208 PrevSpec, DiagID, Policy);
3209 isStorageClass = true;
3211 case tok::kw___auto_type:
3212 Diag(Tok, diag::ext_auto_type);
3213 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3216 case tok::kw_register:
3217 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3218 PrevSpec, DiagID, Policy);
3219 isStorageClass = true;
3221 case tok::kw_mutable:
3222 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3223 PrevSpec, DiagID, Policy);
3224 isStorageClass = true;
3226 case tok::kw___thread:
3227 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3229 isStorageClass = true;
3231 case tok::kw_thread_local:
3232 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3235 case tok::kw__Thread_local:
3236 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3237 Loc, PrevSpec, DiagID);
3238 isStorageClass = true;
3241 // function-specifier
3242 case tok::kw_inline:
3243 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3245 case tok::kw_virtual:
3246 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3248 case tok::kw_explicit:
3249 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
3251 case tok::kw__Noreturn:
3252 if (!getLangOpts().C11)
3253 Diag(Loc, diag::ext_c11_noreturn);
3254 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3257 // alignment-specifier
3258 case tok::kw__Alignas:
3259 if (!getLangOpts().C11)
3260 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
3261 ParseAlignmentSpecifier(DS.getAttributes());
3265 case tok::kw_friend:
3266 if (DSContext == DSC_class)
3267 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3269 PrevSpec = ""; // not actually used by the diagnostic
3270 DiagID = diag::err_friend_invalid_in_context;
3276 case tok::kw___module_private__:
3277 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3281 case tok::kw_constexpr:
3282 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3286 case tok::kw_concept:
3287 isInvalid = DS.SetConceptSpec(Loc, PrevSpec, DiagID);
3292 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3296 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
3297 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3300 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3303 case tok::kw___int64:
3304 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3307 case tok::kw_signed:
3308 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3311 case tok::kw_unsigned:
3312 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3315 case tok::kw__Complex:
3316 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3319 case tok::kw__Imaginary:
3320 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3324 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3328 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3332 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3335 case tok::kw___int128:
3336 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3340 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3344 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3347 case tok::kw_double:
3348 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3351 case tok::kw___float128:
3352 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3355 case tok::kw_wchar_t:
3356 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3359 case tok::kw_char16_t:
3360 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3363 case tok::kw_char32_t:
3364 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3369 if (Tok.is(tok::kw_bool) &&
3370 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3371 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3372 PrevSpec = ""; // Not used by the diagnostic.
3373 DiagID = diag::err_bool_redeclaration;
3374 // For better error recovery.
3375 Tok.setKind(tok::identifier);
3378 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3382 case tok::kw__Decimal32:
3383 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3386 case tok::kw__Decimal64:
3387 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3390 case tok::kw__Decimal128:
3391 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3394 case tok::kw___vector:
3395 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3397 case tok::kw___pixel:
3398 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3400 case tok::kw___bool:
3401 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3404 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3405 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3406 // support the "pipe" word as identifier.
3407 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3408 goto DoneWithDeclSpec;
3410 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3412 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
3413 case tok::kw_##ImgType##_t: \
3414 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3417 #include "clang/Basic/OpenCLImageTypes.def"
3418 case tok::kw___unknown_anytype:
3419 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3420 PrevSpec, DiagID, Policy);
3425 case tok::kw_struct:
3426 case tok::kw___interface:
3427 case tok::kw_union: {
3428 tok::TokenKind Kind = Tok.getKind();
3431 // These are attributes following class specifiers.
3432 // To produce better diagnostic, we parse them when
3433 // parsing class specifier.
3434 ParsedAttributesWithRange Attributes(AttrFactory);
3435 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3436 EnteringContext, DSContext, Attributes);
3438 // If there are attributes following class specifier,
3439 // take them over and handle them here.
3440 if (!Attributes.empty()) {
3441 AttrsLastTime = true;
3442 attrs.takeAllFrom(Attributes);
3450 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3455 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3458 case tok::kw_volatile:
3459 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3462 case tok::kw_restrict:
3463 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3467 // C++ typename-specifier:
3468 case tok::kw_typename:
3469 if (TryAnnotateTypeOrScopeToken()) {
3470 DS.SetTypeSpecError();
3471 goto DoneWithDeclSpec;
3473 if (!Tok.is(tok::kw_typename))
3477 // GNU typeof support.
3478 case tok::kw_typeof:
3479 ParseTypeofSpecifier(DS);
3482 case tok::annot_decltype:
3483 ParseDecltypeSpecifier(DS);
3486 case tok::annot_pragma_pack:
3490 case tok::annot_pragma_ms_pragma:
3491 HandlePragmaMSPragma();
3494 case tok::annot_pragma_ms_vtordisp:
3495 HandlePragmaMSVtorDisp();
3498 case tok::annot_pragma_ms_pointers_to_members:
3499 HandlePragmaMSPointersToMembers();
3502 case tok::kw___underlying_type:
3503 ParseUnderlyingTypeSpecifier(DS);
3506 case tok::kw__Atomic:
3508 // If the _Atomic keyword is immediately followed by a left parenthesis,
3509 // it is interpreted as a type specifier (with a type name), not as a
3511 if (NextToken().is(tok::l_paren)) {
3512 ParseAtomicSpecifier(DS);
3515 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3519 // OpenCL qualifiers:
3520 case tok::kw___generic:
3521 // generic address space is introduced only in OpenCL v2.0
3522 // see OpenCL C Spec v2.0 s6.5.5
3523 if (Actions.getLangOpts().OpenCLVersion < 200) {
3524 DiagID = diag::err_opencl_unknown_type_specifier;
3525 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3529 case tok::kw___private:
3530 case tok::kw___global:
3531 case tok::kw___local:
3532 case tok::kw___constant:
3533 case tok::kw___read_only:
3534 case tok::kw___write_only:
3535 case tok::kw___read_write:
3536 ParseOpenCLQualifiers(DS.getAttributes());
3540 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3541 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3542 // but we support it.
3543 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
3544 goto DoneWithDeclSpec;
3546 SourceLocation StartLoc = Tok.getLocation();
3547 SourceLocation EndLoc;
3548 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3549 if (Type.isUsable()) {
3550 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3551 PrevSpec, DiagID, Type.get(),
3552 Actions.getASTContext().getPrintingPolicy()))
3553 Diag(StartLoc, DiagID) << PrevSpec;
3555 DS.SetRangeEnd(EndLoc);
3557 DS.SetTypeSpecError();
3560 // Need to support trailing type qualifiers (e.g. "id<p> const").
3561 // If a type specifier follows, it will be diagnosed elsewhere.
3564 // If the specifier wasn't legal, issue a diagnostic.
3566 assert(PrevSpec && "Method did not return previous specifier!");
3569 if (DiagID == diag::ext_duplicate_declspec)
3571 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
3572 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
3573 const int OpenCLVer = getLangOpts().OpenCLVersion;
3574 std::string VerSpec = llvm::to_string(OpenCLVer / 100) +
3576 llvm::to_string((OpenCLVer % 100) / 10);
3577 Diag(Tok, DiagID) << VerSpec << PrevSpec << isStorageClass;
3579 Diag(Tok, DiagID) << PrevSpec;
3582 DS.SetRangeEnd(Tok.getLocation());
3583 if (DiagID != diag::err_bool_redeclaration)
3586 AttrsLastTime = false;
3590 /// ParseStructDeclaration - Parse a struct declaration without the terminating
3593 /// struct-declaration:
3594 /// specifier-qualifier-list struct-declarator-list
3595 /// [GNU] __extension__ struct-declaration
3596 /// [GNU] specifier-qualifier-list
3597 /// struct-declarator-list:
3598 /// struct-declarator
3599 /// struct-declarator-list ',' struct-declarator
3600 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3601 /// struct-declarator:
3603 /// [GNU] declarator attributes[opt]
3604 /// declarator[opt] ':' constant-expression
3605 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3607 void Parser::ParseStructDeclaration(
3608 ParsingDeclSpec &DS,
3609 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
3611 if (Tok.is(tok::kw___extension__)) {
3612 // __extension__ silences extension warnings in the subexpression.
3613 ExtensionRAIIObject O(Diags); // Use RAII to do this.
3615 return ParseStructDeclaration(DS, FieldsCallback);
3618 // Parse the common specifier-qualifiers-list piece.
3619 ParseSpecifierQualifierList(DS);
3621 // If there are no declarators, this is a free-standing declaration
3622 // specifier. Let the actions module cope with it.
3623 if (Tok.is(tok::semi)) {
3624 RecordDecl *AnonRecord = nullptr;
3625 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
3627 assert(!AnonRecord && "Did not expect anonymous struct or union here");
3628 DS.complete(TheDecl);
3632 // Read struct-declarators until we find the semicolon.
3633 bool FirstDeclarator = true;
3634 SourceLocation CommaLoc;
3636 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
3637 DeclaratorInfo.D.setCommaLoc(CommaLoc);
3639 // Attributes are only allowed here on successive declarators.
3640 if (!FirstDeclarator)
3641 MaybeParseGNUAttributes(DeclaratorInfo.D);
3643 /// struct-declarator: declarator
3644 /// struct-declarator: declarator[opt] ':' constant-expression
3645 if (Tok.isNot(tok::colon)) {
3646 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3647 ColonProtectionRAIIObject X(*this);
3648 ParseDeclarator(DeclaratorInfo.D);
3650 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
3652 if (TryConsumeToken(tok::colon)) {
3653 ExprResult Res(ParseConstantExpression());
3654 if (Res.isInvalid())
3655 SkipUntil(tok::semi, StopBeforeMatch);
3657 DeclaratorInfo.BitfieldSize = Res.get();
3660 // If attributes exist after the declarator, parse them.
3661 MaybeParseGNUAttributes(DeclaratorInfo.D);
3663 // We're done with this declarator; invoke the callback.
3664 FieldsCallback(DeclaratorInfo);
3666 // If we don't have a comma, it is either the end of the list (a ';')
3667 // or an error, bail out.
3668 if (!TryConsumeToken(tok::comma, CommaLoc))
3671 FirstDeclarator = false;
3675 /// ParseStructUnionBody
3676 /// struct-contents:
3677 /// struct-declaration-list
3679 /// [GNU] "struct-declaration-list" without terminatoring ';'
3680 /// struct-declaration-list:
3681 /// struct-declaration
3682 /// struct-declaration-list struct-declaration
3683 /// [OBC] '@' 'defs' '(' class-name ')'
3685 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
3686 unsigned TagType, Decl *TagDecl) {
3687 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3688 "parsing struct/union body");
3689 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
3691 BalancedDelimiterTracker T(*this, tok::l_brace);
3692 if (T.consumeOpen())
3695 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
3696 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3698 SmallVector<Decl *, 32> FieldDecls;
3700 // While we still have something to read, read the declarations in the struct.
3701 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3702 Tok.isNot(tok::eof)) {
3703 // Each iteration of this loop reads one struct-declaration.
3705 // Check for extraneous top-level semicolon.
3706 if (Tok.is(tok::semi)) {
3707 ConsumeExtraSemi(InsideStruct, TagType);
3711 // Parse _Static_assert declaration.
3712 if (Tok.is(tok::kw__Static_assert)) {
3713 SourceLocation DeclEnd;
3714 ParseStaticAssertDeclaration(DeclEnd);
3718 if (Tok.is(tok::annot_pragma_pack)) {
3723 if (Tok.is(tok::annot_pragma_align)) {
3724 HandlePragmaAlign();
3728 if (Tok.is(tok::annot_pragma_openmp)) {
3729 // Result can be ignored, because it must be always empty.
3730 AccessSpecifier AS = AS_none;
3731 ParsedAttributesWithRange Attrs(AttrFactory);
3732 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
3736 if (!Tok.is(tok::at)) {
3737 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
3738 // Install the declarator into the current TagDecl.
3740 Actions.ActOnField(getCurScope(), TagDecl,
3741 FD.D.getDeclSpec().getSourceRange().getBegin(),
3742 FD.D, FD.BitfieldSize);
3743 FieldDecls.push_back(Field);
3747 // Parse all the comma separated declarators.
3748 ParsingDeclSpec DS(*this);
3749 ParseStructDeclaration(DS, CFieldCallback);
3750 } else { // Handle @defs
3752 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
3753 Diag(Tok, diag::err_unexpected_at);
3754 SkipUntil(tok::semi);
3758 ExpectAndConsume(tok::l_paren);
3759 if (!Tok.is(tok::identifier)) {
3760 Diag(Tok, diag::err_expected) << tok::identifier;
3761 SkipUntil(tok::semi);
3764 SmallVector<Decl *, 16> Fields;
3765 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
3766 Tok.getIdentifierInfo(), Fields);
3767 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
3769 ExpectAndConsume(tok::r_paren);
3772 if (TryConsumeToken(tok::semi))
3775 if (Tok.is(tok::r_brace)) {
3776 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
3780 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
3781 // Skip to end of block or statement to avoid ext-warning on extra ';'.
3782 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
3783 // If we stopped at a ';', eat it.
3784 TryConsumeToken(tok::semi);
3789 ParsedAttributes attrs(AttrFactory);
3790 // If attributes exist after struct contents, parse them.
3791 MaybeParseGNUAttributes(attrs);
3793 Actions.ActOnFields(getCurScope(),
3794 RecordLoc, TagDecl, FieldDecls,
3795 T.getOpenLocation(), T.getCloseLocation(),
3798 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
3801 /// ParseEnumSpecifier
3802 /// enum-specifier: [C99 6.7.2.2]
3803 /// 'enum' identifier[opt] '{' enumerator-list '}'
3804 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
3805 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
3806 /// '}' attributes[opt]
3807 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
3809 /// 'enum' identifier
3810 /// [GNU] 'enum' attributes[opt] identifier
3812 /// [C++11] enum-head '{' enumerator-list[opt] '}'
3813 /// [C++11] enum-head '{' enumerator-list ',' '}'
3815 /// enum-head: [C++11]
3816 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
3817 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
3818 /// identifier enum-base[opt]
3820 /// enum-key: [C++11]
3825 /// enum-base: [C++11]
3826 /// ':' type-specifier-seq
3828 /// [C++] elaborated-type-specifier:
3829 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
3831 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
3832 const ParsedTemplateInfo &TemplateInfo,
3833 AccessSpecifier AS, DeclSpecContext DSC) {
3834 // Parse the tag portion of this.
3835 if (Tok.is(tok::code_completion)) {
3836 // Code completion for an enum name.
3837 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
3838 return cutOffParsing();
3841 // If attributes exist after tag, parse them.
3842 ParsedAttributesWithRange attrs(AttrFactory);
3843 MaybeParseGNUAttributes(attrs);
3844 MaybeParseCXX11Attributes(attrs);
3845 MaybeParseMicrosoftDeclSpecs(attrs);
3847 SourceLocation ScopedEnumKWLoc;
3848 bool IsScopedUsingClassTag = false;
3850 // In C++11, recognize 'enum class' and 'enum struct'.
3851 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
3852 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
3853 : diag::ext_scoped_enum);
3854 IsScopedUsingClassTag = Tok.is(tok::kw_class);
3855 ScopedEnumKWLoc = ConsumeToken();
3857 // Attributes are not allowed between these keywords. Diagnose,
3858 // but then just treat them like they appeared in the right place.
3859 ProhibitAttributes(attrs);
3861 // They are allowed afterwards, though.
3862 MaybeParseGNUAttributes(attrs);
3863 MaybeParseCXX11Attributes(attrs);
3864 MaybeParseMicrosoftDeclSpecs(attrs);
3867 // C++11 [temp.explicit]p12:
3868 // The usual access controls do not apply to names used to specify
3869 // explicit instantiations.
3870 // We extend this to also cover explicit specializations. Note that
3871 // we don't suppress if this turns out to be an elaborated type
3873 bool shouldDelayDiagsInTag =
3874 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3875 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3876 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
3878 // Enum definitions should not be parsed in a trailing-return-type.
3879 bool AllowDeclaration = DSC != DSC_trailing;
3881 bool AllowFixedUnderlyingType = AllowDeclaration &&
3882 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
3883 getLangOpts().ObjC2);
3885 CXXScopeSpec &SS = DS.getTypeSpecScope();
3886 if (getLangOpts().CPlusPlus) {
3887 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
3888 // if a fixed underlying type is allowed.
3889 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
3892 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
3893 /*EnteringContext=*/true))
3896 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
3897 Diag(Tok, diag::err_expected) << tok::identifier;
3898 if (Tok.isNot(tok::l_brace)) {
3899 // Has no name and is not a definition.
3900 // Skip the rest of this declarator, up until the comma or semicolon.
3901 SkipUntil(tok::comma, StopAtSemi);
3909 // Must have either 'enum name' or 'enum {...}'.
3910 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
3911 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
3912 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
3914 // Skip the rest of this declarator, up until the comma or semicolon.
3915 SkipUntil(tok::comma, StopAtSemi);
3919 // If an identifier is present, consume and remember it.
3920 IdentifierInfo *Name = nullptr;
3921 SourceLocation NameLoc;
3922 if (Tok.is(tok::identifier)) {
3923 Name = Tok.getIdentifierInfo();
3924 NameLoc = ConsumeToken();
3927 if (!Name && ScopedEnumKWLoc.isValid()) {
3928 // C++0x 7.2p2: The optional identifier shall not be omitted in the
3929 // declaration of a scoped enumeration.
3930 Diag(Tok, diag::err_scoped_enum_missing_identifier);
3931 ScopedEnumKWLoc = SourceLocation();
3932 IsScopedUsingClassTag = false;
3935 // Okay, end the suppression area. We'll decide whether to emit the
3936 // diagnostics in a second.
3937 if (shouldDelayDiagsInTag)
3938 diagsFromTag.done();
3940 TypeResult BaseType;
3942 // Parse the fixed underlying type.
3943 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
3944 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
3945 bool PossibleBitfield = false;
3946 if (CanBeBitfield) {
3947 // If we're in class scope, this can either be an enum declaration with
3948 // an underlying type, or a declaration of a bitfield member. We try to
3949 // use a simple disambiguation scheme first to catch the common cases
3950 // (integer literal, sizeof); if it's still ambiguous, we then consider
3951 // anything that's a simple-type-specifier followed by '(' as an
3952 // expression. This suffices because function types are not valid
3953 // underlying types anyway.
3954 EnterExpressionEvaluationContext Unevaluated(Actions,
3955 Sema::ConstantEvaluated);
3956 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
3957 // If the next token starts an expression, we know we're parsing a
3958 // bit-field. This is the common case.
3959 if (TPR == TPResult::True)
3960 PossibleBitfield = true;
3961 // If the next token starts a type-specifier-seq, it may be either a
3962 // a fixed underlying type or the start of a function-style cast in C++;
3963 // lookahead one more token to see if it's obvious that we have a
3964 // fixed underlying type.
3965 else if (TPR == TPResult::False &&
3966 GetLookAheadToken(2).getKind() == tok::semi) {
3970 // We have the start of a type-specifier-seq, so we have to perform
3971 // tentative parsing to determine whether we have an expression or a
3973 TentativeParsingAction TPA(*this);
3978 // If we see a type specifier followed by an open-brace, we have an
3979 // ambiguity between an underlying type and a C++11 braced
3980 // function-style cast. Resolve this by always treating it as an
3982 // FIXME: The standard is not entirely clear on how to disambiguate in
3984 if ((getLangOpts().CPlusPlus &&
3985 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
3986 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
3987 // We'll parse this as a bitfield later.
3988 PossibleBitfield = true;
3991 // We have a type-specifier-seq.
4000 if (!PossibleBitfield) {
4002 BaseType = ParseTypeName(&Range);
4004 if (getLangOpts().CPlusPlus11) {
4005 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4006 } else if (!getLangOpts().ObjC2) {
4007 if (getLangOpts().CPlusPlus)
4008 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
4010 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
4015 // There are four options here. If we have 'friend enum foo;' then this is a
4016 // friend declaration, and cannot have an accompanying definition. If we have
4017 // 'enum foo;', then this is a forward declaration. If we have
4018 // 'enum foo {...' then this is a definition. Otherwise we have something
4019 // like 'enum foo xyz', a reference.
4021 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4022 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4023 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4025 Sema::TagUseKind TUK;
4026 if (!AllowDeclaration) {
4027 TUK = Sema::TUK_Reference;
4028 } else if (Tok.is(tok::l_brace)) {
4029 if (DS.isFriendSpecified()) {
4030 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4031 << SourceRange(DS.getFriendSpecLoc());
4033 SkipUntil(tok::r_brace, StopAtSemi);
4034 TUK = Sema::TUK_Friend;
4036 TUK = Sema::TUK_Definition;
4038 } else if (!isTypeSpecifier(DSC) &&
4039 (Tok.is(tok::semi) ||
4040 (Tok.isAtStartOfLine() &&
4041 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4042 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4043 if (Tok.isNot(tok::semi)) {
4044 // A semicolon was missing after this declaration. Diagnose and recover.
4045 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4047 Tok.setKind(tok::semi);
4050 TUK = Sema::TUK_Reference;
4053 // If this is an elaborated type specifier, and we delayed
4054 // diagnostics before, just merge them into the current pool.
4055 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4056 diagsFromTag.redelay();
4059 MultiTemplateParamsArg TParams;
4060 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4061 TUK != Sema::TUK_Reference) {
4062 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4063 // Skip the rest of this declarator, up until the comma or semicolon.
4064 Diag(Tok, diag::err_enum_template);
4065 SkipUntil(tok::comma, StopAtSemi);
4069 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4070 // Enumerations can't be explicitly instantiated.
4071 DS.SetTypeSpecError();
4072 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4076 assert(TemplateInfo.TemplateParams && "no template parameters");
4077 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4078 TemplateInfo.TemplateParams->size());
4081 if (TUK == Sema::TUK_Reference)
4082 ProhibitAttributes(attrs);
4084 if (!Name && TUK != Sema::TUK_Definition) {
4085 Diag(Tok, diag::err_enumerator_unnamed_no_def);
4087 // Skip the rest of this declarator, up until the comma or semicolon.
4088 SkipUntil(tok::comma, StopAtSemi);
4092 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4094 Sema::SkipBodyInfo SkipBody;
4095 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4096 NextToken().is(tok::identifier))
4097 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4098 NextToken().getIdentifierInfo(),
4099 NextToken().getLocation());
4102 bool IsDependent = false;
4103 const char *PrevSpec = nullptr;
4105 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
4106 StartLoc, SS, Name, NameLoc, attrs.getList(),
4107 AS, DS.getModulePrivateSpecLoc(), TParams,
4108 Owned, IsDependent, ScopedEnumKWLoc,
4109 IsScopedUsingClassTag, BaseType,
4110 DSC == DSC_type_specifier, &SkipBody);
4112 if (SkipBody.ShouldSkip) {
4113 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4115 BalancedDelimiterTracker T(*this, tok::l_brace);
4119 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4120 NameLoc.isValid() ? NameLoc : StartLoc,
4121 PrevSpec, DiagID, TagDecl, Owned,
4122 Actions.getASTContext().getPrintingPolicy()))
4123 Diag(StartLoc, DiagID) << PrevSpec;
4128 // This enum has a dependent nested-name-specifier. Handle it as a
4131 DS.SetTypeSpecError();
4132 Diag(Tok, diag::err_expected_type_name_after_typename);
4136 TypeResult Type = Actions.ActOnDependentTag(
4137 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4138 if (Type.isInvalid()) {
4139 DS.SetTypeSpecError();
4143 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4144 NameLoc.isValid() ? NameLoc : StartLoc,
4145 PrevSpec, DiagID, Type.get(),
4146 Actions.getASTContext().getPrintingPolicy()))
4147 Diag(StartLoc, DiagID) << PrevSpec;
4153 // The action failed to produce an enumeration tag. If this is a
4154 // definition, consume the entire definition.
4155 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4157 SkipUntil(tok::r_brace, StopAtSemi);
4160 DS.SetTypeSpecError();
4164 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference)
4165 ParseEnumBody(StartLoc, TagDecl);
4167 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4168 NameLoc.isValid() ? NameLoc : StartLoc,
4169 PrevSpec, DiagID, TagDecl, Owned,
4170 Actions.getASTContext().getPrintingPolicy()))
4171 Diag(StartLoc, DiagID) << PrevSpec;
4174 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4175 /// enumerator-list:
4177 /// enumerator-list ',' enumerator
4179 /// enumeration-constant attributes[opt]
4180 /// enumeration-constant attributes[opt] '=' constant-expression
4181 /// enumeration-constant:
4184 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4185 // Enter the scope of the enum body and start the definition.
4186 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4187 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4189 BalancedDelimiterTracker T(*this, tok::l_brace);
4192 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4193 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4194 Diag(Tok, diag::err_empty_enum);
4196 SmallVector<Decl *, 32> EnumConstantDecls;
4197 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4199 Decl *LastEnumConstDecl = nullptr;
4201 // Parse the enumerator-list.
4202 while (Tok.isNot(tok::r_brace)) {
4203 // Parse enumerator. If failed, try skipping till the start of the next
4204 // enumerator definition.
4205 if (Tok.isNot(tok::identifier)) {
4206 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4207 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4208 TryConsumeToken(tok::comma))
4212 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4213 SourceLocation IdentLoc = ConsumeToken();
4215 // If attributes exist after the enumerator, parse them.
4216 ParsedAttributesWithRange attrs(AttrFactory);
4217 MaybeParseGNUAttributes(attrs);
4218 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4219 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
4220 if (!getLangOpts().CPlusPlus1z)
4221 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
4222 << 1 /*enumerator*/;
4223 ParseCXX11Attributes(attrs);
4226 SourceLocation EqualLoc;
4227 ExprResult AssignedVal;
4228 EnumAvailabilityDiags.emplace_back(*this);
4230 if (TryConsumeToken(tok::equal, EqualLoc)) {
4231 AssignedVal = ParseConstantExpression();
4232 if (AssignedVal.isInvalid())
4233 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4236 // Install the enumerator constant into EnumDecl.
4237 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
4240 attrs.getList(), EqualLoc,
4242 EnumAvailabilityDiags.back().done();
4244 EnumConstantDecls.push_back(EnumConstDecl);
4245 LastEnumConstDecl = EnumConstDecl;
4247 if (Tok.is(tok::identifier)) {
4248 // We're missing a comma between enumerators.
4249 SourceLocation Loc = getEndOfPreviousToken();
4250 Diag(Loc, diag::err_enumerator_list_missing_comma)
4251 << FixItHint::CreateInsertion(Loc, ", ");
4255 // Emumerator definition must be finished, only comma or r_brace are
4257 SourceLocation CommaLoc;
4258 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4259 if (EqualLoc.isValid())
4260 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4263 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4264 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4265 if (TryConsumeToken(tok::comma, CommaLoc))
4272 // If comma is followed by r_brace, emit appropriate warning.
4273 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4274 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4275 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4276 diag::ext_enumerator_list_comma_cxx :
4277 diag::ext_enumerator_list_comma_c)
4278 << FixItHint::CreateRemoval(CommaLoc);
4279 else if (getLangOpts().CPlusPlus11)
4280 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4281 << FixItHint::CreateRemoval(CommaLoc);
4289 // If attributes exist after the identifier list, parse them.
4290 ParsedAttributes attrs(AttrFactory);
4291 MaybeParseGNUAttributes(attrs);
4293 Actions.ActOnEnumBody(StartLoc, T.getRange(),
4294 EnumDecl, EnumConstantDecls,
4298 // Now handle enum constant availability diagnostics.
4299 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4300 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4301 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4302 EnumAvailabilityDiags[i].redelay();
4303 PD.complete(EnumConstantDecls[i]);
4307 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4309 // The next token must be valid after an enum definition. If not, a ';'
4310 // was probably forgotten.
4311 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4312 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4313 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4314 // Push this token back into the preprocessor and change our current token
4315 // to ';' so that the rest of the code recovers as though there were an
4316 // ';' after the definition.
4318 Tok.setKind(tok::semi);
4322 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4323 /// is definitely a type-specifier. Return false if it isn't part of a type
4324 /// specifier or if we're not sure.
4325 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4326 switch (Tok.getKind()) {
4327 default: return false;
4331 case tok::kw___int64:
4332 case tok::kw___int128:
4333 case tok::kw_signed:
4334 case tok::kw_unsigned:
4335 case tok::kw__Complex:
4336 case tok::kw__Imaginary:
4339 case tok::kw_wchar_t:
4340 case tok::kw_char16_t:
4341 case tok::kw_char32_t:
4345 case tok::kw_double:
4346 case tok::kw___float128:
4349 case tok::kw__Decimal32:
4350 case tok::kw__Decimal64:
4351 case tok::kw__Decimal128:
4352 case tok::kw___vector:
4353 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4354 #include "clang/Basic/OpenCLImageTypes.def"
4356 // struct-or-union-specifier (C99) or class-specifier (C++)
4358 case tok::kw_struct:
4359 case tok::kw___interface:
4365 case tok::annot_typename:
4370 /// isTypeSpecifierQualifier - Return true if the current token could be the
4371 /// start of a specifier-qualifier-list.
4372 bool Parser::isTypeSpecifierQualifier() {
4373 switch (Tok.getKind()) {
4374 default: return false;
4376 case tok::identifier: // foo::bar
4377 if (TryAltiVecVectorToken())
4380 case tok::kw_typename: // typename T::type
4381 // Annotate typenames and C++ scope specifiers. If we get one, just
4382 // recurse to handle whatever we get.
4383 if (TryAnnotateTypeOrScopeToken())
4385 if (Tok.is(tok::identifier))
4387 return isTypeSpecifierQualifier();
4389 case tok::coloncolon: // ::foo::bar
4390 if (NextToken().is(tok::kw_new) || // ::new
4391 NextToken().is(tok::kw_delete)) // ::delete
4394 if (TryAnnotateTypeOrScopeToken())
4396 return isTypeSpecifierQualifier();
4398 // GNU attributes support.
4399 case tok::kw___attribute:
4400 // GNU typeof support.
4401 case tok::kw_typeof:
4406 case tok::kw___int64:
4407 case tok::kw___int128:
4408 case tok::kw_signed:
4409 case tok::kw_unsigned:
4410 case tok::kw__Complex:
4411 case tok::kw__Imaginary:
4414 case tok::kw_wchar_t:
4415 case tok::kw_char16_t:
4416 case tok::kw_char32_t:
4420 case tok::kw_double:
4421 case tok::kw___float128:
4424 case tok::kw__Decimal32:
4425 case tok::kw__Decimal64:
4426 case tok::kw__Decimal128:
4427 case tok::kw___vector:
4428 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4429 #include "clang/Basic/OpenCLImageTypes.def"
4431 // struct-or-union-specifier (C99) or class-specifier (C++)
4433 case tok::kw_struct:
4434 case tok::kw___interface:
4441 case tok::kw_volatile:
4442 case tok::kw_restrict:
4444 // Debugger support.
4445 case tok::kw___unknown_anytype:
4448 case tok::annot_typename:
4451 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4453 return getLangOpts().ObjC1;
4455 case tok::kw___cdecl:
4456 case tok::kw___stdcall:
4457 case tok::kw___fastcall:
4458 case tok::kw___thiscall:
4459 case tok::kw___regcall:
4460 case tok::kw___vectorcall:
4462 case tok::kw___ptr64:
4463 case tok::kw___ptr32:
4464 case tok::kw___pascal:
4465 case tok::kw___unaligned:
4467 case tok::kw__Nonnull:
4468 case tok::kw__Nullable:
4469 case tok::kw__Null_unspecified:
4471 case tok::kw___kindof:
4473 case tok::kw___private:
4474 case tok::kw___local:
4475 case tok::kw___global:
4476 case tok::kw___constant:
4477 case tok::kw___generic:
4478 case tok::kw___read_only:
4479 case tok::kw___read_write:
4480 case tok::kw___write_only:
4485 case tok::kw__Atomic:
4490 /// isDeclarationSpecifier() - Return true if the current token is part of a
4491 /// declaration specifier.
4493 /// \param DisambiguatingWithExpression True to indicate that the purpose of
4494 /// this check is to disambiguate between an expression and a declaration.
4495 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4496 switch (Tok.getKind()) {
4497 default: return false;
4500 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4502 case tok::identifier: // foo::bar
4503 // Unfortunate hack to support "Class.factoryMethod" notation.
4504 if (getLangOpts().ObjC1 && NextToken().is(tok::period))
4506 if (TryAltiVecVectorToken())
4509 case tok::kw_decltype: // decltype(T())::type
4510 case tok::kw_typename: // typename T::type
4511 // Annotate typenames and C++ scope specifiers. If we get one, just
4512 // recurse to handle whatever we get.
4513 if (TryAnnotateTypeOrScopeToken())
4515 if (Tok.is(tok::identifier))
4518 // If we're in Objective-C and we have an Objective-C class type followed
4519 // by an identifier and then either ':' or ']', in a place where an
4520 // expression is permitted, then this is probably a class message send
4521 // missing the initial '['. In this case, we won't consider this to be
4522 // the start of a declaration.
4523 if (DisambiguatingWithExpression &&
4524 isStartOfObjCClassMessageMissingOpenBracket())
4527 return isDeclarationSpecifier();
4529 case tok::coloncolon: // ::foo::bar
4530 if (NextToken().is(tok::kw_new) || // ::new
4531 NextToken().is(tok::kw_delete)) // ::delete
4534 // Annotate typenames and C++ scope specifiers. If we get one, just
4535 // recurse to handle whatever we get.
4536 if (TryAnnotateTypeOrScopeToken())
4538 return isDeclarationSpecifier();
4540 // storage-class-specifier
4541 case tok::kw_typedef:
4542 case tok::kw_extern:
4543 case tok::kw___private_extern__:
4544 case tok::kw_static:
4546 case tok::kw___auto_type:
4547 case tok::kw_register:
4548 case tok::kw___thread:
4549 case tok::kw_thread_local:
4550 case tok::kw__Thread_local:
4553 case tok::kw___module_private__:
4556 case tok::kw___unknown_anytype:
4561 case tok::kw___int64:
4562 case tok::kw___int128:
4563 case tok::kw_signed:
4564 case tok::kw_unsigned:
4565 case tok::kw__Complex:
4566 case tok::kw__Imaginary:
4569 case tok::kw_wchar_t:
4570 case tok::kw_char16_t:
4571 case tok::kw_char32_t:
4576 case tok::kw_double:
4577 case tok::kw___float128:
4580 case tok::kw__Decimal32:
4581 case tok::kw__Decimal64:
4582 case tok::kw__Decimal128:
4583 case tok::kw___vector:
4585 // struct-or-union-specifier (C99) or class-specifier (C++)
4587 case tok::kw_struct:
4589 case tok::kw___interface:
4595 case tok::kw_volatile:
4596 case tok::kw_restrict:
4598 // function-specifier
4599 case tok::kw_inline:
4600 case tok::kw_virtual:
4601 case tok::kw_explicit:
4602 case tok::kw__Noreturn:
4604 // alignment-specifier
4605 case tok::kw__Alignas:
4608 case tok::kw_friend:
4610 // static_assert-declaration
4611 case tok::kw__Static_assert:
4613 // GNU typeof support.
4614 case tok::kw_typeof:
4617 case tok::kw___attribute:
4619 // C++11 decltype and constexpr.
4620 case tok::annot_decltype:
4621 case tok::kw_constexpr:
4623 // C++ Concepts TS - concept
4624 case tok::kw_concept:
4627 case tok::kw__Atomic:
4630 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4632 return getLangOpts().ObjC1;
4635 case tok::annot_typename:
4636 return !DisambiguatingWithExpression ||
4637 !isStartOfObjCClassMessageMissingOpenBracket();
4639 case tok::kw___declspec:
4640 case tok::kw___cdecl:
4641 case tok::kw___stdcall:
4642 case tok::kw___fastcall:
4643 case tok::kw___thiscall:
4644 case tok::kw___regcall:
4645 case tok::kw___vectorcall:
4647 case tok::kw___sptr:
4648 case tok::kw___uptr:
4649 case tok::kw___ptr64:
4650 case tok::kw___ptr32:
4651 case tok::kw___forceinline:
4652 case tok::kw___pascal:
4653 case tok::kw___unaligned:
4655 case tok::kw__Nonnull:
4656 case tok::kw__Nullable:
4657 case tok::kw__Null_unspecified:
4659 case tok::kw___kindof:
4661 case tok::kw___private:
4662 case tok::kw___local:
4663 case tok::kw___global:
4664 case tok::kw___constant:
4665 case tok::kw___generic:
4666 case tok::kw___read_only:
4667 case tok::kw___read_write:
4668 case tok::kw___write_only:
4669 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4670 #include "clang/Basic/OpenCLImageTypes.def"
4676 bool Parser::isConstructorDeclarator(bool IsUnqualified) {
4677 TentativeParsingAction TPA(*this);
4679 // Parse the C++ scope specifier.
4681 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
4682 /*EnteringContext=*/true)) {
4687 // Parse the constructor name.
4688 if (Tok.isOneOf(tok::identifier, tok::annot_template_id)) {
4689 // We already know that we have a constructor name; just consume
4697 // Current class name must be followed by a left parenthesis.
4698 if (Tok.isNot(tok::l_paren)) {
4704 // A right parenthesis, or ellipsis followed by a right parenthesis signals
4705 // that we have a constructor.
4706 if (Tok.is(tok::r_paren) ||
4707 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
4712 // A C++11 attribute here signals that we have a constructor, and is an
4713 // attribute on the first constructor parameter.
4714 if (getLangOpts().CPlusPlus11 &&
4715 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
4716 /*OuterMightBeMessageSend*/ true)) {
4721 // If we need to, enter the specified scope.
4722 DeclaratorScopeObj DeclScopeObj(*this, SS);
4723 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
4724 DeclScopeObj.EnterDeclaratorScope();
4726 // Optionally skip Microsoft attributes.
4727 ParsedAttributes Attrs(AttrFactory);
4728 MaybeParseMicrosoftAttributes(Attrs);
4730 // Check whether the next token(s) are part of a declaration
4731 // specifier, in which case we have the start of a parameter and,
4732 // therefore, we know that this is a constructor.
4733 bool IsConstructor = false;
4734 if (isDeclarationSpecifier())
4735 IsConstructor = true;
4736 else if (Tok.is(tok::identifier) ||
4737 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
4738 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
4739 // This might be a parenthesized member name, but is more likely to
4740 // be a constructor declaration with an invalid argument type. Keep
4742 if (Tok.is(tok::annot_cxxscope))
4746 // If this is not a constructor, we must be parsing a declarator,
4747 // which must have one of the following syntactic forms (see the
4748 // grammar extract at the start of ParseDirectDeclarator):
4749 switch (Tok.getKind()) {
4754 // C(X [ [attribute]]);
4755 case tok::coloncolon:
4758 // Assume this isn't a constructor, rather than assuming it's a
4759 // constructor with an unnamed parameter of an ill-formed type.
4764 if (NextToken().is(tok::colon) || NextToken().is(tok::kw_try)) {
4765 // Assume these were meant to be constructors:
4766 // C(X) : (the name of a bit-field cannot be parenthesized).
4767 // C(X) try (this is otherwise ill-formed).
4768 IsConstructor = true;
4770 if (NextToken().is(tok::semi) || NextToken().is(tok::l_brace)) {
4771 // If we have a constructor name within the class definition,
4772 // assume these were meant to be constructors:
4775 // ... because otherwise we would be declaring a non-static data
4776 // member that is ill-formed because it's of the same type as its
4777 // surrounding class.
4779 // FIXME: We can actually do this whether or not the name is qualified,
4780 // because if it is qualified in this context it must be being used as
4781 // a constructor name. However, we do not implement that rule correctly
4782 // currently, so we're somewhat conservative here.
4783 IsConstructor = IsUnqualified;
4788 IsConstructor = true;
4794 return IsConstructor;
4797 /// ParseTypeQualifierListOpt
4798 /// type-qualifier-list: [C99 6.7.5]
4800 /// [vendor] attributes
4801 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
4802 /// type-qualifier-list type-qualifier
4803 /// [vendor] type-qualifier-list attributes
4804 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
4805 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
4806 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
4807 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
4808 /// AttrRequirements bitmask values.
4809 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, unsigned AttrReqs,
4811 bool IdentifierRequired) {
4812 if (getLangOpts().CPlusPlus11 && (AttrReqs & AR_CXX11AttributesParsed) &&
4813 isCXX11AttributeSpecifier()) {
4814 ParsedAttributesWithRange attrs(AttrFactory);
4815 ParseCXX11Attributes(attrs);
4816 DS.takeAttributesFrom(attrs);
4819 SourceLocation EndLoc;
4822 bool isInvalid = false;
4823 const char *PrevSpec = nullptr;
4824 unsigned DiagID = 0;
4825 SourceLocation Loc = Tok.getLocation();
4827 switch (Tok.getKind()) {
4828 case tok::code_completion:
4829 Actions.CodeCompleteTypeQualifiers(DS);
4830 return cutOffParsing();
4833 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
4836 case tok::kw_volatile:
4837 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4840 case tok::kw_restrict:
4841 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4844 case tok::kw__Atomic:
4846 goto DoneWithTypeQuals;
4847 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4851 // OpenCL qualifiers:
4852 case tok::kw___private:
4853 case tok::kw___global:
4854 case tok::kw___local:
4855 case tok::kw___constant:
4856 case tok::kw___generic:
4857 case tok::kw___read_only:
4858 case tok::kw___write_only:
4859 case tok::kw___read_write:
4860 ParseOpenCLQualifiers(DS.getAttributes());
4863 case tok::kw___unaligned:
4864 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
4867 case tok::kw___uptr:
4868 // GNU libc headers in C mode use '__uptr' as an identifer which conflicts
4869 // with the MS modifier keyword.
4870 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
4871 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
4872 if (TryKeywordIdentFallback(false))
4875 case tok::kw___sptr:
4877 case tok::kw___ptr64:
4878 case tok::kw___ptr32:
4879 case tok::kw___cdecl:
4880 case tok::kw___stdcall:
4881 case tok::kw___fastcall:
4882 case tok::kw___thiscall:
4883 case tok::kw___regcall:
4884 case tok::kw___vectorcall:
4885 if (AttrReqs & AR_DeclspecAttributesParsed) {
4886 ParseMicrosoftTypeAttributes(DS.getAttributes());
4889 goto DoneWithTypeQuals;
4890 case tok::kw___pascal:
4891 if (AttrReqs & AR_VendorAttributesParsed) {
4892 ParseBorlandTypeAttributes(DS.getAttributes());
4895 goto DoneWithTypeQuals;
4897 // Nullability type specifiers.
4898 case tok::kw__Nonnull:
4899 case tok::kw__Nullable:
4900 case tok::kw__Null_unspecified:
4901 ParseNullabilityTypeSpecifiers(DS.getAttributes());
4904 // Objective-C 'kindof' types.
4905 case tok::kw___kindof:
4906 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
4907 nullptr, 0, AttributeList::AS_Keyword);
4908 (void)ConsumeToken();
4911 case tok::kw___attribute:
4912 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
4913 // When GNU attributes are expressly forbidden, diagnose their usage.
4914 Diag(Tok, diag::err_attributes_not_allowed);
4916 // Parse the attributes even if they are rejected to ensure that error
4917 // recovery is graceful.
4918 if (AttrReqs & AR_GNUAttributesParsed ||
4919 AttrReqs & AR_GNUAttributesParsedAndRejected) {
4920 ParseGNUAttributes(DS.getAttributes());
4921 continue; // do *not* consume the next token!
4923 // otherwise, FALL THROUGH!
4926 // If this is not a type-qualifier token, we're done reading type
4927 // qualifiers. First verify that DeclSpec's are consistent.
4928 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
4929 if (EndLoc.isValid())
4930 DS.SetRangeEnd(EndLoc);
4934 // If the specifier combination wasn't legal, issue a diagnostic.
4936 assert(PrevSpec && "Method did not return previous specifier!");
4937 Diag(Tok, DiagID) << PrevSpec;
4939 EndLoc = ConsumeToken();
4943 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
4945 void Parser::ParseDeclarator(Declarator &D) {
4946 /// This implements the 'declarator' production in the C grammar, then checks
4947 /// for well-formedness and issues diagnostics.
4948 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
4951 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
4952 unsigned TheContext) {
4953 if (Kind == tok::star || Kind == tok::caret)
4956 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
4959 if (!Lang.CPlusPlus)
4962 if (Kind == tok::amp)
4965 // We parse rvalue refs in C++03, because otherwise the errors are scary.
4966 // But we must not parse them in conversion-type-ids and new-type-ids, since
4967 // those can be legitimately followed by a && operator.
4968 // (The same thing can in theory happen after a trailing-return-type, but
4969 // since those are a C++11 feature, there is no rejects-valid issue there.)
4970 if (Kind == tok::ampamp)
4971 return Lang.CPlusPlus11 || (TheContext != Declarator::ConversionIdContext &&
4972 TheContext != Declarator::CXXNewContext);
4977 // Indicates whether the given declarator is a pipe declarator.
4978 static bool isPipeDeclerator(const Declarator &D) {
4979 const unsigned NumTypes = D.getNumTypeObjects();
4981 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
4982 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
4988 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
4989 /// is parsed by the function passed to it. Pass null, and the direct-declarator
4990 /// isn't parsed at all, making this function effectively parse the C++
4991 /// ptr-operator production.
4993 /// If the grammar of this construct is extended, matching changes must also be
4994 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
4995 /// isConstructorDeclarator.
4997 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
4998 /// [C] pointer[opt] direct-declarator
4999 /// [C++] direct-declarator
5000 /// [C++] ptr-operator declarator
5002 /// pointer: [C99 6.7.5]
5003 /// '*' type-qualifier-list[opt]
5004 /// '*' type-qualifier-list[opt] pointer
5007 /// '*' cv-qualifier-seq[opt]
5010 /// [GNU] '&' restrict[opt] attributes[opt]
5011 /// [GNU?] '&&' restrict[opt] attributes[opt]
5012 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
5013 void Parser::ParseDeclaratorInternal(Declarator &D,
5014 DirectDeclParseFunction DirectDeclParser) {
5015 if (Diags.hasAllExtensionsSilenced())
5018 // C++ member pointers start with a '::' or a nested-name.
5019 // Member pointers get special handling, since there's no place for the
5020 // scope spec in the generic path below.
5021 if (getLangOpts().CPlusPlus &&
5022 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
5023 (Tok.is(tok::identifier) &&
5024 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
5025 Tok.is(tok::annot_cxxscope))) {
5026 bool EnteringContext = D.getContext() == Declarator::FileContext ||
5027 D.getContext() == Declarator::MemberContext;
5029 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
5031 if (SS.isNotEmpty()) {
5032 if (Tok.isNot(tok::star)) {
5033 // The scope spec really belongs to the direct-declarator.
5034 if (D.mayHaveIdentifier())
5035 D.getCXXScopeSpec() = SS;
5037 AnnotateScopeToken(SS, true);
5039 if (DirectDeclParser)
5040 (this->*DirectDeclParser)(D);
5044 SourceLocation Loc = ConsumeToken();
5046 DeclSpec DS(AttrFactory);
5047 ParseTypeQualifierListOpt(DS);
5048 D.ExtendWithDeclSpec(DS);
5050 // Recurse to parse whatever is left.
5051 ParseDeclaratorInternal(D, DirectDeclParser);
5053 // Sema will have to catch (syntactically invalid) pointers into global
5054 // scope. It has to catch pointers into namespace scope anyway.
5055 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
5058 /* Don't replace range end. */SourceLocation());
5063 tok::TokenKind Kind = Tok.getKind();
5065 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
5066 DeclSpec DS(AttrFactory);
5067 ParseTypeQualifierListOpt(DS);
5070 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
5071 DS.getAttributes(), SourceLocation());
5074 // Not a pointer, C++ reference, or block.
5075 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
5076 if (DirectDeclParser)
5077 (this->*DirectDeclParser)(D);
5081 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5082 // '&&' -> rvalue reference
5083 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
5086 if (Kind == tok::star || Kind == tok::caret) {
5088 DeclSpec DS(AttrFactory);
5090 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5091 // C++11 attributes are allowed.
5092 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
5093 ((D.getContext() != Declarator::CXXNewContext)
5094 ? AR_GNUAttributesParsed
5095 : AR_GNUAttributesParsedAndRejected);
5096 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
5097 D.ExtendWithDeclSpec(DS);
5099 // Recursively parse the declarator.
5100 ParseDeclaratorInternal(D, DirectDeclParser);
5101 if (Kind == tok::star)
5102 // Remember that we parsed a pointer type, and remember the type-quals.
5103 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
5104 DS.getConstSpecLoc(),
5105 DS.getVolatileSpecLoc(),
5106 DS.getRestrictSpecLoc(),
5107 DS.getAtomicSpecLoc(),
5108 DS.getUnalignedSpecLoc()),
5112 // Remember that we parsed a Block type, and remember the type-quals.
5113 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
5119 DeclSpec DS(AttrFactory);
5121 // Complain about rvalue references in C++03, but then go on and build
5123 if (Kind == tok::ampamp)
5124 Diag(Loc, getLangOpts().CPlusPlus11 ?
5125 diag::warn_cxx98_compat_rvalue_reference :
5126 diag::ext_rvalue_reference);
5128 // GNU-style and C++11 attributes are allowed here, as is restrict.
5129 ParseTypeQualifierListOpt(DS);
5130 D.ExtendWithDeclSpec(DS);
5132 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5133 // cv-qualifiers are introduced through the use of a typedef or of a
5134 // template type argument, in which case the cv-qualifiers are ignored.
5135 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5136 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5137 Diag(DS.getConstSpecLoc(),
5138 diag::err_invalid_reference_qualifier_application) << "const";
5139 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5140 Diag(DS.getVolatileSpecLoc(),
5141 diag::err_invalid_reference_qualifier_application) << "volatile";
5142 // 'restrict' is permitted as an extension.
5143 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5144 Diag(DS.getAtomicSpecLoc(),
5145 diag::err_invalid_reference_qualifier_application) << "_Atomic";
5148 // Recursively parse the declarator.
5149 ParseDeclaratorInternal(D, DirectDeclParser);
5151 if (D.getNumTypeObjects() > 0) {
5152 // C++ [dcl.ref]p4: There shall be no references to references.
5153 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5154 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5155 if (const IdentifierInfo *II = D.getIdentifier())
5156 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5159 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5162 // Once we've complained about the reference-to-reference, we
5163 // can go ahead and build the (technically ill-formed)
5164 // declarator: reference collapsing will take care of it.
5168 // Remember that we parsed a reference type.
5169 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
5176 // When correcting from misplaced brackets before the identifier, the location
5177 // is saved inside the declarator so that other diagnostic messages can use
5178 // them. This extracts and returns that location, or returns the provided
5179 // location if a stored location does not exist.
5180 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5181 SourceLocation Loc) {
5182 if (D.getName().StartLocation.isInvalid() &&
5183 D.getName().EndLocation.isValid())
5184 return D.getName().EndLocation;
5189 /// ParseDirectDeclarator
5190 /// direct-declarator: [C99 6.7.5]
5191 /// [C99] identifier
5192 /// '(' declarator ')'
5193 /// [GNU] '(' attributes declarator ')'
5194 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5195 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5196 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5197 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5198 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5199 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5200 /// attribute-specifier-seq[opt]
5201 /// direct-declarator '(' parameter-type-list ')'
5202 /// direct-declarator '(' identifier-list[opt] ')'
5203 /// [GNU] direct-declarator '(' parameter-forward-declarations
5204 /// parameter-type-list[opt] ')'
5205 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
5206 /// cv-qualifier-seq[opt] exception-specification[opt]
5207 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5208 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5209 /// ref-qualifier[opt] exception-specification[opt]
5210 /// [C++] declarator-id
5211 /// [C++11] declarator-id attribute-specifier-seq[opt]
5213 /// declarator-id: [C++ 8]
5214 /// '...'[opt] id-expression
5215 /// '::'[opt] nested-name-specifier[opt] type-name
5217 /// id-expression: [C++ 5.1]
5221 /// unqualified-id: [C++ 5.1]
5223 /// operator-function-id
5224 /// conversion-function-id
5228 /// C++17 adds the following, which we also handle here:
5230 /// simple-declaration:
5231 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5233 /// Note, any additional constructs added here may need corresponding changes
5234 /// in isConstructorDeclarator.
5235 void Parser::ParseDirectDeclarator(Declarator &D) {
5236 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
5238 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
5239 // This might be a C++17 structured binding.
5240 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5241 D.getCXXScopeSpec().isEmpty())
5242 return ParseDecompositionDeclarator(D);
5244 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5245 // this context it is a bitfield. Also in range-based for statement colon
5246 // may delimit for-range-declaration.
5247 ColonProtectionRAIIObject X(*this,
5248 D.getContext() == Declarator::MemberContext ||
5249 (D.getContext() == Declarator::ForContext &&
5250 getLangOpts().CPlusPlus11));
5252 // ParseDeclaratorInternal might already have parsed the scope.
5253 if (D.getCXXScopeSpec().isEmpty()) {
5254 bool EnteringContext = D.getContext() == Declarator::FileContext ||
5255 D.getContext() == Declarator::MemberContext;
5256 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
5260 if (D.getCXXScopeSpec().isValid()) {
5261 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5262 D.getCXXScopeSpec()))
5263 // Change the declaration context for name lookup, until this function
5264 // is exited (and the declarator has been parsed).
5265 DeclScopeObj.EnterDeclaratorScope();
5266 else if (getObjCDeclContext()) {
5267 // Ensure that we don't interpret the next token as an identifier when
5268 // dealing with declarations in an Objective-C container.
5269 D.SetIdentifier(nullptr, Tok.getLocation());
5270 D.setInvalidType(true);
5272 goto PastIdentifier;
5276 // C++0x [dcl.fct]p14:
5277 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5278 // parameter-declaration-clause without a preceding comma. In this case,
5279 // the ellipsis is parsed as part of the abstract-declarator if the type
5280 // of the parameter either names a template parameter pack that has not
5281 // been expanded or contains auto; otherwise, it is parsed as part of the
5282 // parameter-declaration-clause.
5283 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
5284 !((D.getContext() == Declarator::PrototypeContext ||
5285 D.getContext() == Declarator::LambdaExprParameterContext ||
5286 D.getContext() == Declarator::BlockLiteralContext) &&
5287 NextToken().is(tok::r_paren) &&
5288 !D.hasGroupingParens() &&
5289 !Actions.containsUnexpandedParameterPacks(D) &&
5290 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
5291 SourceLocation EllipsisLoc = ConsumeToken();
5292 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
5293 // The ellipsis was put in the wrong place. Recover, and explain to
5294 // the user what they should have done.
5296 if (EllipsisLoc.isValid())
5297 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5300 D.setEllipsisLoc(EllipsisLoc);
5302 // The ellipsis can't be followed by a parenthesized declarator. We
5303 // check for that in ParseParenDeclarator, after we have disambiguated
5304 // the l_paren token.
5307 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5309 // We found something that indicates the start of an unqualified-id.
5310 // Parse that unqualified-id.
5311 bool AllowConstructorName;
5312 if (D.getDeclSpec().hasTypeSpecifier())
5313 AllowConstructorName = false;
5314 else if (D.getCXXScopeSpec().isSet())
5315 AllowConstructorName =
5316 (D.getContext() == Declarator::FileContext ||
5317 D.getContext() == Declarator::MemberContext);
5319 AllowConstructorName = (D.getContext() == Declarator::MemberContext);
5321 SourceLocation TemplateKWLoc;
5322 bool HadScope = D.getCXXScopeSpec().isValid();
5323 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5324 /*EnteringContext=*/true,
5325 /*AllowDestructorName=*/true, AllowConstructorName,
5326 nullptr, TemplateKWLoc, D.getName()) ||
5327 // Once we're past the identifier, if the scope was bad, mark the
5328 // whole declarator bad.
5329 D.getCXXScopeSpec().isInvalid()) {
5330 D.SetIdentifier(nullptr, Tok.getLocation());
5331 D.setInvalidType(true);
5333 // ParseUnqualifiedId might have parsed a scope specifier during error
5334 // recovery. If it did so, enter that scope.
5335 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5336 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5337 D.getCXXScopeSpec()))
5338 DeclScopeObj.EnterDeclaratorScope();
5340 // Parsed the unqualified-id; update range information and move along.
5341 if (D.getSourceRange().getBegin().isInvalid())
5342 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5343 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
5345 goto PastIdentifier;
5348 if (D.getCXXScopeSpec().isNotEmpty()) {
5349 // We have a scope specifier but no following unqualified-id.
5350 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5351 diag::err_expected_unqualified_id)
5353 D.SetIdentifier(nullptr, Tok.getLocation());
5354 goto PastIdentifier;
5356 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
5357 assert(!getLangOpts().CPlusPlus &&
5358 "There's a C++-specific check for tok::identifier above");
5359 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5360 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5361 D.SetRangeEnd(Tok.getLocation());
5363 goto PastIdentifier;
5364 } else if (Tok.is(tok::identifier) && D.diagnoseIdentifier()) {
5365 // A virt-specifier isn't treated as an identifier if it appears after a
5366 // trailing-return-type.
5367 if (D.getContext() != Declarator::TrailingReturnContext ||
5368 !isCXX11VirtSpecifier(Tok)) {
5369 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5370 << FixItHint::CreateRemoval(Tok.getLocation());
5371 D.SetIdentifier(nullptr, Tok.getLocation());
5373 goto PastIdentifier;
5377 if (Tok.is(tok::l_paren)) {
5378 // direct-declarator: '(' declarator ')'
5379 // direct-declarator: '(' attributes declarator ')'
5380 // Example: 'char (*X)' or 'int (*XX)(void)'
5381 ParseParenDeclarator(D);
5383 // If the declarator was parenthesized, we entered the declarator
5384 // scope when parsing the parenthesized declarator, then exited
5385 // the scope already. Re-enter the scope, if we need to.
5386 if (D.getCXXScopeSpec().isSet()) {
5387 // If there was an error parsing parenthesized declarator, declarator
5388 // scope may have been entered before. Don't do it again.
5389 if (!D.isInvalidType() &&
5390 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5391 D.getCXXScopeSpec()))
5392 // Change the declaration context for name lookup, until this function
5393 // is exited (and the declarator has been parsed).
5394 DeclScopeObj.EnterDeclaratorScope();
5396 } else if (D.mayOmitIdentifier()) {
5397 // This could be something simple like "int" (in which case the declarator
5398 // portion is empty), if an abstract-declarator is allowed.
5399 D.SetIdentifier(nullptr, Tok.getLocation());
5401 // The grammar for abstract-pack-declarator does not allow grouping parens.
5402 // FIXME: Revisit this once core issue 1488 is resolved.
5403 if (D.hasEllipsis() && D.hasGroupingParens())
5404 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5405 diag::ext_abstract_pack_declarator_parens);
5407 if (Tok.getKind() == tok::annot_pragma_parser_crash)
5409 if (Tok.is(tok::l_square))
5410 return ParseMisplacedBracketDeclarator(D);
5411 if (D.getContext() == Declarator::MemberContext) {
5412 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5413 diag::err_expected_member_name_or_semi)
5414 << (D.getDeclSpec().isEmpty() ? SourceRange()
5415 : D.getDeclSpec().getSourceRange());
5416 } else if (getLangOpts().CPlusPlus) {
5417 if (Tok.isOneOf(tok::period, tok::arrow))
5418 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
5420 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5421 if (Tok.isAtStartOfLine() && Loc.isValid())
5422 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5423 << getLangOpts().CPlusPlus;
5425 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5426 diag::err_expected_unqualified_id)
5427 << getLangOpts().CPlusPlus;
5430 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5431 diag::err_expected_either)
5432 << tok::identifier << tok::l_paren;
5434 D.SetIdentifier(nullptr, Tok.getLocation());
5435 D.setInvalidType(true);
5439 assert(D.isPastIdentifier() &&
5440 "Haven't past the location of the identifier yet?");
5442 // Don't parse attributes unless we have parsed an unparenthesized name.
5443 if (D.hasName() && !D.getNumTypeObjects())
5444 MaybeParseCXX11Attributes(D);
5447 if (Tok.is(tok::l_paren)) {
5448 // Enter function-declaration scope, limiting any declarators to the
5449 // function prototype scope, including parameter declarators.
5450 ParseScope PrototypeScope(this,
5451 Scope::FunctionPrototypeScope|Scope::DeclScope|
5452 (D.isFunctionDeclaratorAFunctionDeclaration()
5453 ? Scope::FunctionDeclarationScope : 0));
5455 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5456 // In such a case, check if we actually have a function declarator; if it
5457 // is not, the declarator has been fully parsed.
5458 bool IsAmbiguous = false;
5459 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5460 // The name of the declarator, if any, is tentatively declared within
5461 // a possible direct initializer.
5462 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5463 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5464 TentativelyDeclaredIdentifiers.pop_back();
5465 if (!IsFunctionDecl)
5468 ParsedAttributes attrs(AttrFactory);
5469 BalancedDelimiterTracker T(*this, tok::l_paren);
5471 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
5472 PrototypeScope.Exit();
5473 } else if (Tok.is(tok::l_square)) {
5474 ParseBracketDeclarator(D);
5481 void Parser::ParseDecompositionDeclarator(Declarator &D) {
5482 assert(Tok.is(tok::l_square));
5484 // If this doesn't look like a structured binding, maybe it's a misplaced
5485 // array declarator.
5486 // FIXME: Consume the l_square first so we don't need extra lookahead for
5488 if (!(NextToken().is(tok::identifier) &&
5489 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5490 !(NextToken().is(tok::r_square) &&
5491 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5492 return ParseMisplacedBracketDeclarator(D);
5494 BalancedDelimiterTracker T(*this, tok::l_square);
5497 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5498 while (Tok.isNot(tok::r_square)) {
5499 if (!Bindings.empty()) {
5500 if (Tok.is(tok::comma))
5503 if (Tok.is(tok::identifier)) {
5504 SourceLocation EndLoc = getEndOfPreviousToken();
5505 Diag(EndLoc, diag::err_expected)
5506 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
5508 Diag(Tok, diag::err_expected_comma_or_rsquare);
5511 SkipUntil(tok::r_square, tok::comma, tok::identifier,
5512 StopAtSemi | StopBeforeMatch);
5513 if (Tok.is(tok::comma))
5515 else if (Tok.isNot(tok::identifier))
5520 if (Tok.isNot(tok::identifier)) {
5521 Diag(Tok, diag::err_expected) << tok::identifier;
5525 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
5529 if (Tok.isNot(tok::r_square))
5530 // We've already diagnosed a problem here.
5533 // C++17 does not allow the identifier-list in a structured binding
5535 if (Bindings.empty())
5536 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
5541 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
5542 T.getCloseLocation());
5545 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
5546 /// only called before the identifier, so these are most likely just grouping
5547 /// parens for precedence. If we find that these are actually function
5548 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5550 /// direct-declarator:
5551 /// '(' declarator ')'
5552 /// [GNU] '(' attributes declarator ')'
5553 /// direct-declarator '(' parameter-type-list ')'
5554 /// direct-declarator '(' identifier-list[opt] ')'
5555 /// [GNU] direct-declarator '(' parameter-forward-declarations
5556 /// parameter-type-list[opt] ')'
5558 void Parser::ParseParenDeclarator(Declarator &D) {
5559 BalancedDelimiterTracker T(*this, tok::l_paren);
5562 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
5564 // Eat any attributes before we look at whether this is a grouping or function
5565 // declarator paren. If this is a grouping paren, the attribute applies to
5566 // the type being built up, for example:
5567 // int (__attribute__(()) *x)(long y)
5568 // If this ends up not being a grouping paren, the attribute applies to the
5569 // first argument, for example:
5570 // int (__attribute__(()) int x)
5571 // In either case, we need to eat any attributes to be able to determine what
5572 // sort of paren this is.
5574 ParsedAttributes attrs(AttrFactory);
5575 bool RequiresArg = false;
5576 if (Tok.is(tok::kw___attribute)) {
5577 ParseGNUAttributes(attrs);
5579 // We require that the argument list (if this is a non-grouping paren) be
5580 // present even if the attribute list was empty.
5584 // Eat any Microsoft extensions.
5585 ParseMicrosoftTypeAttributes(attrs);
5587 // Eat any Borland extensions.
5588 if (Tok.is(tok::kw___pascal))
5589 ParseBorlandTypeAttributes(attrs);
5591 // If we haven't past the identifier yet (or where the identifier would be
5592 // stored, if this is an abstract declarator), then this is probably just
5593 // grouping parens. However, if this could be an abstract-declarator, then
5594 // this could also be the start of function arguments (consider 'void()').
5597 if (!D.mayOmitIdentifier()) {
5598 // If this can't be an abstract-declarator, this *must* be a grouping
5599 // paren, because we haven't seen the identifier yet.
5601 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
5602 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
5603 NextToken().is(tok::r_paren)) || // C++ int(...)
5604 isDeclarationSpecifier() || // 'int(int)' is a function.
5605 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
5606 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
5607 // considered to be a type, not a K&R identifier-list.
5610 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
5614 // If this is a grouping paren, handle:
5615 // direct-declarator: '(' declarator ')'
5616 // direct-declarator: '(' attributes declarator ')'
5618 SourceLocation EllipsisLoc = D.getEllipsisLoc();
5619 D.setEllipsisLoc(SourceLocation());
5621 bool hadGroupingParens = D.hasGroupingParens();
5622 D.setGroupingParens(true);
5623 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5626 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
5627 T.getCloseLocation()),
5628 attrs, T.getCloseLocation());
5630 D.setGroupingParens(hadGroupingParens);
5632 // An ellipsis cannot be placed outside parentheses.
5633 if (EllipsisLoc.isValid())
5634 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5639 // Okay, if this wasn't a grouping paren, it must be the start of a function
5640 // argument list. Recognize that this declarator will never have an
5641 // identifier (and remember where it would have been), then call into
5642 // ParseFunctionDeclarator to handle of argument list.
5643 D.SetIdentifier(nullptr, Tok.getLocation());
5645 // Enter function-declaration scope, limiting any declarators to the
5646 // function prototype scope, including parameter declarators.
5647 ParseScope PrototypeScope(this,
5648 Scope::FunctionPrototypeScope | Scope::DeclScope |
5649 (D.isFunctionDeclaratorAFunctionDeclaration()
5650 ? Scope::FunctionDeclarationScope : 0));
5651 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
5652 PrototypeScope.Exit();
5655 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
5656 /// declarator D up to a paren, which indicates that we are parsing function
5659 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
5660 /// immediately after the open paren - they should be considered to be the
5661 /// first argument of a parameter.
5663 /// If RequiresArg is true, then the first argument of the function is required
5664 /// to be present and required to not be an identifier list.
5666 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
5667 /// (C++11) ref-qualifier[opt], exception-specification[opt],
5668 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
5670 /// [C++11] exception-specification:
5671 /// dynamic-exception-specification
5672 /// noexcept-specification
5674 void Parser::ParseFunctionDeclarator(Declarator &D,
5675 ParsedAttributes &FirstArgAttrs,
5676 BalancedDelimiterTracker &Tracker,
5679 assert(getCurScope()->isFunctionPrototypeScope() &&
5680 "Should call from a Function scope");
5681 // lparen is already consumed!
5682 assert(D.isPastIdentifier() && "Should not call before identifier!");
5684 // This should be true when the function has typed arguments.
5685 // Otherwise, it is treated as a K&R-style function.
5686 bool HasProto = false;
5687 // Build up an array of information about the parsed arguments.
5688 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
5689 // Remember where we see an ellipsis, if any.
5690 SourceLocation EllipsisLoc;
5692 DeclSpec DS(AttrFactory);
5693 bool RefQualifierIsLValueRef = true;
5694 SourceLocation RefQualifierLoc;
5695 SourceLocation ConstQualifierLoc;
5696 SourceLocation VolatileQualifierLoc;
5697 SourceLocation RestrictQualifierLoc;
5698 ExceptionSpecificationType ESpecType = EST_None;
5699 SourceRange ESpecRange;
5700 SmallVector<ParsedType, 2> DynamicExceptions;
5701 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5702 ExprResult NoexceptExpr;
5703 CachedTokens *ExceptionSpecTokens = nullptr;
5704 ParsedAttributes FnAttrs(AttrFactory);
5705 TypeResult TrailingReturnType;
5707 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
5708 EndLoc is the end location for the function declarator.
5709 They differ for trailing return types. */
5710 SourceLocation StartLoc, LocalEndLoc, EndLoc;
5711 SourceLocation LParenLoc, RParenLoc;
5712 LParenLoc = Tracker.getOpenLocation();
5713 StartLoc = LParenLoc;
5715 if (isFunctionDeclaratorIdentifierList()) {
5717 Diag(Tok, diag::err_argument_required_after_attribute);
5719 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
5721 Tracker.consumeClose();
5722 RParenLoc = Tracker.getCloseLocation();
5723 LocalEndLoc = RParenLoc;
5726 if (Tok.isNot(tok::r_paren))
5727 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
5729 else if (RequiresArg)
5730 Diag(Tok, diag::err_argument_required_after_attribute);
5732 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
5734 // If we have the closing ')', eat it.
5735 Tracker.consumeClose();
5736 RParenLoc = Tracker.getCloseLocation();
5737 LocalEndLoc = RParenLoc;
5740 if (getLangOpts().CPlusPlus) {
5741 // FIXME: Accept these components in any order, and produce fixits to
5742 // correct the order if the user gets it wrong. Ideally we should deal
5743 // with the pure-specifier in the same way.
5745 // Parse cv-qualifier-seq[opt].
5746 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
5747 /*AtomicAllowed*/ false);
5748 if (!DS.getSourceRange().getEnd().isInvalid()) {
5749 EndLoc = DS.getSourceRange().getEnd();
5750 ConstQualifierLoc = DS.getConstSpecLoc();
5751 VolatileQualifierLoc = DS.getVolatileSpecLoc();
5752 RestrictQualifierLoc = DS.getRestrictSpecLoc();
5755 // Parse ref-qualifier[opt].
5756 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
5757 EndLoc = RefQualifierLoc;
5759 // C++11 [expr.prim.general]p3:
5760 // If a declaration declares a member function or member function
5761 // template of a class X, the expression this is a prvalue of type
5762 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5763 // and the end of the function-definition, member-declarator, or
5765 // FIXME: currently, "static" case isn't handled correctly.
5766 bool IsCXX11MemberFunction =
5767 getLangOpts().CPlusPlus11 &&
5768 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5769 (D.getContext() == Declarator::MemberContext
5770 ? !D.getDeclSpec().isFriendSpecified()
5771 : D.getContext() == Declarator::FileContext &&
5772 D.getCXXScopeSpec().isValid() &&
5773 Actions.CurContext->isRecord());
5774 Sema::CXXThisScopeRAII ThisScope(Actions,
5775 dyn_cast<CXXRecordDecl>(Actions.CurContext),
5776 DS.getTypeQualifiers() |
5777 (D.getDeclSpec().isConstexprSpecified() &&
5778 !getLangOpts().CPlusPlus14
5779 ? Qualifiers::Const : 0),
5780 IsCXX11MemberFunction);
5782 // Parse exception-specification[opt].
5783 bool Delayed = D.isFirstDeclarationOfMember() &&
5784 D.isFunctionDeclaratorAFunctionDeclaration();
5785 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
5786 GetLookAheadToken(0).is(tok::kw_noexcept) &&
5787 GetLookAheadToken(1).is(tok::l_paren) &&
5788 GetLookAheadToken(2).is(tok::kw_noexcept) &&
5789 GetLookAheadToken(3).is(tok::l_paren) &&
5790 GetLookAheadToken(4).is(tok::identifier) &&
5791 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
5792 // HACK: We've got an exception-specification
5793 // noexcept(noexcept(swap(...)))
5795 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
5796 // on a 'swap' member function. This is a libstdc++ bug; the lookup
5797 // for 'swap' will only find the function we're currently declaring,
5798 // whereas it expects to find a non-member swap through ADL. Turn off
5799 // delayed parsing to give it a chance to find what it expects.
5802 ESpecType = tryParseExceptionSpecification(Delayed,
5805 DynamicExceptionRanges,
5807 ExceptionSpecTokens);
5808 if (ESpecType != EST_None)
5809 EndLoc = ESpecRange.getEnd();
5811 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
5812 // after the exception-specification.
5813 MaybeParseCXX11Attributes(FnAttrs);
5815 // Parse trailing-return-type[opt].
5816 LocalEndLoc = EndLoc;
5817 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
5818 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
5819 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
5820 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5821 LocalEndLoc = Tok.getLocation();
5823 TrailingReturnType = ParseTrailingReturnType(Range);
5824 EndLoc = Range.getEnd();
5829 // Collect non-parameter declarations from the prototype if this is a function
5830 // declaration. They will be moved into the scope of the function. Only do
5831 // this in C and not C++, where the decls will continue to live in the
5832 // surrounding context.
5833 SmallVector<NamedDecl *, 0> DeclsInPrototype;
5834 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
5835 !getLangOpts().CPlusPlus) {
5836 for (Decl *D : getCurScope()->decls()) {
5837 NamedDecl *ND = dyn_cast<NamedDecl>(D);
5838 if (!ND || isa<ParmVarDecl>(ND))
5840 DeclsInPrototype.push_back(ND);
5844 // Remember that we parsed a function type, and remember the attributes.
5845 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
5848 ParamInfo.data(), ParamInfo.size(),
5849 EllipsisLoc, RParenLoc,
5850 DS.getTypeQualifiers(),
5851 RefQualifierIsLValueRef,
5852 RefQualifierLoc, ConstQualifierLoc,
5853 VolatileQualifierLoc,
5854 RestrictQualifierLoc,
5855 /*MutableLoc=*/SourceLocation(),
5856 ESpecType, ESpecRange,
5857 DynamicExceptions.data(),
5858 DynamicExceptionRanges.data(),
5859 DynamicExceptions.size(),
5860 NoexceptExpr.isUsable() ?
5861 NoexceptExpr.get() : nullptr,
5862 ExceptionSpecTokens,
5864 StartLoc, LocalEndLoc, D,
5865 TrailingReturnType),
5869 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
5870 /// true if a ref-qualifier is found.
5871 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
5872 SourceLocation &RefQualifierLoc) {
5873 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
5874 Diag(Tok, getLangOpts().CPlusPlus11 ?
5875 diag::warn_cxx98_compat_ref_qualifier :
5876 diag::ext_ref_qualifier);
5878 RefQualifierIsLValueRef = Tok.is(tok::amp);
5879 RefQualifierLoc = ConsumeToken();
5885 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
5886 /// identifier list form for a K&R-style function: void foo(a,b,c)
5888 /// Note that identifier-lists are only allowed for normal declarators, not for
5889 /// abstract-declarators.
5890 bool Parser::isFunctionDeclaratorIdentifierList() {
5891 return !getLangOpts().CPlusPlus
5892 && Tok.is(tok::identifier)
5893 && !TryAltiVecVectorToken()
5894 // K&R identifier lists can't have typedefs as identifiers, per C99
5896 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
5897 // Identifier lists follow a really simple grammar: the identifiers can
5898 // be followed *only* by a ", identifier" or ")". However, K&R
5899 // identifier lists are really rare in the brave new modern world, and
5900 // it is very common for someone to typo a type in a non-K&R style
5901 // list. If we are presented with something like: "void foo(intptr x,
5902 // float y)", we don't want to start parsing the function declarator as
5903 // though it is a K&R style declarator just because intptr is an
5906 // To handle this, we check to see if the token after the first
5907 // identifier is a "," or ")". Only then do we parse it as an
5909 && (!Tok.is(tok::eof) &&
5910 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
5913 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
5914 /// we found a K&R-style identifier list instead of a typed parameter list.
5916 /// After returning, ParamInfo will hold the parsed parameters.
5918 /// identifier-list: [C99 6.7.5]
5920 /// identifier-list ',' identifier
5922 void Parser::ParseFunctionDeclaratorIdentifierList(
5924 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
5925 // If there was no identifier specified for the declarator, either we are in
5926 // an abstract-declarator, or we are in a parameter declarator which was found
5927 // to be abstract. In abstract-declarators, identifier lists are not valid:
5929 if (!D.getIdentifier())
5930 Diag(Tok, diag::ext_ident_list_in_param);
5932 // Maintain an efficient lookup of params we have seen so far.
5933 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
5936 // If this isn't an identifier, report the error and skip until ')'.
5937 if (Tok.isNot(tok::identifier)) {
5938 Diag(Tok, diag::err_expected) << tok::identifier;
5939 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
5940 // Forget we parsed anything.
5945 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
5947 // Reject 'typedef int y; int test(x, y)', but continue parsing.
5948 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
5949 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
5951 // Verify that the argument identifier has not already been mentioned.
5952 if (!ParamsSoFar.insert(ParmII).second) {
5953 Diag(Tok, diag::err_param_redefinition) << ParmII;
5955 // Remember this identifier in ParamInfo.
5956 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
5961 // Eat the identifier.
5963 // The list continues if we see a comma.
5964 } while (TryConsumeToken(tok::comma));
5967 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
5968 /// after the opening parenthesis. This function will not parse a K&R-style
5969 /// identifier list.
5971 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
5972 /// caller parsed those arguments immediately after the open paren - they should
5973 /// be considered to be part of the first parameter.
5975 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
5976 /// be the location of the ellipsis, if any was parsed.
5978 /// parameter-type-list: [C99 6.7.5]
5980 /// parameter-list ',' '...'
5981 /// [C++] parameter-list '...'
5983 /// parameter-list: [C99 6.7.5]
5984 /// parameter-declaration
5985 /// parameter-list ',' parameter-declaration
5987 /// parameter-declaration: [C99 6.7.5]
5988 /// declaration-specifiers declarator
5989 /// [C++] declaration-specifiers declarator '=' assignment-expression
5990 /// [C++11] initializer-clause
5991 /// [GNU] declaration-specifiers declarator attributes
5992 /// declaration-specifiers abstract-declarator[opt]
5993 /// [C++] declaration-specifiers abstract-declarator[opt]
5994 /// '=' assignment-expression
5995 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
5996 /// [C++11] attribute-specifier-seq parameter-declaration
5998 void Parser::ParseParameterDeclarationClause(
6000 ParsedAttributes &FirstArgAttrs,
6001 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
6002 SourceLocation &EllipsisLoc) {
6004 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6005 // before deciding this was a parameter-declaration-clause.
6006 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
6009 // Parse the declaration-specifiers.
6010 // Just use the ParsingDeclaration "scope" of the declarator.
6011 DeclSpec DS(AttrFactory);
6013 // Parse any C++11 attributes.
6014 MaybeParseCXX11Attributes(DS.getAttributes());
6016 // Skip any Microsoft attributes before a param.
6017 MaybeParseMicrosoftAttributes(DS.getAttributes());
6019 SourceLocation DSStart = Tok.getLocation();
6021 // If the caller parsed attributes for the first argument, add them now.
6022 // Take them so that we only apply the attributes to the first parameter.
6023 // FIXME: If we can leave the attributes in the token stream somehow, we can
6024 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6026 DS.takeAttributesFrom(FirstArgAttrs);
6028 ParseDeclarationSpecifiers(DS);
6031 // Parse the declarator. This is "PrototypeContext" or
6032 // "LambdaExprParameterContext", because we must accept either
6033 // 'declarator' or 'abstract-declarator' here.
6034 Declarator ParmDeclarator(DS,
6035 D.getContext() == Declarator::LambdaExprContext ?
6036 Declarator::LambdaExprParameterContext :
6037 Declarator::PrototypeContext);
6038 ParseDeclarator(ParmDeclarator);
6040 // Parse GNU attributes, if present.
6041 MaybeParseGNUAttributes(ParmDeclarator);
6043 // Remember this parsed parameter in ParamInfo.
6044 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
6046 // DefArgToks is used when the parsing of default arguments needs
6048 std::unique_ptr<CachedTokens> DefArgToks;
6050 // If no parameter was specified, verify that *something* was specified,
6051 // otherwise we have a missing type and identifier.
6052 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
6053 ParmDeclarator.getNumTypeObjects() == 0) {
6054 // Completely missing, emit error.
6055 Diag(DSStart, diag::err_missing_param);
6057 // Otherwise, we have something. Add it and let semantic analysis try
6058 // to grok it and add the result to the ParamInfo we are building.
6060 // Last chance to recover from a misplaced ellipsis in an attempted
6061 // parameter pack declaration.
6062 if (Tok.is(tok::ellipsis) &&
6063 (NextToken().isNot(tok::r_paren) ||
6064 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6065 !Actions.isUnexpandedParameterPackPermitted())) &&
6066 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6067 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6069 // Inform the actions module about the parameter declarator, so it gets
6070 // added to the current scope.
6071 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
6072 // Parse the default argument, if any. We parse the default
6073 // arguments in all dialects; the semantic analysis in
6074 // ActOnParamDefaultArgument will reject the default argument in
6076 if (Tok.is(tok::equal)) {
6077 SourceLocation EqualLoc = Tok.getLocation();
6079 // Parse the default argument
6080 if (D.getContext() == Declarator::MemberContext) {
6081 // If we're inside a class definition, cache the tokens
6082 // corresponding to the default argument. We'll actually parse
6083 // them when we see the end of the class definition.
6084 DefArgToks.reset(new CachedTokens);
6086 SourceLocation ArgStartLoc = NextToken().getLocation();
6087 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
6089 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6091 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
6098 // The argument isn't actually potentially evaluated unless it is
6100 EnterExpressionEvaluationContext Eval(Actions,
6101 Sema::PotentiallyEvaluatedIfUsed,
6104 ExprResult DefArgResult;
6105 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
6106 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
6107 DefArgResult = ParseBraceInitializer();
6109 DefArgResult = ParseAssignmentExpression();
6110 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
6111 if (DefArgResult.isInvalid()) {
6112 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6113 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
6115 // Inform the actions module about the default argument
6116 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
6117 DefArgResult.get());
6122 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6123 ParmDeclarator.getIdentifierLoc(),
6124 Param, std::move(DefArgToks)));
6127 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6128 if (!getLangOpts().CPlusPlus) {
6129 // We have ellipsis without a preceding ',', which is ill-formed
6130 // in C. Complain and provide the fix.
6131 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6132 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6133 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6134 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6135 // It looks like this was supposed to be a parameter pack. Warn and
6136 // point out where the ellipsis should have gone.
6137 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6138 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6139 << ParmEllipsis.isValid() << ParmEllipsis;
6140 if (ParmEllipsis.isValid()) {
6142 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6144 Diag(ParmDeclarator.getIdentifierLoc(),
6145 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6146 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6148 << !ParmDeclarator.hasName();
6150 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
6151 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6154 // We can't have any more parameters after an ellipsis.
6158 // If the next token is a comma, consume it and keep reading arguments.
6159 } while (TryConsumeToken(tok::comma));
6162 /// [C90] direct-declarator '[' constant-expression[opt] ']'
6163 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6164 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6165 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6166 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
6167 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
6168 /// attribute-specifier-seq[opt]
6169 void Parser::ParseBracketDeclarator(Declarator &D) {
6170 if (CheckProhibitedCXX11Attribute())
6173 BalancedDelimiterTracker T(*this, tok::l_square);
6176 // C array syntax has many features, but by-far the most common is [] and [4].
6177 // This code does a fast path to handle some of the most obvious cases.
6178 if (Tok.getKind() == tok::r_square) {
6180 ParsedAttributes attrs(AttrFactory);
6181 MaybeParseCXX11Attributes(attrs);
6183 // Remember that we parsed the empty array type.
6184 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
6185 T.getOpenLocation(),
6186 T.getCloseLocation()),
6187 attrs, T.getCloseLocation());
6189 } else if (Tok.getKind() == tok::numeric_constant &&
6190 GetLookAheadToken(1).is(tok::r_square)) {
6191 // [4] is very common. Parse the numeric constant expression.
6192 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
6196 ParsedAttributes attrs(AttrFactory);
6197 MaybeParseCXX11Attributes(attrs);
6199 // Remember that we parsed a array type, and remember its features.
6200 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false,
6202 T.getOpenLocation(),
6203 T.getCloseLocation()),
6204 attrs, T.getCloseLocation());
6206 } else if (Tok.getKind() == tok::code_completion) {
6207 Actions.CodeCompleteBracketDeclarator(getCurScope());
6208 return cutOffParsing();
6211 // If valid, this location is the position where we read the 'static' keyword.
6212 SourceLocation StaticLoc;
6213 TryConsumeToken(tok::kw_static, StaticLoc);
6215 // If there is a type-qualifier-list, read it now.
6216 // Type qualifiers in an array subscript are a C99 feature.
6217 DeclSpec DS(AttrFactory);
6218 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
6220 // If we haven't already read 'static', check to see if there is one after the
6221 // type-qualifier-list.
6222 if (!StaticLoc.isValid())
6223 TryConsumeToken(tok::kw_static, StaticLoc);
6225 // Handle "direct-declarator [ type-qual-list[opt] * ]".
6226 bool isStar = false;
6227 ExprResult NumElements;
6229 // Handle the case where we have '[*]' as the array size. However, a leading
6230 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
6231 // the token after the star is a ']'. Since stars in arrays are
6232 // infrequent, use of lookahead is not costly here.
6233 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
6234 ConsumeToken(); // Eat the '*'.
6236 if (StaticLoc.isValid()) {
6237 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
6238 StaticLoc = SourceLocation(); // Drop the static.
6241 } else if (Tok.isNot(tok::r_square)) {
6242 // Note, in C89, this production uses the constant-expr production instead
6243 // of assignment-expr. The only difference is that assignment-expr allows
6244 // things like '=' and '*='. Sema rejects these in C89 mode because they
6245 // are not i-c-e's, so we don't need to distinguish between the two here.
6247 // Parse the constant-expression or assignment-expression now (depending
6249 if (getLangOpts().CPlusPlus) {
6250 NumElements = ParseConstantExpression();
6252 EnterExpressionEvaluationContext Unevaluated(Actions,
6253 Sema::ConstantEvaluated);
6255 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
6258 if (StaticLoc.isValid()) {
6259 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6260 StaticLoc = SourceLocation(); // Drop the static.
6264 // If there was an error parsing the assignment-expression, recover.
6265 if (NumElements.isInvalid()) {
6266 D.setInvalidType(true);
6267 // If the expression was invalid, skip it.
6268 SkipUntil(tok::r_square, StopAtSemi);
6274 MaybeParseCXX11Attributes(DS.getAttributes());
6276 // Remember that we parsed a array type, and remember its features.
6277 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
6278 StaticLoc.isValid(), isStar,
6280 T.getOpenLocation(),
6281 T.getCloseLocation()),
6282 DS.getAttributes(), T.getCloseLocation());
6285 /// Diagnose brackets before an identifier.
6286 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6287 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6288 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6290 SourceLocation StartBracketLoc = Tok.getLocation();
6291 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6293 while (Tok.is(tok::l_square)) {
6294 ParseBracketDeclarator(TempDeclarator);
6297 // Stuff the location of the start of the brackets into the Declarator.
6298 // The diagnostics from ParseDirectDeclarator will make more sense if
6299 // they use this location instead.
6300 if (Tok.is(tok::semi))
6301 D.getName().EndLocation = StartBracketLoc;
6303 SourceLocation SuggestParenLoc = Tok.getLocation();
6305 // Now that the brackets are removed, try parsing the declarator again.
6306 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6308 // Something went wrong parsing the brackets, in which case,
6309 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6311 if (TempDeclarator.getNumTypeObjects() == 0)
6314 // Determine if parens will need to be suggested in the diagnostic.
6315 bool NeedParens = false;
6316 if (D.getNumTypeObjects() != 0) {
6317 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6318 case DeclaratorChunk::Pointer:
6319 case DeclaratorChunk::Reference:
6320 case DeclaratorChunk::BlockPointer:
6321 case DeclaratorChunk::MemberPointer:
6322 case DeclaratorChunk::Pipe:
6325 case DeclaratorChunk::Array:
6326 case DeclaratorChunk::Function:
6327 case DeclaratorChunk::Paren:
6333 // Create a DeclaratorChunk for the inserted parens.
6334 ParsedAttributes attrs(AttrFactory);
6335 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6336 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), attrs,
6340 // Adding back the bracket info to the end of the Declarator.
6341 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6342 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
6343 ParsedAttributes attrs(AttrFactory);
6344 attrs.set(Chunk.Common.AttrList);
6345 D.AddTypeInfo(Chunk, attrs, SourceLocation());
6348 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6349 // If parentheses are required, always suggest them.
6350 if (!D.getIdentifier() && !NeedParens)
6353 SourceLocation EndBracketLoc = TempDeclarator.getLocEnd();
6355 // Generate the move bracket error message.
6356 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
6357 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6360 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6361 << getLangOpts().CPlusPlus
6362 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6363 << FixItHint::CreateInsertion(EndLoc, ")")
6364 << FixItHint::CreateInsertionFromRange(
6365 EndLoc, CharSourceRange(BracketRange, true))
6366 << FixItHint::CreateRemoval(BracketRange);
6368 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6369 << getLangOpts().CPlusPlus
6370 << FixItHint::CreateInsertionFromRange(
6371 EndLoc, CharSourceRange(BracketRange, true))
6372 << FixItHint::CreateRemoval(BracketRange);
6376 /// [GNU] typeof-specifier:
6377 /// typeof ( expressions )
6378 /// typeof ( type-name )
6379 /// [GNU/C++] typeof unary-expression
6381 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
6382 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
6384 SourceLocation StartLoc = ConsumeToken();
6386 const bool hasParens = Tok.is(tok::l_paren);
6388 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
6389 Sema::ReuseLambdaContextDecl);
6393 SourceRange CastRange;
6394 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6395 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
6397 DS.setTypeofParensRange(CastRange);
6399 if (CastRange.getEnd().isInvalid())
6400 // FIXME: Not accurate, the range gets one token more than it should.
6401 DS.SetRangeEnd(Tok.getLocation());
6403 DS.SetRangeEnd(CastRange.getEnd());
6407 DS.SetTypeSpecError();
6411 const char *PrevSpec = nullptr;
6413 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6414 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
6416 Actions.getASTContext().getPrintingPolicy()))
6417 Diag(StartLoc, DiagID) << PrevSpec;
6421 // If we get here, the operand to the typeof was an expresion.
6422 if (Operand.isInvalid()) {
6423 DS.SetTypeSpecError();
6427 // We might need to transform the operand if it is potentially evaluated.
6428 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6429 if (Operand.isInvalid()) {
6430 DS.SetTypeSpecError();
6434 const char *PrevSpec = nullptr;
6436 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6437 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
6438 DiagID, Operand.get(),
6439 Actions.getASTContext().getPrintingPolicy()))
6440 Diag(StartLoc, DiagID) << PrevSpec;
6443 /// [C11] atomic-specifier:
6444 /// _Atomic ( type-name )
6446 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
6447 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6448 "Not an atomic specifier");
6450 SourceLocation StartLoc = ConsumeToken();
6451 BalancedDelimiterTracker T(*this, tok::l_paren);
6452 if (T.consumeOpen())
6455 TypeResult Result = ParseTypeName();
6456 if (Result.isInvalid()) {
6457 SkipUntil(tok::r_paren, StopAtSemi);
6464 if (T.getCloseLocation().isInvalid())
6467 DS.setTypeofParensRange(T.getRange());
6468 DS.SetRangeEnd(T.getCloseLocation());
6470 const char *PrevSpec = nullptr;
6472 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
6473 DiagID, Result.get(),
6474 Actions.getASTContext().getPrintingPolicy()))
6475 Diag(StartLoc, DiagID) << PrevSpec;
6478 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6479 /// from TryAltiVecVectorToken.
6480 bool Parser::TryAltiVecVectorTokenOutOfLine() {
6481 Token Next = NextToken();
6482 switch (Next.getKind()) {
6483 default: return false;
6486 case tok::kw_signed:
6487 case tok::kw_unsigned:
6492 case tok::kw_double:
6494 case tok::kw___bool:
6495 case tok::kw___pixel:
6496 Tok.setKind(tok::kw___vector);
6498 case tok::identifier:
6499 if (Next.getIdentifierInfo() == Ident_pixel) {
6500 Tok.setKind(tok::kw___vector);
6503 if (Next.getIdentifierInfo() == Ident_bool) {
6504 Tok.setKind(tok::kw___vector);
6511 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6512 const char *&PrevSpec, unsigned &DiagID,
6514 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
6515 if (Tok.getIdentifierInfo() == Ident_vector) {
6516 Token Next = NextToken();
6517 switch (Next.getKind()) {
6520 case tok::kw_signed:
6521 case tok::kw_unsigned:
6526 case tok::kw_double:
6528 case tok::kw___bool:
6529 case tok::kw___pixel:
6530 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
6532 case tok::identifier:
6533 if (Next.getIdentifierInfo() == Ident_pixel) {
6534 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6537 if (Next.getIdentifierInfo() == Ident_bool) {
6538 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6545 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
6546 DS.isTypeAltiVecVector()) {
6547 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
6549 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
6550 DS.isTypeAltiVecVector()) {
6551 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);