1 //===--- ParseDecl.cpp - Declaration Parsing ------------------------------===//
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 "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringSwitch.h"
30 using namespace clang;
32 //===----------------------------------------------------------------------===//
33 // C99 6.7: Declarations.
34 //===----------------------------------------------------------------------===//
37 /// type-name: [C99 6.7.6]
38 /// specifier-qualifier-list abstract-declarator[opt]
40 /// Called type-id in C++.
41 TypeResult Parser::ParseTypeName(SourceRange *Range,
42 Declarator::TheContext Context,
45 ParsedAttributes *Attrs) {
46 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
47 if (DSC == DSC_normal)
48 DSC = DSC_type_specifier;
50 // Parse the common declaration-specifiers piece.
51 DeclSpec DS(AttrFactory);
53 DS.addAttributes(Attrs->getList());
54 ParseSpecifierQualifierList(DS, AS, DSC);
56 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
58 // Parse the abstract-declarator, if present.
59 Declarator DeclaratorInfo(DS, Context);
60 ParseDeclarator(DeclaratorInfo);
62 *Range = DeclaratorInfo.getSourceRange();
64 if (DeclaratorInfo.isInvalidType())
67 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
71 /// isAttributeLateParsed - Return true if the attribute has arguments that
72 /// require late parsing.
73 static bool isAttributeLateParsed(const IdentifierInfo &II) {
74 #define CLANG_ATTR_LATE_PARSED_LIST
75 return llvm::StringSwitch<bool>(II.getName())
76 #include "clang/Parse/AttrParserStringSwitches.inc"
78 #undef CLANG_ATTR_LATE_PARSED_LIST
81 /// ParseGNUAttributes - Parse a non-empty attributes list.
85 /// attributes attribute
88 /// '__attribute__' '(' '(' attribute-list ')' ')'
90 /// [GNU] attribute-list:
92 /// attribute_list ',' attrib
97 /// attrib-name '(' identifier ')'
98 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
99 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
101 /// [GNU] attrib-name:
107 /// Whether an attribute takes an 'identifier' is determined by the
108 /// attrib-name. GCC's behavior here is not worth imitating:
110 /// * In C mode, if the attribute argument list starts with an identifier
111 /// followed by a ',' or an ')', and the identifier doesn't resolve to
112 /// a type, it is parsed as an identifier. If the attribute actually
113 /// wanted an expression, it's out of luck (but it turns out that no
114 /// attributes work that way, because C constant expressions are very
116 /// * In C++ mode, if the attribute argument list starts with an identifier,
117 /// and the attribute *wants* an identifier, it is parsed as an identifier.
118 /// At block scope, any additional tokens between the identifier and the
119 /// ',' or ')' are ignored, otherwise they produce a parse error.
121 /// We follow the C++ model, but don't allow junk after the identifier.
122 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
123 SourceLocation *endLoc,
124 LateParsedAttrList *LateAttrs,
126 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
128 while (Tok.is(tok::kw___attribute)) {
130 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
132 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
135 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
136 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
139 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
141 // Allow empty/non-empty attributes. ((__vector_size__(16),,,,))
142 if (TryConsumeToken(tok::comma))
145 // Expect an identifier or declaration specifier (const, int, etc.)
146 if (Tok.isNot(tok::identifier) && !isDeclarationSpecifier())
149 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
150 SourceLocation AttrNameLoc = ConsumeToken();
152 if (Tok.isNot(tok::l_paren)) {
153 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
154 AttributeList::AS_GNU);
158 // Handle "parameterized" attributes
159 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
160 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
161 SourceLocation(), AttributeList::AS_GNU, D);
165 // Handle attributes with arguments that require late parsing.
166 LateParsedAttribute *LA =
167 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
168 LateAttrs->push_back(LA);
170 // Attributes in a class are parsed at the end of the class, along
171 // with other late-parsed declarations.
172 if (!ClassStack.empty() && !LateAttrs->parseSoon())
173 getCurrentClass().LateParsedDeclarations.push_back(LA);
175 // consume everything up to and including the matching right parens
176 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false);
180 Eof.setLocation(Tok.getLocation());
181 LA->Toks.push_back(Eof);
184 if (ExpectAndConsume(tok::r_paren))
185 SkipUntil(tok::r_paren, StopAtSemi);
186 SourceLocation Loc = Tok.getLocation();
187 if (ExpectAndConsume(tok::r_paren))
188 SkipUntil(tok::r_paren, StopAtSemi);
194 /// \brief Normalizes an attribute name by dropping prefixed and suffixed __.
195 static StringRef normalizeAttrName(StringRef Name) {
196 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
197 Name = Name.drop_front(2).drop_back(2);
201 /// \brief Determine whether the given attribute has an identifier argument.
202 static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
203 #define CLANG_ATTR_IDENTIFIER_ARG_LIST
204 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
205 #include "clang/Parse/AttrParserStringSwitches.inc"
207 #undef CLANG_ATTR_IDENTIFIER_ARG_LIST
210 /// \brief Determine whether the given attribute parses a type argument.
211 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
212 #define CLANG_ATTR_TYPE_ARG_LIST
213 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
214 #include "clang/Parse/AttrParserStringSwitches.inc"
216 #undef CLANG_ATTR_TYPE_ARG_LIST
219 /// \brief Determine whether the given attribute requires parsing its arguments
220 /// in an unevaluated context or not.
221 static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
222 #define CLANG_ATTR_ARG_CONTEXT_LIST
223 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
224 #include "clang/Parse/AttrParserStringSwitches.inc"
226 #undef CLANG_ATTR_ARG_CONTEXT_LIST
229 IdentifierLoc *Parser::ParseIdentifierLoc() {
230 assert(Tok.is(tok::identifier) && "expected an identifier");
231 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
233 Tok.getIdentifierInfo());
238 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
239 SourceLocation AttrNameLoc,
240 ParsedAttributes &Attrs,
241 SourceLocation *EndLoc,
242 IdentifierInfo *ScopeName,
243 SourceLocation ScopeLoc,
244 AttributeList::Syntax Syntax) {
245 BalancedDelimiterTracker Parens(*this, tok::l_paren);
246 Parens.consumeOpen();
249 if (Tok.isNot(tok::r_paren))
252 if (Parens.consumeClose())
259 Attrs.addNewTypeAttr(&AttrName,
260 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
261 ScopeName, ScopeLoc, T.get(), Syntax);
263 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
264 ScopeName, ScopeLoc, nullptr, 0, Syntax);
267 unsigned Parser::ParseAttributeArgsCommon(
268 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
269 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
270 SourceLocation ScopeLoc, AttributeList::Syntax Syntax) {
271 // Ignore the left paren location for now.
275 if (Tok.is(tok::identifier)) {
276 // If this attribute wants an 'identifier' argument, make it so.
277 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName);
278 AttributeList::Kind AttrKind =
279 AttributeList::getKind(AttrName, ScopeName, Syntax);
281 // If we don't know how to parse this attribute, but this is the only
282 // token in this argument, assume it's meant to be an identifier.
283 if (AttrKind == AttributeList::UnknownAttribute ||
284 AttrKind == AttributeList::IgnoredAttribute) {
285 const Token &Next = NextToken();
286 IsIdentifierArg = Next.is(tok::r_paren) || Next.is(tok::comma);
290 ArgExprs.push_back(ParseIdentifierLoc());
293 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
295 if (!ArgExprs.empty())
298 // Parse the non-empty comma-separated list of expressions.
300 std::unique_ptr<EnterExpressionEvaluationContext> Unevaluated;
301 if (attributeParsedArgsUnevaluated(*AttrName))
303 new EnterExpressionEvaluationContext(Actions, Sema::Unevaluated));
305 ExprResult ArgExpr(ParseAssignmentExpression());
306 if (ArgExpr.isInvalid()) {
307 SkipUntil(tok::r_paren, StopAtSemi);
310 ArgExprs.push_back(ArgExpr.get());
311 // Eat the comma, move to the next argument
312 } while (TryConsumeToken(tok::comma));
315 SourceLocation RParen = Tok.getLocation();
316 if (!ExpectAndConsume(tok::r_paren)) {
317 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
318 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
319 ArgExprs.data(), ArgExprs.size(), Syntax);
325 return static_cast<unsigned>(ArgExprs.size());
328 /// Parse the arguments to a parameterized GNU attribute or
329 /// a C++11 attribute in "gnu" namespace.
330 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
331 SourceLocation AttrNameLoc,
332 ParsedAttributes &Attrs,
333 SourceLocation *EndLoc,
334 IdentifierInfo *ScopeName,
335 SourceLocation ScopeLoc,
336 AttributeList::Syntax Syntax,
339 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
341 AttributeList::Kind AttrKind =
342 AttributeList::getKind(AttrName, ScopeName, Syntax);
344 if (AttrKind == AttributeList::AT_Availability) {
345 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
348 } else if (AttrKind == AttributeList::AT_ObjCBridgeRelated) {
349 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
350 ScopeName, ScopeLoc, Syntax);
352 } else if (AttrKind == AttributeList::AT_TypeTagForDatatype) {
353 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
354 ScopeName, ScopeLoc, Syntax);
356 } else if (attributeIsTypeArgAttr(*AttrName)) {
357 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
362 // These may refer to the function arguments, but need to be parsed early to
363 // participate in determining whether it's a redeclaration.
364 std::unique_ptr<ParseScope> PrototypeScope;
365 if (AttrName->isStr("enable_if") && D && D->isFunctionDeclarator()) {
366 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
367 PrototypeScope.reset(new ParseScope(this, Scope::FunctionPrototypeScope |
368 Scope::FunctionDeclarationScope |
370 for (unsigned i = 0; i != FTI.NumParams; ++i) {
371 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
372 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
376 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
380 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
381 SourceLocation AttrNameLoc,
382 ParsedAttributes &Attrs) {
383 // If the attribute isn't known, we will not attempt to parse any
385 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
386 getTargetInfo().getTriple(), getLangOpts())) {
387 // Eat the left paren, then skip to the ending right paren.
389 SkipUntil(tok::r_paren);
393 SourceLocation OpenParenLoc = Tok.getLocation();
395 if (AttrName->getName() == "property") {
396 // The property declspec is more complex in that it can take one or two
397 // assignment expressions as a parameter, but the lhs of the assignment
398 // must be named get or put.
400 BalancedDelimiterTracker T(*this, tok::l_paren);
401 T.expectAndConsume(diag::err_expected_lparen_after,
402 AttrName->getNameStart(), tok::r_paren);
407 AK_Get = 1 // indices into AccessorNames
409 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
410 bool HasInvalidAccessor = false;
412 // Parse the accessor specifications.
414 // Stop if this doesn't look like an accessor spec.
415 if (!Tok.is(tok::identifier)) {
416 // If the user wrote a completely empty list, use a special diagnostic.
417 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
418 AccessorNames[AK_Put] == nullptr &&
419 AccessorNames[AK_Get] == nullptr) {
420 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
424 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
429 SourceLocation KindLoc = Tok.getLocation();
430 StringRef KindStr = Tok.getIdentifierInfo()->getName();
431 if (KindStr == "get") {
433 } else if (KindStr == "put") {
436 // Recover from the common mistake of using 'set' instead of 'put'.
437 } else if (KindStr == "set") {
438 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
439 << FixItHint::CreateReplacement(KindLoc, "put");
442 // Handle the mistake of forgetting the accessor kind by skipping
444 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
445 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
447 HasInvalidAccessor = true;
448 goto next_property_accessor;
450 // Otherwise, complain about the unknown accessor kind.
452 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
453 HasInvalidAccessor = true;
456 // Try to keep parsing unless it doesn't look like an accessor spec.
457 if (!NextToken().is(tok::equal))
461 // Consume the identifier.
465 if (!TryConsumeToken(tok::equal)) {
466 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
471 // Expect the method name.
472 if (!Tok.is(tok::identifier)) {
473 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
477 if (Kind == AK_Invalid) {
478 // Just drop invalid accessors.
479 } else if (AccessorNames[Kind] != nullptr) {
480 // Complain about the repeated accessor, ignore it, and keep parsing.
481 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
483 AccessorNames[Kind] = Tok.getIdentifierInfo();
487 next_property_accessor:
488 // Keep processing accessors until we run out.
489 if (TryConsumeToken(tok::comma))
492 // If we run into the ')', stop without consuming it.
493 if (Tok.is(tok::r_paren))
496 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
500 // Only add the property attribute if it was well-formed.
501 if (!HasInvalidAccessor)
502 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
503 AccessorNames[AK_Get], AccessorNames[AK_Put],
504 AttributeList::AS_Declspec);
506 return !HasInvalidAccessor;
510 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
511 SourceLocation(), AttributeList::AS_Declspec);
513 // If this attribute's args were parsed, and it was expected to have
514 // arguments but none were provided, emit a diagnostic.
515 const AttributeList *Attr = Attrs.getList();
516 if (Attr && Attr->getMaxArgs() && !NumArgs) {
517 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
523 /// [MS] decl-specifier:
524 /// __declspec ( extended-decl-modifier-seq )
526 /// [MS] extended-decl-modifier-seq:
527 /// extended-decl-modifier[opt]
528 /// extended-decl-modifier extended-decl-modifier-seq
529 void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &Attrs) {
530 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
533 BalancedDelimiterTracker T(*this, tok::l_paren);
534 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
538 // An empty declspec is perfectly legal and should not warn. Additionally,
539 // you can specify multiple attributes per declspec.
540 while (Tok.isNot(tok::r_paren)) {
541 // Attribute not present.
542 if (TryConsumeToken(tok::comma))
545 // We expect either a well-known identifier or a generic string. Anything
546 // else is a malformed declspec.
547 bool IsString = Tok.getKind() == tok::string_literal ? true : false;
548 if (!IsString && Tok.getKind() != tok::identifier &&
549 Tok.getKind() != tok::kw_restrict) {
550 Diag(Tok, diag::err_ms_declspec_type);
555 IdentifierInfo *AttrName;
556 SourceLocation AttrNameLoc;
558 SmallString<8> StrBuffer;
559 bool Invalid = false;
560 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
565 AttrName = PP.getIdentifierInfo(Str);
566 AttrNameLoc = ConsumeStringToken();
568 AttrName = Tok.getIdentifierInfo();
569 AttrNameLoc = ConsumeToken();
572 bool AttrHandled = false;
574 // Parse attribute arguments.
575 if (Tok.is(tok::l_paren))
576 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
577 else if (AttrName->getName() == "property")
578 // The property attribute must have an argument list.
579 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
580 << AttrName->getName();
583 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
584 AttributeList::AS_Declspec);
589 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
590 // Treat these like attributes
591 while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
592 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl) ||
593 Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) ||
594 Tok.is(tok::kw___ptr32) || Tok.is(tok::kw___unaligned) ||
595 Tok.is(tok::kw___sptr) || Tok.is(tok::kw___uptr)) {
596 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
597 SourceLocation AttrNameLoc = ConsumeToken();
598 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
599 AttributeList::AS_Keyword);
603 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
604 // Treat these like attributes
605 while (Tok.is(tok::kw___pascal)) {
606 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
607 SourceLocation AttrNameLoc = ConsumeToken();
608 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
609 AttributeList::AS_Keyword);
613 void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
614 // Treat these like attributes
615 while (Tok.is(tok::kw___kernel)) {
616 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
617 SourceLocation AttrNameLoc = ConsumeToken();
618 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
619 AttributeList::AS_Keyword);
623 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
624 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
625 SourceLocation AttrNameLoc = Tok.getLocation();
626 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
627 AttributeList::AS_Keyword);
630 /// \brief Parse a version number.
634 /// simple-integer ',' simple-integer
635 /// simple-integer ',' simple-integer ',' simple-integer
636 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
637 Range = Tok.getLocation();
639 if (!Tok.is(tok::numeric_constant)) {
640 Diag(Tok, diag::err_expected_version);
641 SkipUntil(tok::comma, tok::r_paren,
642 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
643 return VersionTuple();
646 // Parse the major (and possibly minor and subminor) versions, which
647 // are stored in the numeric constant. We utilize a quirk of the
648 // lexer, which is that it handles something like 1.2.3 as a single
649 // numeric constant, rather than two separate tokens.
650 SmallString<512> Buffer;
651 Buffer.resize(Tok.getLength()+1);
652 const char *ThisTokBegin = &Buffer[0];
654 // Get the spelling of the token, which eliminates trigraphs, etc.
655 bool Invalid = false;
656 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
658 return VersionTuple();
660 // Parse the major version.
661 unsigned AfterMajor = 0;
663 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
664 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
668 if (AfterMajor == 0) {
669 Diag(Tok, diag::err_expected_version);
670 SkipUntil(tok::comma, tok::r_paren,
671 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
672 return VersionTuple();
675 if (AfterMajor == ActualLength) {
678 // We only had a single version component.
680 Diag(Tok, diag::err_zero_version);
681 return VersionTuple();
684 return VersionTuple(Major);
687 if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) {
688 Diag(Tok, diag::err_expected_version);
689 SkipUntil(tok::comma, tok::r_paren,
690 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
691 return VersionTuple();
694 // Parse the minor version.
695 unsigned AfterMinor = AfterMajor + 1;
697 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
698 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
702 if (AfterMinor == ActualLength) {
705 // We had major.minor.
706 if (Major == 0 && Minor == 0) {
707 Diag(Tok, diag::err_zero_version);
708 return VersionTuple();
711 return VersionTuple(Major, Minor);
714 // If what follows is not a '.', we have a problem.
715 if (ThisTokBegin[AfterMinor] != '.') {
716 Diag(Tok, diag::err_expected_version);
717 SkipUntil(tok::comma, tok::r_paren,
718 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
719 return VersionTuple();
722 // Parse the subminor version.
723 unsigned AfterSubminor = AfterMinor + 1;
724 unsigned Subminor = 0;
725 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
726 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
730 if (AfterSubminor != ActualLength) {
731 Diag(Tok, diag::err_expected_version);
732 SkipUntil(tok::comma, tok::r_paren,
733 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
734 return VersionTuple();
737 return VersionTuple(Major, Minor, Subminor);
740 /// \brief Parse the contents of the "availability" attribute.
742 /// availability-attribute:
743 /// 'availability' '(' platform ',' version-arg-list, opt-message')'
748 /// version-arg-list:
750 /// version-arg ',' version-arg-list
753 /// 'introduced' '=' version
754 /// 'deprecated' '=' version
755 /// 'obsoleted' = version
758 /// 'message' '=' <string>
759 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
760 SourceLocation AvailabilityLoc,
761 ParsedAttributes &attrs,
762 SourceLocation *endLoc,
763 IdentifierInfo *ScopeName,
764 SourceLocation ScopeLoc,
765 AttributeList::Syntax Syntax) {
766 enum { Introduced, Deprecated, Obsoleted, Unknown };
767 AvailabilityChange Changes[Unknown];
768 ExprResult MessageExpr;
771 BalancedDelimiterTracker T(*this, tok::l_paren);
772 if (T.consumeOpen()) {
773 Diag(Tok, diag::err_expected) << tok::l_paren;
777 // Parse the platform name,
778 if (Tok.isNot(tok::identifier)) {
779 Diag(Tok, diag::err_availability_expected_platform);
780 SkipUntil(tok::r_paren, StopAtSemi);
783 IdentifierLoc *Platform = ParseIdentifierLoc();
785 // Parse the ',' following the platform name.
786 if (ExpectAndConsume(tok::comma)) {
787 SkipUntil(tok::r_paren, StopAtSemi);
791 // If we haven't grabbed the pointers for the identifiers
792 // "introduced", "deprecated", and "obsoleted", do so now.
793 if (!Ident_introduced) {
794 Ident_introduced = PP.getIdentifierInfo("introduced");
795 Ident_deprecated = PP.getIdentifierInfo("deprecated");
796 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
797 Ident_unavailable = PP.getIdentifierInfo("unavailable");
798 Ident_message = PP.getIdentifierInfo("message");
801 // Parse the set of introductions/deprecations/removals.
802 SourceLocation UnavailableLoc;
804 if (Tok.isNot(tok::identifier)) {
805 Diag(Tok, diag::err_availability_expected_change);
806 SkipUntil(tok::r_paren, StopAtSemi);
809 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
810 SourceLocation KeywordLoc = ConsumeToken();
812 if (Keyword == Ident_unavailable) {
813 if (UnavailableLoc.isValid()) {
814 Diag(KeywordLoc, diag::err_availability_redundant)
815 << Keyword << SourceRange(UnavailableLoc);
817 UnavailableLoc = KeywordLoc;
821 if (Tok.isNot(tok::equal)) {
822 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
823 SkipUntil(tok::r_paren, StopAtSemi);
827 if (Keyword == Ident_message) {
828 if (Tok.isNot(tok::string_literal)) {
829 Diag(Tok, diag::err_expected_string_literal)
830 << /*Source='availability attribute'*/2;
831 SkipUntil(tok::r_paren, StopAtSemi);
834 MessageExpr = ParseStringLiteralExpression();
835 // Also reject wide string literals.
836 if (StringLiteral *MessageStringLiteral =
837 cast_or_null<StringLiteral>(MessageExpr.get())) {
838 if (MessageStringLiteral->getCharByteWidth() != 1) {
839 Diag(MessageStringLiteral->getSourceRange().getBegin(),
840 diag::err_expected_string_literal)
841 << /*Source='availability attribute'*/ 2;
842 SkipUntil(tok::r_paren, StopAtSemi);
849 SourceRange VersionRange;
850 VersionTuple Version = ParseVersionTuple(VersionRange);
852 if (Version.empty()) {
853 SkipUntil(tok::r_paren, StopAtSemi);
858 if (Keyword == Ident_introduced)
860 else if (Keyword == Ident_deprecated)
862 else if (Keyword == Ident_obsoleted)
867 if (Index < Unknown) {
868 if (!Changes[Index].KeywordLoc.isInvalid()) {
869 Diag(KeywordLoc, diag::err_availability_redundant)
871 << SourceRange(Changes[Index].KeywordLoc,
872 Changes[Index].VersionRange.getEnd());
875 Changes[Index].KeywordLoc = KeywordLoc;
876 Changes[Index].Version = Version;
877 Changes[Index].VersionRange = VersionRange;
879 Diag(KeywordLoc, diag::err_availability_unknown_change)
880 << Keyword << VersionRange;
883 } while (TryConsumeToken(tok::comma));
886 if (T.consumeClose())
890 *endLoc = T.getCloseLocation();
892 // The 'unavailable' availability cannot be combined with any other
893 // availability changes. Make sure that hasn't happened.
894 if (UnavailableLoc.isValid()) {
895 bool Complained = false;
896 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
897 if (Changes[Index].KeywordLoc.isValid()) {
899 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
900 << SourceRange(Changes[Index].KeywordLoc,
901 Changes[Index].VersionRange.getEnd());
905 // Clear out the availability.
906 Changes[Index] = AvailabilityChange();
911 // Record this attribute
912 attrs.addNew(&Availability,
913 SourceRange(AvailabilityLoc, T.getCloseLocation()),
919 UnavailableLoc, MessageExpr.get(),
923 /// \brief Parse the contents of the "objc_bridge_related" attribute.
924 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
928 /// opt-class_method:
929 /// Identifier: | <empty>
931 /// opt-instance_method:
932 /// Identifier | <empty>
934 void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
935 SourceLocation ObjCBridgeRelatedLoc,
936 ParsedAttributes &attrs,
937 SourceLocation *endLoc,
938 IdentifierInfo *ScopeName,
939 SourceLocation ScopeLoc,
940 AttributeList::Syntax Syntax) {
942 BalancedDelimiterTracker T(*this, tok::l_paren);
943 if (T.consumeOpen()) {
944 Diag(Tok, diag::err_expected) << tok::l_paren;
948 // Parse the related class name.
949 if (Tok.isNot(tok::identifier)) {
950 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
951 SkipUntil(tok::r_paren, StopAtSemi);
954 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
955 if (ExpectAndConsume(tok::comma)) {
956 SkipUntil(tok::r_paren, StopAtSemi);
960 // Parse optional class method name.
961 IdentifierLoc *ClassMethod = nullptr;
962 if (Tok.is(tok::identifier)) {
963 ClassMethod = ParseIdentifierLoc();
964 if (!TryConsumeToken(tok::colon)) {
965 Diag(Tok, diag::err_objcbridge_related_selector_name);
966 SkipUntil(tok::r_paren, StopAtSemi);
970 if (!TryConsumeToken(tok::comma)) {
971 if (Tok.is(tok::colon))
972 Diag(Tok, diag::err_objcbridge_related_selector_name);
974 Diag(Tok, diag::err_expected) << tok::comma;
975 SkipUntil(tok::r_paren, StopAtSemi);
979 // Parse optional instance method name.
980 IdentifierLoc *InstanceMethod = nullptr;
981 if (Tok.is(tok::identifier))
982 InstanceMethod = ParseIdentifierLoc();
983 else if (Tok.isNot(tok::r_paren)) {
984 Diag(Tok, diag::err_expected) << tok::r_paren;
985 SkipUntil(tok::r_paren, StopAtSemi);
990 if (T.consumeClose())
994 *endLoc = T.getCloseLocation();
996 // Record this attribute
997 attrs.addNew(&ObjCBridgeRelated,
998 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1006 // Late Parsed Attributes:
1007 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1009 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1011 void Parser::LateParsedClass::ParseLexedAttributes() {
1012 Self->ParseLexedAttributes(*Class);
1015 void Parser::LateParsedAttribute::ParseLexedAttributes() {
1016 Self->ParseLexedAttribute(*this, true, false);
1019 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1020 /// scope appropriately.
1021 void Parser::ParseLexedAttributes(ParsingClass &Class) {
1022 // Deal with templates
1023 // FIXME: Test cases to make sure this does the right thing for templates.
1024 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1025 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1027 if (HasTemplateScope)
1028 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1030 // Set or update the scope flags.
1031 bool AlreadyHasClassScope = Class.TopLevelClass;
1032 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
1033 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1034 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1036 // Enter the scope of nested classes
1037 if (!AlreadyHasClassScope)
1038 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1039 Class.TagOrTemplate);
1040 if (!Class.LateParsedDeclarations.empty()) {
1041 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1042 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1046 if (!AlreadyHasClassScope)
1047 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1048 Class.TagOrTemplate);
1052 /// \brief Parse all attributes in LAs, and attach them to Decl D.
1053 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1054 bool EnterScope, bool OnDefinition) {
1055 assert(LAs.parseSoon() &&
1056 "Attribute list should be marked for immediate parsing.");
1057 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1060 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1067 /// \brief Finish parsing an attribute for which parsing was delayed.
1068 /// This will be called at the end of parsing a class declaration
1069 /// for each LateParsedAttribute. We consume the saved tokens and
1070 /// create an attribute with the arguments filled in. We add this
1071 /// to the Attribute list for the decl.
1072 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1073 bool EnterScope, bool OnDefinition) {
1074 // Save the current token position.
1075 SourceLocation OrigLoc = Tok.getLocation();
1077 // Append the current token at the end of the new token stream so that it
1078 // doesn't get lost.
1079 LA.Toks.push_back(Tok);
1080 PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false);
1081 // Consume the previously pushed token.
1082 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1084 ParsedAttributes Attrs(AttrFactory);
1085 SourceLocation endLoc;
1087 if (LA.Decls.size() > 0) {
1088 Decl *D = LA.Decls[0];
1089 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1090 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1092 // Allow 'this' within late-parsed attributes.
1093 Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0,
1094 ND && ND->isCXXInstanceMember());
1096 if (LA.Decls.size() == 1) {
1097 // If the Decl is templatized, add template parameters to scope.
1098 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1099 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1100 if (HasTemplateScope)
1101 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1103 // If the Decl is on a function, add function parameters to the scope.
1104 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1105 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunScope);
1107 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1109 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1110 nullptr, SourceLocation(), AttributeList::AS_GNU,
1114 Actions.ActOnExitFunctionContext();
1115 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1117 if (HasTemplateScope) {
1121 // If there are multiple decls, then the decl cannot be within the
1123 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1124 nullptr, SourceLocation(), AttributeList::AS_GNU,
1128 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1131 const AttributeList *AL = Attrs.getList();
1132 if (OnDefinition && AL && !AL->isCXX11Attribute() &&
1134 Diag(Tok, diag::warn_attribute_on_function_definition)
1137 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
1138 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1140 if (Tok.getLocation() != OrigLoc) {
1141 // Due to a parsing error, we either went over the cached tokens or
1142 // there are still cached tokens left, so we skip the leftover tokens.
1143 // Since this is an uncommon situation that should be avoided, use the
1144 // expensive isBeforeInTranslationUnit call.
1145 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
1147 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
1152 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1153 SourceLocation AttrNameLoc,
1154 ParsedAttributes &Attrs,
1155 SourceLocation *EndLoc,
1156 IdentifierInfo *ScopeName,
1157 SourceLocation ScopeLoc,
1158 AttributeList::Syntax Syntax) {
1159 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1161 BalancedDelimiterTracker T(*this, tok::l_paren);
1164 if (Tok.isNot(tok::identifier)) {
1165 Diag(Tok, diag::err_expected) << tok::identifier;
1169 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1171 if (ExpectAndConsume(tok::comma)) {
1176 SourceRange MatchingCTypeRange;
1177 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1178 if (MatchingCType.isInvalid()) {
1183 bool LayoutCompatible = false;
1184 bool MustBeNull = false;
1185 while (TryConsumeToken(tok::comma)) {
1186 if (Tok.isNot(tok::identifier)) {
1187 Diag(Tok, diag::err_expected) << tok::identifier;
1191 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1192 if (Flag->isStr("layout_compatible"))
1193 LayoutCompatible = true;
1194 else if (Flag->isStr("must_be_null"))
1197 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1201 ConsumeToken(); // consume flag
1204 if (!T.consumeClose()) {
1205 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1206 ArgumentKind, MatchingCType.get(),
1207 LayoutCompatible, MustBeNull, Syntax);
1211 *EndLoc = T.getCloseLocation();
1214 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1215 /// of a C++11 attribute-specifier in a location where an attribute is not
1216 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1219 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1220 /// this doesn't appear to actually be an attribute-specifier, and the caller
1221 /// should try to parse it.
1222 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1223 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1225 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1226 case CAK_NotAttributeSpecifier:
1227 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1230 case CAK_InvalidAttributeSpecifier:
1231 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1234 case CAK_AttributeSpecifier:
1235 // Parse and discard the attributes.
1236 SourceLocation BeginLoc = ConsumeBracket();
1238 SkipUntil(tok::r_square);
1239 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1240 SourceLocation EndLoc = ConsumeBracket();
1241 Diag(BeginLoc, diag::err_attributes_not_allowed)
1242 << SourceRange(BeginLoc, EndLoc);
1245 llvm_unreachable("All cases handled above.");
1248 /// \brief We have found the opening square brackets of a C++11
1249 /// attribute-specifier in a location where an attribute is not permitted, but
1250 /// we know where the attributes ought to be written. Parse them anyway, and
1251 /// provide a fixit moving them to the right place.
1252 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1253 SourceLocation CorrectLocation) {
1254 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1255 Tok.is(tok::kw_alignas));
1257 // Consume the attributes.
1258 SourceLocation Loc = Tok.getLocation();
1259 ParseCXX11Attributes(Attrs);
1260 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1262 Diag(Loc, diag::err_attributes_not_allowed)
1263 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1264 << FixItHint::CreateRemoval(AttrRange);
1267 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
1268 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
1272 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs) {
1273 AttributeList *AttrList = attrs.getList();
1275 if (AttrList->isCXX11Attribute()) {
1276 Diag(AttrList->getLoc(), diag::err_attribute_not_type_attr)
1277 << AttrList->getName();
1278 AttrList->setInvalid();
1280 AttrList = AttrList->getNext();
1284 /// ParseDeclaration - Parse a full 'declaration', which consists of
1285 /// declaration-specifiers, some number of declarators, and a semicolon.
1286 /// 'Context' should be a Declarator::TheContext value. This returns the
1287 /// location of the semicolon in DeclEnd.
1289 /// declaration: [C99 6.7]
1290 /// block-declaration ->
1291 /// simple-declaration
1293 /// [C++] template-declaration
1294 /// [C++] namespace-definition
1295 /// [C++] using-directive
1296 /// [C++] using-declaration
1297 /// [C++11/C11] static_assert-declaration
1298 /// others... [FIXME]
1300 Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts,
1302 SourceLocation &DeclEnd,
1303 ParsedAttributesWithRange &attrs) {
1304 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1305 // Must temporarily exit the objective-c container scope for
1306 // parsing c none objective-c decls.
1307 ObjCDeclContextSwitch ObjCDC(*this);
1309 Decl *SingleDecl = nullptr;
1310 Decl *OwnedType = nullptr;
1311 switch (Tok.getKind()) {
1312 case tok::kw_template:
1313 case tok::kw_export:
1314 ProhibitAttributes(attrs);
1315 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
1317 case tok::kw_inline:
1318 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1319 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1320 ProhibitAttributes(attrs);
1321 SourceLocation InlineLoc = ConsumeToken();
1322 SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc);
1325 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs,
1327 case tok::kw_namespace:
1328 ProhibitAttributes(attrs);
1329 SingleDecl = ParseNamespace(Context, DeclEnd);
1332 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1333 DeclEnd, attrs, &OwnedType);
1335 case tok::kw_static_assert:
1336 case tok::kw__Static_assert:
1337 ProhibitAttributes(attrs);
1338 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1341 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true);
1344 // This routine returns a DeclGroup, if the thing we parsed only contains a
1345 // single decl, convert it now. Alias declarations can also declare a type;
1346 // include that too if it is present.
1347 return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType);
1350 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1351 /// declaration-specifiers init-declarator-list[opt] ';'
1352 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1353 /// init-declarator-list ';'
1354 ///[C90/C++]init-declarator-list ';' [TODO]
1355 /// [OMP] threadprivate-directive [TODO]
1357 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1358 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1360 /// If RequireSemi is false, this does not check for a ';' at the end of the
1361 /// declaration. If it is true, it checks for and eats it.
1363 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1364 /// of a simple-declaration. If we find that we are, we also parse the
1365 /// for-range-initializer, and place it here.
1366 Parser::DeclGroupPtrTy
1367 Parser::ParseSimpleDeclaration(StmtVector &Stmts, unsigned Context,
1368 SourceLocation &DeclEnd,
1369 ParsedAttributesWithRange &Attrs,
1370 bool RequireSemi, ForRangeInit *FRI) {
1371 // Parse the common declaration-specifiers piece.
1372 ParsingDeclSpec DS(*this);
1374 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1375 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1377 // If we had a free-standing type definition with a missing semicolon, we
1378 // may get this far before the problem becomes obvious.
1379 if (DS.hasTagDefinition() &&
1380 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1381 return DeclGroupPtrTy();
1383 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1384 // declaration-specifiers init-declarator-list[opt] ';'
1385 if (Tok.is(tok::semi)) {
1386 ProhibitAttributes(Attrs);
1387 DeclEnd = Tok.getLocation();
1388 if (RequireSemi) ConsumeToken();
1389 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1391 DS.complete(TheDecl);
1392 return Actions.ConvertDeclToDeclGroup(TheDecl);
1395 DS.takeAttributesFrom(Attrs);
1396 return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI);
1399 /// Returns true if this might be the start of a declarator, or a common typo
1400 /// for a declarator.
1401 bool Parser::MightBeDeclarator(unsigned Context) {
1402 switch (Tok.getKind()) {
1403 case tok::annot_cxxscope:
1404 case tok::annot_template_id:
1406 case tok::code_completion:
1407 case tok::coloncolon:
1409 case tok::kw___attribute:
1410 case tok::kw_operator:
1417 return getLangOpts().CPlusPlus;
1419 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1420 return Context == Declarator::MemberContext && getLangOpts().CPlusPlus11 &&
1421 NextToken().is(tok::l_square);
1423 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1424 return Context == Declarator::MemberContext || getLangOpts().CPlusPlus;
1426 case tok::identifier:
1427 switch (NextToken().getKind()) {
1428 case tok::code_completion:
1429 case tok::coloncolon:
1432 case tok::equalequal: // Might be a typo for '='.
1433 case tok::kw_alignas:
1435 case tok::kw___attribute:
1447 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1448 // and in block scope it's probably a label. Inside a class definition,
1449 // this is a bit-field.
1450 return Context == Declarator::MemberContext ||
1451 (getLangOpts().CPlusPlus && Context == Declarator::FileContext);
1453 case tok::identifier: // Possible virt-specifier.
1454 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1465 /// Skip until we reach something which seems like a sensible place to pick
1466 /// up parsing after a malformed declaration. This will sometimes stop sooner
1467 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1468 void Parser::SkipMalformedDecl() {
1470 switch (Tok.getKind()) {
1472 // Skip until matching }, then stop. We've probably skipped over
1473 // a malformed class or function definition or similar.
1475 SkipUntil(tok::r_brace);
1476 if (Tok.is(tok::comma) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try)) {
1477 // This declaration isn't over yet. Keep skipping.
1480 TryConsumeToken(tok::semi);
1485 SkipUntil(tok::r_square);
1490 SkipUntil(tok::r_paren);
1500 case tok::kw_inline:
1501 // 'inline namespace' at the start of a line is almost certainly
1502 // a good place to pick back up parsing, except in an Objective-C
1503 // @interface context.
1504 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1505 (!ParsingInObjCContainer || CurParsedObjCImpl))
1509 case tok::kw_namespace:
1510 // 'namespace' at the start of a line is almost certainly a good
1511 // place to pick back up parsing, except in an Objective-C
1512 // @interface context.
1513 if (Tok.isAtStartOfLine() &&
1514 (!ParsingInObjCContainer || CurParsedObjCImpl))
1519 // @end is very much like } in Objective-C contexts.
1520 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1521 ParsingInObjCContainer)
1527 // - and + probably start new method declarations in Objective-C contexts.
1528 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1533 case tok::annot_module_begin:
1534 case tok::annot_module_end:
1535 case tok::annot_module_include:
1546 /// ParseDeclGroup - Having concluded that this is either a function
1547 /// definition or a group of object declarations, actually parse the
1549 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1551 bool AllowFunctionDefinitions,
1552 SourceLocation *DeclEnd,
1553 ForRangeInit *FRI) {
1554 // Parse the first declarator.
1555 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
1558 // Bail out if the first declarator didn't seem well-formed.
1559 if (!D.hasName() && !D.mayOmitIdentifier()) {
1560 SkipMalformedDecl();
1561 return DeclGroupPtrTy();
1564 // Save late-parsed attributes for now; they need to be parsed in the
1565 // appropriate function scope after the function Decl has been constructed.
1566 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1567 LateParsedAttrList LateParsedAttrs(true);
1568 if (D.isFunctionDeclarator())
1569 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1571 // Check to see if we have a function *definition* which must have a body.
1572 if (D.isFunctionDeclarator() &&
1573 // Look at the next token to make sure that this isn't a function
1574 // declaration. We have to check this because __attribute__ might be the
1575 // start of a function definition in GCC-extended K&R C.
1576 !isDeclarationAfterDeclarator()) {
1578 if (AllowFunctionDefinitions) {
1579 if (isStartOfFunctionDefinition(D)) {
1580 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1581 Diag(Tok, diag::err_function_declared_typedef);
1583 // Recover by treating the 'typedef' as spurious.
1584 DS.ClearStorageClassSpecs();
1588 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1589 return Actions.ConvertDeclToDeclGroup(TheDecl);
1592 if (isDeclarationSpecifier()) {
1593 // If there is an invalid declaration specifier right after the function
1594 // prototype, then we must be in a missing semicolon case where this isn't
1595 // actually a body. Just fall through into the code that handles it as a
1596 // prototype, and let the top-level code handle the erroneous declspec
1597 // where it would otherwise expect a comma or semicolon.
1599 Diag(Tok, diag::err_expected_fn_body);
1600 SkipUntil(tok::semi);
1601 return DeclGroupPtrTy();
1604 if (Tok.is(tok::l_brace)) {
1605 Diag(Tok, diag::err_function_definition_not_allowed);
1606 SkipMalformedDecl();
1607 return DeclGroupPtrTy();
1612 if (ParseAsmAttributesAfterDeclarator(D))
1613 return DeclGroupPtrTy();
1615 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1616 // must parse and analyze the for-range-initializer before the declaration is
1619 // Handle the Objective-C for-in loop variable similarly, although we
1620 // don't need to parse the container in advance.
1621 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
1622 bool IsForRangeLoop = false;
1623 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
1624 IsForRangeLoop = true;
1625 if (Tok.is(tok::l_brace))
1626 FRI->RangeExpr = ParseBraceInitializer();
1628 FRI->RangeExpr = ParseExpression();
1631 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1633 Actions.ActOnCXXForRangeDecl(ThisDecl);
1634 Actions.FinalizeDeclaration(ThisDecl);
1635 D.complete(ThisDecl);
1636 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
1639 SmallVector<Decl *, 8> DeclsInGroup;
1640 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
1641 D, ParsedTemplateInfo(), FRI);
1642 if (LateParsedAttrs.size() > 0)
1643 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
1644 D.complete(FirstDecl);
1646 DeclsInGroup.push_back(FirstDecl);
1648 bool ExpectSemi = Context != Declarator::ForContext;
1650 // If we don't have a comma, it is either the end of the list (a ';') or an
1652 SourceLocation CommaLoc;
1653 while (TryConsumeToken(tok::comma, CommaLoc)) {
1654 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
1655 // This comma was followed by a line-break and something which can't be
1656 // the start of a declarator. The comma was probably a typo for a
1658 Diag(CommaLoc, diag::err_expected_semi_declaration)
1659 << FixItHint::CreateReplacement(CommaLoc, ";");
1664 // Parse the next declarator.
1666 D.setCommaLoc(CommaLoc);
1668 // Accept attributes in an init-declarator. In the first declarator in a
1669 // declaration, these would be part of the declspec. In subsequent
1670 // declarators, they become part of the declarator itself, so that they
1671 // don't apply to declarators after *this* one. Examples:
1672 // short __attribute__((common)) var; -> declspec
1673 // short var __attribute__((common)); -> declarator
1674 // short x, __attribute__((common)) var; -> declarator
1675 MaybeParseGNUAttributes(D);
1678 if (!D.isInvalidType()) {
1679 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
1680 D.complete(ThisDecl);
1682 DeclsInGroup.push_back(ThisDecl);
1687 *DeclEnd = Tok.getLocation();
1690 ExpectAndConsumeSemi(Context == Declarator::FileContext
1691 ? diag::err_invalid_token_after_toplevel_declarator
1692 : diag::err_expected_semi_declaration)) {
1693 // Okay, there was no semicolon and one was expected. If we see a
1694 // declaration specifier, just assume it was missing and continue parsing.
1695 // Otherwise things are very confused and we skip to recover.
1696 if (!isDeclarationSpecifier()) {
1697 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1698 TryConsumeToken(tok::semi);
1702 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
1705 /// Parse an optional simple-asm-expr and attributes, and attach them to a
1706 /// declarator. Returns true on an error.
1707 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
1708 // If a simple-asm-expr is present, parse it.
1709 if (Tok.is(tok::kw_asm)) {
1711 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1712 if (AsmLabel.isInvalid()) {
1713 SkipUntil(tok::semi, StopBeforeMatch);
1717 D.setAsmLabel(AsmLabel.get());
1721 MaybeParseGNUAttributes(D);
1725 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
1726 /// declarator'. This method parses the remainder of the declaration
1727 /// (including any attributes or initializer, among other things) and
1728 /// finalizes the declaration.
1730 /// init-declarator: [C99 6.7]
1732 /// declarator '=' initializer
1733 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
1734 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
1735 /// [C++] declarator initializer[opt]
1737 /// [C++] initializer:
1738 /// [C++] '=' initializer-clause
1739 /// [C++] '(' expression-list ')'
1740 /// [C++0x] '=' 'default' [TODO]
1741 /// [C++0x] '=' 'delete'
1742 /// [C++0x] braced-init-list
1744 /// According to the standard grammar, =default and =delete are function
1745 /// definitions, but that definitely doesn't fit with the parser here.
1747 Decl *Parser::ParseDeclarationAfterDeclarator(
1748 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
1749 if (ParseAsmAttributesAfterDeclarator(D))
1752 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
1755 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
1756 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
1757 // Inform the current actions module that we just parsed this declarator.
1758 Decl *ThisDecl = nullptr;
1759 switch (TemplateInfo.Kind) {
1760 case ParsedTemplateInfo::NonTemplate:
1761 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1764 case ParsedTemplateInfo::Template:
1765 case ParsedTemplateInfo::ExplicitSpecialization: {
1766 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
1767 *TemplateInfo.TemplateParams,
1769 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
1770 // Re-direct this decl to refer to the templated decl so that we can
1772 ThisDecl = VT->getTemplatedDecl();
1775 case ParsedTemplateInfo::ExplicitInstantiation: {
1776 if (Tok.is(tok::semi)) {
1777 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
1778 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
1779 if (ThisRes.isInvalid()) {
1780 SkipUntil(tok::semi, StopBeforeMatch);
1783 ThisDecl = ThisRes.get();
1785 // FIXME: This check should be for a variable template instantiation only.
1787 // Check that this is a valid instantiation
1788 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
1789 // If the declarator-id is not a template-id, issue a diagnostic and
1790 // recover by ignoring the 'template' keyword.
1791 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1792 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1793 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1795 SourceLocation LAngleLoc =
1796 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1797 Diag(D.getIdentifierLoc(),
1798 diag::err_explicit_instantiation_with_definition)
1799 << SourceRange(TemplateInfo.TemplateLoc)
1800 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1802 // Recover as if it were an explicit specialization.
1803 TemplateParameterLists FakedParamLists;
1804 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1805 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr,
1809 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
1816 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
1818 // Parse declarator '=' initializer.
1819 // If a '==' or '+=' is found, suggest a fixit to '='.
1820 if (isTokenEqualOrEqualTypo()) {
1821 SourceLocation EqualLoc = ConsumeToken();
1823 if (Tok.is(tok::kw_delete)) {
1824 if (D.isFunctionDeclarator())
1825 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1828 Diag(ConsumeToken(), diag::err_deleted_non_function);
1829 } else if (Tok.is(tok::kw_default)) {
1830 if (D.isFunctionDeclarator())
1831 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1834 Diag(ConsumeToken(), diag::err_default_special_members);
1836 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1838 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1841 if (Tok.is(tok::code_completion)) {
1842 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
1843 Actions.FinalizeDeclaration(ThisDecl);
1848 ExprResult Init(ParseInitializer());
1850 // If this is the only decl in (possibly) range based for statement,
1851 // our best guess is that the user meant ':' instead of '='.
1852 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
1853 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
1854 << FixItHint::CreateReplacement(EqualLoc, ":");
1855 // We are trying to stop parser from looking for ';' in this for
1856 // statement, therefore preventing spurious errors to be issued.
1857 FRI->ColonLoc = EqualLoc;
1859 FRI->RangeExpr = Init;
1862 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1863 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1867 if (Init.isInvalid()) {
1868 SmallVector<tok::TokenKind, 2> StopTokens;
1869 StopTokens.push_back(tok::comma);
1870 if (D.getContext() == Declarator::ForContext)
1871 StopTokens.push_back(tok::r_paren);
1872 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
1873 Actions.ActOnInitializerError(ThisDecl);
1875 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
1876 /*DirectInit=*/false, TypeContainsAuto);
1878 } else if (Tok.is(tok::l_paren)) {
1879 // Parse C++ direct initializer: '(' expression-list ')'
1880 BalancedDelimiterTracker T(*this, tok::l_paren);
1884 CommaLocsTy CommaLocs;
1886 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1888 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1891 if (ParseExpressionList(Exprs, CommaLocs)) {
1892 Actions.ActOnInitializerError(ThisDecl);
1893 SkipUntil(tok::r_paren, StopAtSemi);
1895 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1896 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1903 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
1904 "Unexpected number of commas!");
1906 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1907 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1911 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
1912 T.getCloseLocation(),
1914 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
1915 /*DirectInit=*/true, TypeContainsAuto);
1917 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
1918 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
1919 // Parse C++0x braced-init-list.
1920 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1922 if (D.getCXXScopeSpec().isSet()) {
1924 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1927 ExprResult Init(ParseBraceInitializer());
1929 if (D.getCXXScopeSpec().isSet()) {
1930 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1934 if (Init.isInvalid()) {
1935 Actions.ActOnInitializerError(ThisDecl);
1937 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
1938 /*DirectInit=*/true, TypeContainsAuto);
1941 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
1944 Actions.FinalizeDeclaration(ThisDecl);
1949 /// ParseSpecifierQualifierList
1950 /// specifier-qualifier-list:
1951 /// type-specifier specifier-qualifier-list[opt]
1952 /// type-qualifier specifier-qualifier-list[opt]
1953 /// [GNU] attributes specifier-qualifier-list[opt]
1955 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
1956 DeclSpecContext DSC) {
1957 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
1958 /// parse declaration-specifiers and complain about extra stuff.
1959 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
1960 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
1962 // Validate declspec for type-name.
1963 unsigned Specs = DS.getParsedSpecifiers();
1964 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
1965 Diag(Tok, diag::err_expected_type);
1966 DS.SetTypeSpecError();
1967 } else if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
1968 !DS.hasAttributes()) {
1969 Diag(Tok, diag::err_typename_requires_specqual);
1970 if (!DS.hasTypeSpecifier())
1971 DS.SetTypeSpecError();
1974 // Issue diagnostic and remove storage class if present.
1975 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
1976 if (DS.getStorageClassSpecLoc().isValid())
1977 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
1979 Diag(DS.getThreadStorageClassSpecLoc(),
1980 diag::err_typename_invalid_storageclass);
1981 DS.ClearStorageClassSpecs();
1984 // Issue diagnostic and remove function specfier if present.
1985 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
1986 if (DS.isInlineSpecified())
1987 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
1988 if (DS.isVirtualSpecified())
1989 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
1990 if (DS.isExplicitSpecified())
1991 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
1992 DS.ClearFunctionSpecs();
1995 // Issue diagnostic and remove constexpr specfier if present.
1996 if (DS.isConstexprSpecified()) {
1997 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
1998 DS.ClearConstexprSpec();
2002 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2003 /// specified token is valid after the identifier in a declarator which
2004 /// immediately follows the declspec. For example, these things are valid:
2006 /// int x [ 4]; // direct-declarator
2007 /// int x ( int y); // direct-declarator
2008 /// int(int x ) // direct-declarator
2009 /// int x ; // simple-declaration
2010 /// int x = 17; // init-declarator-list
2011 /// int x , y; // init-declarator-list
2012 /// int x __asm__ ("foo"); // init-declarator-list
2013 /// int x : 4; // struct-declarator
2014 /// int x { 5}; // C++'0x unified initializers
2016 /// This is not, because 'x' does not immediately follow the declspec (though
2017 /// ')' happens to be valid anyway).
2020 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2021 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
2022 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
2023 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
2027 /// ParseImplicitInt - This method is called when we have an non-typename
2028 /// identifier in a declspec (which normally terminates the decl spec) when
2029 /// the declspec has no type specifier. In this case, the declspec is either
2030 /// malformed or is "implicit int" (in K&R and C89).
2032 /// This method handles diagnosing this prettily and returns false if the
2033 /// declspec is done being processed. If it recovers and thinks there may be
2034 /// other pieces of declspec after it, it returns true.
2036 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2037 const ParsedTemplateInfo &TemplateInfo,
2038 AccessSpecifier AS, DeclSpecContext DSC,
2039 ParsedAttributesWithRange &Attrs) {
2040 assert(Tok.is(tok::identifier) && "should have identifier");
2042 SourceLocation Loc = Tok.getLocation();
2043 // If we see an identifier that is not a type name, we normally would
2044 // parse it as the identifer being declared. However, when a typename
2045 // is typo'd or the definition is not included, this will incorrectly
2046 // parse the typename as the identifier name and fall over misparsing
2047 // later parts of the diagnostic.
2049 // As such, we try to do some look-ahead in cases where this would
2050 // otherwise be an "implicit-int" case to see if this is invalid. For
2051 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2052 // an identifier with implicit int, we'd get a parse error because the
2053 // next token is obviously invalid for a type. Parse these as a case
2054 // with an invalid type specifier.
2055 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2057 // Since we know that this either implicit int (which is rare) or an
2058 // error, do lookahead to try to do better recovery. This never applies
2059 // within a type specifier. Outside of C++, we allow this even if the
2060 // language doesn't "officially" support implicit int -- we support
2061 // implicit int as an extension in C99 and C11.
2062 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2063 isValidAfterIdentifierInDeclarator(NextToken())) {
2064 // If this token is valid for implicit int, e.g. "static x = 4", then
2065 // we just avoid eating the identifier, so it will be parsed as the
2066 // identifier in the declarator.
2070 if (getLangOpts().CPlusPlus &&
2071 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2072 // Don't require a type specifier if we have the 'auto' storage class
2073 // specifier in C++98 -- we'll promote it to a type specifier.
2075 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2079 // Otherwise, if we don't consume this token, we are going to emit an
2080 // error anyway. Try to recover from various common problems. Check
2081 // to see if this was a reference to a tag name without a tag specified.
2082 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2084 // C++ doesn't need this, and isTagName doesn't take SS.
2085 if (SS == nullptr) {
2086 const char *TagName = nullptr, *FixitTagName = nullptr;
2087 tok::TokenKind TagKind = tok::unknown;
2089 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2091 case DeclSpec::TST_enum:
2092 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2093 case DeclSpec::TST_union:
2094 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2095 case DeclSpec::TST_struct:
2096 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2097 case DeclSpec::TST_interface:
2098 TagName="__interface"; FixitTagName = "__interface ";
2099 TagKind=tok::kw___interface;break;
2100 case DeclSpec::TST_class:
2101 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2105 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2106 LookupResult R(Actions, TokenName, SourceLocation(),
2107 Sema::LookupOrdinaryName);
2109 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2110 << TokenName << TagName << getLangOpts().CPlusPlus
2111 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2113 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2114 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2116 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2117 << TokenName << TagName;
2120 // Parse this as a tag as if the missing tag were present.
2121 if (TagKind == tok::kw_enum)
2122 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
2124 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2125 /*EnteringContext*/ false, DSC_normal, Attrs);
2130 // Determine whether this identifier could plausibly be the name of something
2131 // being declared (with a missing type).
2132 if (!isTypeSpecifier(DSC) &&
2133 (!SS || DSC == DSC_top_level || DSC == DSC_class)) {
2134 // Look ahead to the next token to try to figure out what this declaration
2135 // was supposed to be.
2136 switch (NextToken().getKind()) {
2137 case tok::l_paren: {
2138 // static x(4); // 'x' is not a type
2139 // x(int n); // 'x' is not a type
2140 // x (*p)[]; // 'x' is a type
2142 // Since we're in an error case, we can afford to perform a tentative
2143 // parse to determine which case we're in.
2144 TentativeParsingAction PA(*this);
2146 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2149 if (TPR != TPResult::False) {
2150 // The identifier is followed by a parenthesized declarator.
2151 // It's supposed to be a type.
2155 // If we're in a context where we could be declaring a constructor,
2156 // check whether this is a constructor declaration with a bogus name.
2157 if (DSC == DSC_class || (DSC == DSC_top_level && SS)) {
2158 IdentifierInfo *II = Tok.getIdentifierInfo();
2159 if (Actions.isCurrentClassNameTypo(II, SS)) {
2160 Diag(Loc, diag::err_constructor_bad_name)
2161 << Tok.getIdentifierInfo() << II
2162 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2163 Tok.setIdentifierInfo(II);
2174 // This looks like a variable or function declaration. The type is
2175 // probably missing. We're done parsing decl-specifiers.
2177 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2181 // This is probably supposed to be a type. This includes cases like:
2183 // struct S { unsinged : 4; };
2188 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2189 // and attempt to recover.
2191 IdentifierInfo *II = Tok.getIdentifierInfo();
2192 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2193 getLangOpts().CPlusPlus &&
2194 NextToken().is(tok::less));
2196 // The action has suggested that the type T could be used. Set that as
2197 // the type in the declaration specifiers, consume the would-be type
2198 // name token, and we're done.
2199 const char *PrevSpec;
2201 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2202 Actions.getASTContext().getPrintingPolicy());
2203 DS.SetRangeEnd(Tok.getLocation());
2205 // There may be other declaration specifiers after this.
2207 } else if (II != Tok.getIdentifierInfo()) {
2208 // If no type was suggested, the correction is to a keyword
2209 Tok.setKind(II->getTokenID());
2210 // There may be other declaration specifiers after this.
2214 // Otherwise, the action had no suggestion for us. Mark this as an error.
2215 DS.SetTypeSpecError();
2216 DS.SetRangeEnd(Tok.getLocation());
2219 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2220 // avoid rippling error messages on subsequent uses of the same type,
2221 // could be useful if #include was forgotten.
2225 /// \brief Determine the declaration specifier context from the declarator
2228 /// \param Context the declarator context, which is one of the
2229 /// Declarator::TheContext enumerator values.
2230 Parser::DeclSpecContext
2231 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
2232 if (Context == Declarator::MemberContext)
2234 if (Context == Declarator::FileContext)
2235 return DSC_top_level;
2236 if (Context == Declarator::TemplateTypeArgContext)
2237 return DSC_template_type_arg;
2238 if (Context == Declarator::TrailingReturnContext)
2239 return DSC_trailing;
2240 if (Context == Declarator::AliasDeclContext ||
2241 Context == Declarator::AliasTemplateContext)
2242 return DSC_alias_declaration;
2246 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2248 /// FIXME: Simply returns an alignof() expression if the argument is a
2249 /// type. Ideally, the type should be propagated directly into Sema.
2252 /// [C11] constant-expression
2253 /// [C++0x] type-id ...[opt]
2254 /// [C++0x] assignment-expression ...[opt]
2255 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2256 SourceLocation &EllipsisLoc) {
2258 if (isTypeIdInParens()) {
2259 SourceLocation TypeLoc = Tok.getLocation();
2260 ParsedType Ty = ParseTypeName().get();
2261 SourceRange TypeRange(Start, Tok.getLocation());
2262 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2263 Ty.getAsOpaquePtr(), TypeRange);
2265 ER = ParseConstantExpression();
2267 if (getLangOpts().CPlusPlus11)
2268 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2273 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2274 /// attribute to Attrs.
2276 /// alignment-specifier:
2277 /// [C11] '_Alignas' '(' type-id ')'
2278 /// [C11] '_Alignas' '(' constant-expression ')'
2279 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2280 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2281 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2282 SourceLocation *EndLoc) {
2283 assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) &&
2284 "Not an alignment-specifier!");
2286 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2287 SourceLocation KWLoc = ConsumeToken();
2289 BalancedDelimiterTracker T(*this, tok::l_paren);
2290 if (T.expectAndConsume())
2293 SourceLocation EllipsisLoc;
2294 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2295 if (ArgExpr.isInvalid()) {
2302 *EndLoc = T.getCloseLocation();
2304 ArgsVector ArgExprs;
2305 ArgExprs.push_back(ArgExpr.get());
2306 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2307 AttributeList::AS_Keyword, EllipsisLoc);
2310 /// Determine whether we're looking at something that might be a declarator
2311 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2312 /// diagnose a missing semicolon after a prior tag definition in the decl
2315 /// \return \c true if an error occurred and this can't be any kind of
2318 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2319 DeclSpecContext DSContext,
2320 LateParsedAttrList *LateAttrs) {
2321 assert(DS.hasTagDefinition() && "shouldn't call this");
2323 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2325 if (getLangOpts().CPlusPlus &&
2326 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
2327 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id)) &&
2328 TryAnnotateCXXScopeToken(EnteringContext)) {
2329 SkipMalformedDecl();
2333 bool HasScope = Tok.is(tok::annot_cxxscope);
2334 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2335 Token AfterScope = HasScope ? NextToken() : Tok;
2337 // Determine whether the following tokens could possibly be a
2339 bool MightBeDeclarator = true;
2340 if (Tok.is(tok::kw_typename) || Tok.is(tok::annot_typename)) {
2341 // A declarator-id can't start with 'typename'.
2342 MightBeDeclarator = false;
2343 } else if (AfterScope.is(tok::annot_template_id)) {
2344 // If we have a type expressed as a template-id, this cannot be a
2345 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2346 TemplateIdAnnotation *Annot =
2347 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2348 if (Annot->Kind == TNK_Type_template)
2349 MightBeDeclarator = false;
2350 } else if (AfterScope.is(tok::identifier)) {
2351 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2353 // These tokens cannot come after the declarator-id in a
2354 // simple-declaration, and are likely to come after a type-specifier.
2355 if (Next.is(tok::star) || Next.is(tok::amp) || Next.is(tok::ampamp) ||
2356 Next.is(tok::identifier) || Next.is(tok::annot_cxxscope) ||
2357 Next.is(tok::coloncolon)) {
2358 // Missing a semicolon.
2359 MightBeDeclarator = false;
2360 } else if (HasScope) {
2361 // If the declarator-id has a scope specifier, it must redeclare a
2362 // previously-declared entity. If that's a type (and this is not a
2363 // typedef), that's an error.
2365 Actions.RestoreNestedNameSpecifierAnnotation(
2366 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2367 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2368 Sema::NameClassification Classification = Actions.ClassifyName(
2369 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2370 /*IsAddressOfOperand*/false);
2371 switch (Classification.getKind()) {
2372 case Sema::NC_Error:
2373 SkipMalformedDecl();
2376 case Sema::NC_Keyword:
2377 case Sema::NC_NestedNameSpecifier:
2378 llvm_unreachable("typo correction and nested name specifiers not "
2382 case Sema::NC_TypeTemplate:
2383 // Not a previously-declared non-type entity.
2384 MightBeDeclarator = false;
2387 case Sema::NC_Unknown:
2388 case Sema::NC_Expression:
2389 case Sema::NC_VarTemplate:
2390 case Sema::NC_FunctionTemplate:
2391 // Might be a redeclaration of a prior entity.
2397 if (MightBeDeclarator)
2400 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2401 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()),
2402 diag::err_expected_after)
2403 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2405 // Try to recover from the typo, by dropping the tag definition and parsing
2406 // the problematic tokens as a type.
2408 // FIXME: Split the DeclSpec into pieces for the standalone
2409 // declaration and pieces for the following declaration, instead
2410 // of assuming that all the other pieces attach to new declaration,
2411 // and call ParsedFreeStandingDeclSpec as appropriate.
2412 DS.ClearTypeSpecType();
2413 ParsedTemplateInfo NotATemplate;
2414 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2418 /// ParseDeclarationSpecifiers
2419 /// declaration-specifiers: [C99 6.7]
2420 /// storage-class-specifier declaration-specifiers[opt]
2421 /// type-specifier declaration-specifiers[opt]
2422 /// [C99] function-specifier declaration-specifiers[opt]
2423 /// [C11] alignment-specifier declaration-specifiers[opt]
2424 /// [GNU] attributes declaration-specifiers[opt]
2425 /// [Clang] '__module_private__' declaration-specifiers[opt]
2427 /// storage-class-specifier: [C99 6.7.1]
2434 /// [C++11] 'thread_local'
2435 /// [C11] '_Thread_local'
2436 /// [GNU] '__thread'
2437 /// function-specifier: [C99 6.7.4]
2440 /// [C++] 'explicit'
2441 /// [OpenCL] '__kernel'
2442 /// 'friend': [C++ dcl.friend]
2443 /// 'constexpr': [C++0x dcl.constexpr]
2446 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2447 const ParsedTemplateInfo &TemplateInfo,
2449 DeclSpecContext DSContext,
2450 LateParsedAttrList *LateAttrs) {
2451 if (DS.getSourceRange().isInvalid()) {
2452 DS.SetRangeStart(Tok.getLocation());
2453 DS.SetRangeEnd(Tok.getLocation());
2456 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2457 bool AttrsLastTime = false;
2458 ParsedAttributesWithRange attrs(AttrFactory);
2459 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
2461 bool isInvalid = false;
2462 const char *PrevSpec = nullptr;
2463 unsigned DiagID = 0;
2465 SourceLocation Loc = Tok.getLocation();
2467 switch (Tok.getKind()) {
2471 ProhibitAttributes(attrs);
2473 // Reject C++11 attributes that appertain to decl specifiers as
2474 // we don't support any C++11 attributes that appertain to decl
2475 // specifiers. This also conforms to what g++ 4.8 is doing.
2476 ProhibitCXX11Attributes(attrs);
2478 DS.takeAttributesFrom(attrs);
2481 // If this is not a declaration specifier token, we're done reading decl
2482 // specifiers. First verify that DeclSpec's are consistent.
2483 DS.Finish(Diags, PP, Policy);
2487 case tok::kw_alignas:
2488 if (!getLangOpts().CPlusPlus11 || !isCXX11AttributeSpecifier())
2489 goto DoneWithDeclSpec;
2491 ProhibitAttributes(attrs);
2492 // FIXME: It would be good to recover by accepting the attributes,
2493 // but attempting to do that now would cause serious
2494 // madness in terms of diagnostics.
2496 attrs.Range = SourceRange();
2498 ParseCXX11Attributes(attrs);
2499 AttrsLastTime = true;
2502 case tok::code_completion: {
2503 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2504 if (DS.hasTypeSpecifier()) {
2505 bool AllowNonIdentifiers
2506 = (getCurScope()->getFlags() & (Scope::ControlScope |
2508 Scope::TemplateParamScope |
2509 Scope::FunctionPrototypeScope |
2510 Scope::AtCatchScope)) == 0;
2511 bool AllowNestedNameSpecifiers
2512 = DSContext == DSC_top_level ||
2513 (DSContext == DSC_class && DS.isFriendSpecified());
2515 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
2516 AllowNonIdentifiers,
2517 AllowNestedNameSpecifiers);
2518 return cutOffParsing();
2521 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
2522 CCC = Sema::PCC_LocalDeclarationSpecifiers;
2523 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
2524 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
2525 : Sema::PCC_Template;
2526 else if (DSContext == DSC_class)
2527 CCC = Sema::PCC_Class;
2528 else if (CurParsedObjCImpl)
2529 CCC = Sema::PCC_ObjCImplementation;
2531 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
2532 return cutOffParsing();
2535 case tok::coloncolon: // ::foo::bar
2536 // C++ scope specifier. Annotate and loop, or bail out on error.
2537 if (TryAnnotateCXXScopeToken(EnteringContext)) {
2538 if (!DS.hasTypeSpecifier())
2539 DS.SetTypeSpecError();
2540 goto DoneWithDeclSpec;
2542 if (Tok.is(tok::coloncolon)) // ::new or ::delete
2543 goto DoneWithDeclSpec;
2546 case tok::annot_cxxscope: {
2547 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
2548 goto DoneWithDeclSpec;
2551 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2552 Tok.getAnnotationRange(),
2555 // We are looking for a qualified typename.
2556 Token Next = NextToken();
2557 if (Next.is(tok::annot_template_id) &&
2558 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
2559 ->Kind == TNK_Type_template) {
2560 // We have a qualified template-id, e.g., N::A<int>
2562 // C++ [class.qual]p2:
2563 // In a lookup in which the constructor is an acceptable lookup
2564 // result and the nested-name-specifier nominates a class C:
2566 // - if the name specified after the
2567 // nested-name-specifier, when looked up in C, is the
2568 // injected-class-name of C (Clause 9), or
2570 // - if the name specified after the nested-name-specifier
2571 // is the same as the identifier or the
2572 // simple-template-id's template-name in the last
2573 // component of the nested-name-specifier,
2575 // the name is instead considered to name the constructor of
2578 // Thus, if the template-name is actually the constructor
2579 // name, then the code is ill-formed; this interpretation is
2580 // reinforced by the NAD status of core issue 635.
2581 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
2582 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2584 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2585 if (isConstructorDeclarator(/*Unqualified*/false)) {
2586 // The user meant this to be an out-of-line constructor
2587 // definition, but template arguments are not allowed
2588 // there. Just allow this as a constructor; we'll
2589 // complain about it later.
2590 goto DoneWithDeclSpec;
2593 // The user meant this to name a type, but it actually names
2594 // a constructor with some extraneous template
2595 // arguments. Complain, then parse it as a type as the user
2597 Diag(TemplateId->TemplateNameLoc,
2598 diag::err_out_of_line_template_id_names_constructor)
2599 << TemplateId->Name;
2602 DS.getTypeSpecScope() = SS;
2603 ConsumeToken(); // The C++ scope.
2604 assert(Tok.is(tok::annot_template_id) &&
2605 "ParseOptionalCXXScopeSpecifier not working");
2606 AnnotateTemplateIdTokenAsType();
2610 if (Next.is(tok::annot_typename)) {
2611 DS.getTypeSpecScope() = SS;
2612 ConsumeToken(); // The C++ scope.
2613 if (Tok.getAnnotationValue()) {
2614 ParsedType T = getTypeAnnotation(Tok);
2615 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
2616 Tok.getAnnotationEndLoc(),
2617 PrevSpec, DiagID, T, Policy);
2622 DS.SetTypeSpecError();
2623 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2624 ConsumeToken(); // The typename
2627 if (Next.isNot(tok::identifier))
2628 goto DoneWithDeclSpec;
2630 // If we're in a context where the identifier could be a class name,
2631 // check whether this is a constructor declaration.
2632 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2633 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
2635 if (isConstructorDeclarator(/*Unqualified*/false))
2636 goto DoneWithDeclSpec;
2638 // As noted in C++ [class.qual]p2 (cited above), when the name
2639 // of the class is qualified in a context where it could name
2640 // a constructor, its a constructor name. However, we've
2641 // looked at the declarator, and the user probably meant this
2642 // to be a type. Complain that it isn't supposed to be treated
2643 // as a type, then proceed to parse it as a type.
2644 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
2645 << Next.getIdentifierInfo();
2648 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
2651 false, false, ParsedType(),
2652 /*IsCtorOrDtorName=*/false,
2653 /*NonTrivialSourceInfo=*/true);
2655 // If the referenced identifier is not a type, then this declspec is
2656 // erroneous: We already checked about that it has no type specifier, and
2657 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
2660 ConsumeToken(); // Eat the scope spec so the identifier is current.
2661 ParsedAttributesWithRange Attrs(AttrFactory);
2662 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
2663 if (!Attrs.empty()) {
2664 AttrsLastTime = true;
2665 attrs.takeAllFrom(Attrs);
2669 goto DoneWithDeclSpec;
2672 DS.getTypeSpecScope() = SS;
2673 ConsumeToken(); // The C++ scope.
2675 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2676 DiagID, TypeRep, Policy);
2680 DS.SetRangeEnd(Tok.getLocation());
2681 ConsumeToken(); // The typename.
2686 case tok::annot_typename: {
2687 // If we've previously seen a tag definition, we were almost surely
2688 // missing a semicolon after it.
2689 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
2690 goto DoneWithDeclSpec;
2692 if (Tok.getAnnotationValue()) {
2693 ParsedType T = getTypeAnnotation(Tok);
2694 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2697 DS.SetTypeSpecError();
2702 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2703 ConsumeToken(); // The typename
2705 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2706 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2707 // Objective-C interface.
2708 if (Tok.is(tok::less) && getLangOpts().ObjC1)
2709 ParseObjCProtocolQualifiers(DS);
2714 case tok::kw___is_signed:
2715 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
2716 // typically treats it as a trait. If we see __is_signed as it appears
2717 // in libstdc++, e.g.,
2719 // static const bool __is_signed;
2721 // then treat __is_signed as an identifier rather than as a keyword.
2722 if (DS.getTypeSpecType() == TST_bool &&
2723 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
2724 DS.getStorageClassSpec() == DeclSpec::SCS_static)
2725 TryKeywordIdentFallback(true);
2727 // We're done with the declaration-specifiers.
2728 goto DoneWithDeclSpec;
2731 case tok::kw_decltype:
2732 case tok::identifier: {
2733 // This identifier can only be a typedef name if we haven't already seen
2734 // a type-specifier. Without this check we misparse:
2735 // typedef int X; struct Y { short X; }; as 'short int'.
2736 if (DS.hasTypeSpecifier())
2737 goto DoneWithDeclSpec;
2739 // In C++, check to see if this is a scope specifier like foo::bar::, if
2740 // so handle it as such. This is important for ctor parsing.
2741 if (getLangOpts().CPlusPlus) {
2742 if (TryAnnotateCXXScopeToken(EnteringContext)) {
2743 DS.SetTypeSpecError();
2744 goto DoneWithDeclSpec;
2746 if (!Tok.is(tok::identifier))
2750 // Check for need to substitute AltiVec keyword tokens.
2751 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
2754 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
2755 // allow the use of a typedef name as a type specifier.
2756 if (DS.isTypeAltiVecVector())
2757 goto DoneWithDeclSpec;
2759 ParsedType TypeRep =
2760 Actions.getTypeName(*Tok.getIdentifierInfo(),
2761 Tok.getLocation(), getCurScope());
2763 // MSVC: If we weren't able to parse a default template argument, and it's
2764 // just a simple identifier, create a DependentNameType. This will allow us
2765 // to defer the name lookup to template instantiation time, as long we forge a
2766 // NestedNameSpecifier for the current context.
2767 if (!TypeRep && DSContext == DSC_template_type_arg &&
2768 getLangOpts().MSVCCompat && getCurScope()->isTemplateParamScope()) {
2769 TypeRep = Actions.ActOnDelayedDefaultTemplateArg(
2770 *Tok.getIdentifierInfo(), Tok.getLocation());
2773 // If this is not a typedef name, don't parse it as part of the declspec,
2774 // it must be an implicit int or an error.
2776 ParsedAttributesWithRange Attrs(AttrFactory);
2777 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
2778 if (!Attrs.empty()) {
2779 AttrsLastTime = true;
2780 attrs.takeAllFrom(Attrs);
2784 goto DoneWithDeclSpec;
2787 // If we're in a context where the identifier could be a class name,
2788 // check whether this is a constructor declaration.
2789 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2790 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
2791 isConstructorDeclarator(/*Unqualified*/true))
2792 goto DoneWithDeclSpec;
2794 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2795 DiagID, TypeRep, Policy);
2799 DS.SetRangeEnd(Tok.getLocation());
2800 ConsumeToken(); // The identifier
2802 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2803 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2804 // Objective-C interface.
2805 if (Tok.is(tok::less) && getLangOpts().ObjC1)
2806 ParseObjCProtocolQualifiers(DS);
2808 // Need to support trailing type qualifiers (e.g. "id<p> const").
2809 // If a type specifier follows, it will be diagnosed elsewhere.
2814 case tok::annot_template_id: {
2815 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2816 if (TemplateId->Kind != TNK_Type_template) {
2817 // This template-id does not refer to a type name, so we're
2818 // done with the type-specifiers.
2819 goto DoneWithDeclSpec;
2822 // If we're in a context where the template-id could be a
2823 // constructor name or specialization, check whether this is a
2824 // constructor declaration.
2825 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2826 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
2827 isConstructorDeclarator(TemplateId->SS.isEmpty()))
2828 goto DoneWithDeclSpec;
2830 // Turn the template-id annotation token into a type annotation
2831 // token, then try again to parse it as a type-specifier.
2832 AnnotateTemplateIdTokenAsType();
2836 // GNU attributes support.
2837 case tok::kw___attribute:
2838 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
2841 // Microsoft declspec support.
2842 case tok::kw___declspec:
2843 ParseMicrosoftDeclSpec(DS.getAttributes());
2846 // Microsoft single token adornments.
2847 case tok::kw___forceinline: {
2848 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
2849 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
2850 SourceLocation AttrNameLoc = Tok.getLocation();
2851 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
2852 nullptr, 0, AttributeList::AS_Keyword);
2856 case tok::kw___sptr:
2857 case tok::kw___uptr:
2858 case tok::kw___ptr64:
2859 case tok::kw___ptr32:
2861 case tok::kw___cdecl:
2862 case tok::kw___stdcall:
2863 case tok::kw___fastcall:
2864 case tok::kw___thiscall:
2865 case tok::kw___unaligned:
2866 ParseMicrosoftTypeAttributes(DS.getAttributes());
2869 // Borland single token adornments.
2870 case tok::kw___pascal:
2871 ParseBorlandTypeAttributes(DS.getAttributes());
2874 // OpenCL single token adornments.
2875 case tok::kw___kernel:
2876 ParseOpenCLAttributes(DS.getAttributes());
2879 // storage-class-specifier
2880 case tok::kw_typedef:
2881 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
2882 PrevSpec, DiagID, Policy);
2884 case tok::kw_extern:
2885 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
2886 Diag(Tok, diag::ext_thread_before) << "extern";
2887 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
2888 PrevSpec, DiagID, Policy);
2890 case tok::kw___private_extern__:
2891 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
2892 Loc, PrevSpec, DiagID, Policy);
2894 case tok::kw_static:
2895 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
2896 Diag(Tok, diag::ext_thread_before) << "static";
2897 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
2898 PrevSpec, DiagID, Policy);
2901 if (getLangOpts().CPlusPlus11) {
2902 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
2903 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
2904 PrevSpec, DiagID, Policy);
2906 Diag(Tok, diag::ext_auto_storage_class)
2907 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
2909 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
2912 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
2913 PrevSpec, DiagID, Policy);
2915 case tok::kw_register:
2916 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
2917 PrevSpec, DiagID, Policy);
2919 case tok::kw_mutable:
2920 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
2921 PrevSpec, DiagID, Policy);
2923 case tok::kw___thread:
2924 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
2927 case tok::kw_thread_local:
2928 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
2931 case tok::kw__Thread_local:
2932 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
2933 Loc, PrevSpec, DiagID);
2936 // function-specifier
2937 case tok::kw_inline:
2938 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
2940 case tok::kw_virtual:
2941 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
2943 case tok::kw_explicit:
2944 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
2946 case tok::kw__Noreturn:
2947 if (!getLangOpts().C11)
2948 Diag(Loc, diag::ext_c11_noreturn);
2949 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2952 // alignment-specifier
2953 case tok::kw__Alignas:
2954 if (!getLangOpts().C11)
2955 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
2956 ParseAlignmentSpecifier(DS.getAttributes());
2960 case tok::kw_friend:
2961 if (DSContext == DSC_class)
2962 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
2964 PrevSpec = ""; // not actually used by the diagnostic
2965 DiagID = diag::err_friend_invalid_in_context;
2971 case tok::kw___module_private__:
2972 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
2976 case tok::kw_constexpr:
2977 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
2982 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
2986 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
2987 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
2990 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2993 case tok::kw___int64:
2994 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2997 case tok::kw_signed:
2998 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3001 case tok::kw_unsigned:
3002 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3005 case tok::kw__Complex:
3006 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3009 case tok::kw__Imaginary:
3010 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3014 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3018 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3022 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3025 case tok::kw___int128:
3026 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3030 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3034 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3037 case tok::kw_double:
3038 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3041 case tok::kw_wchar_t:
3042 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3045 case tok::kw_char16_t:
3046 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3049 case tok::kw_char32_t:
3050 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3055 if (Tok.is(tok::kw_bool) &&
3056 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3057 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3058 PrevSpec = ""; // Not used by the diagnostic.
3059 DiagID = diag::err_bool_redeclaration;
3060 // For better error recovery.
3061 Tok.setKind(tok::identifier);
3064 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3068 case tok::kw__Decimal32:
3069 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3072 case tok::kw__Decimal64:
3073 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3076 case tok::kw__Decimal128:
3077 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3080 case tok::kw___vector:
3081 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3083 case tok::kw___pixel:
3084 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3086 case tok::kw___unknown_anytype:
3087 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3088 PrevSpec, DiagID, Policy);
3093 case tok::kw_struct:
3094 case tok::kw___interface:
3095 case tok::kw_union: {
3096 tok::TokenKind Kind = Tok.getKind();
3099 // These are attributes following class specifiers.
3100 // To produce better diagnostic, we parse them when
3101 // parsing class specifier.
3102 ParsedAttributesWithRange Attributes(AttrFactory);
3103 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3104 EnteringContext, DSContext, Attributes);
3106 // If there are attributes following class specifier,
3107 // take them over and handle them here.
3108 if (!Attributes.empty()) {
3109 AttrsLastTime = true;
3110 attrs.takeAllFrom(Attributes);
3118 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3123 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3126 case tok::kw_volatile:
3127 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3130 case tok::kw_restrict:
3131 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3135 // C++ typename-specifier:
3136 case tok::kw_typename:
3137 if (TryAnnotateTypeOrScopeToken()) {
3138 DS.SetTypeSpecError();
3139 goto DoneWithDeclSpec;
3141 if (!Tok.is(tok::kw_typename))
3145 // GNU typeof support.
3146 case tok::kw_typeof:
3147 ParseTypeofSpecifier(DS);
3150 case tok::annot_decltype:
3151 ParseDecltypeSpecifier(DS);
3154 case tok::kw___underlying_type:
3155 ParseUnderlyingTypeSpecifier(DS);
3158 case tok::kw__Atomic:
3160 // If the _Atomic keyword is immediately followed by a left parenthesis,
3161 // it is interpreted as a type specifier (with a type name), not as a
3163 if (NextToken().is(tok::l_paren)) {
3164 ParseAtomicSpecifier(DS);
3167 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3171 // OpenCL qualifiers:
3172 case tok::kw___private:
3173 case tok::kw___global:
3174 case tok::kw___local:
3175 case tok::kw___constant:
3176 case tok::kw___read_only:
3177 case tok::kw___write_only:
3178 case tok::kw___read_write:
3179 ParseOpenCLQualifiers(DS.getAttributes());
3183 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3184 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3185 // but we support it.
3186 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
3187 goto DoneWithDeclSpec;
3189 if (!ParseObjCProtocolQualifiers(DS))
3190 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
3191 << FixItHint::CreateInsertion(Loc, "id")
3192 << SourceRange(Loc, DS.getSourceRange().getEnd());
3194 // Need to support trailing type qualifiers (e.g. "id<p> const").
3195 // If a type specifier follows, it will be diagnosed elsewhere.
3198 // If the specifier wasn't legal, issue a diagnostic.
3200 assert(PrevSpec && "Method did not return previous specifier!");
3203 if (DiagID == diag::ext_duplicate_declspec)
3205 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
3207 Diag(Tok, DiagID) << PrevSpec;
3210 DS.SetRangeEnd(Tok.getLocation());
3211 if (DiagID != diag::err_bool_redeclaration)
3214 AttrsLastTime = false;
3218 /// ParseStructDeclaration - Parse a struct declaration without the terminating
3221 /// struct-declaration:
3222 /// specifier-qualifier-list struct-declarator-list
3223 /// [GNU] __extension__ struct-declaration
3224 /// [GNU] specifier-qualifier-list
3225 /// struct-declarator-list:
3226 /// struct-declarator
3227 /// struct-declarator-list ',' struct-declarator
3228 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3229 /// struct-declarator:
3231 /// [GNU] declarator attributes[opt]
3232 /// declarator[opt] ':' constant-expression
3233 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3236 ParseStructDeclaration(ParsingDeclSpec &DS, FieldCallback &Fields) {
3238 if (Tok.is(tok::kw___extension__)) {
3239 // __extension__ silences extension warnings in the subexpression.
3240 ExtensionRAIIObject O(Diags); // Use RAII to do this.
3242 return ParseStructDeclaration(DS, Fields);
3245 // Parse the common specifier-qualifiers-list piece.
3246 ParseSpecifierQualifierList(DS);
3248 // If there are no declarators, this is a free-standing declaration
3249 // specifier. Let the actions module cope with it.
3250 if (Tok.is(tok::semi)) {
3251 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
3253 DS.complete(TheDecl);
3257 // Read struct-declarators until we find the semicolon.
3258 bool FirstDeclarator = true;
3259 SourceLocation CommaLoc;
3261 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
3262 DeclaratorInfo.D.setCommaLoc(CommaLoc);
3264 // Attributes are only allowed here on successive declarators.
3265 if (!FirstDeclarator)
3266 MaybeParseGNUAttributes(DeclaratorInfo.D);
3268 /// struct-declarator: declarator
3269 /// struct-declarator: declarator[opt] ':' constant-expression
3270 if (Tok.isNot(tok::colon)) {
3271 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3272 ColonProtectionRAIIObject X(*this);
3273 ParseDeclarator(DeclaratorInfo.D);
3276 if (TryConsumeToken(tok::colon)) {
3277 ExprResult Res(ParseConstantExpression());
3278 if (Res.isInvalid())
3279 SkipUntil(tok::semi, StopBeforeMatch);
3281 DeclaratorInfo.BitfieldSize = Res.get();
3284 // If attributes exist after the declarator, parse them.
3285 MaybeParseGNUAttributes(DeclaratorInfo.D);
3287 // We're done with this declarator; invoke the callback.
3288 Fields.invoke(DeclaratorInfo);
3290 // If we don't have a comma, it is either the end of the list (a ';')
3291 // or an error, bail out.
3292 if (!TryConsumeToken(tok::comma, CommaLoc))
3295 FirstDeclarator = false;
3299 /// ParseStructUnionBody
3300 /// struct-contents:
3301 /// struct-declaration-list
3303 /// [GNU] "struct-declaration-list" without terminatoring ';'
3304 /// struct-declaration-list:
3305 /// struct-declaration
3306 /// struct-declaration-list struct-declaration
3307 /// [OBC] '@' 'defs' '(' class-name ')'
3309 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
3310 unsigned TagType, Decl *TagDecl) {
3311 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3312 "parsing struct/union body");
3313 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
3315 BalancedDelimiterTracker T(*this, tok::l_brace);
3316 if (T.consumeOpen())
3319 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
3320 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3322 SmallVector<Decl *, 32> FieldDecls;
3324 // While we still have something to read, read the declarations in the struct.
3325 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
3326 // Each iteration of this loop reads one struct-declaration.
3328 // Check for extraneous top-level semicolon.
3329 if (Tok.is(tok::semi)) {
3330 ConsumeExtraSemi(InsideStruct, TagType);
3334 // Parse _Static_assert declaration.
3335 if (Tok.is(tok::kw__Static_assert)) {
3336 SourceLocation DeclEnd;
3337 ParseStaticAssertDeclaration(DeclEnd);
3341 if (Tok.is(tok::annot_pragma_pack)) {
3346 if (Tok.is(tok::annot_pragma_align)) {
3347 HandlePragmaAlign();
3351 if (!Tok.is(tok::at)) {
3352 struct CFieldCallback : FieldCallback {
3355 SmallVectorImpl<Decl *> &FieldDecls;
3357 CFieldCallback(Parser &P, Decl *TagDecl,
3358 SmallVectorImpl<Decl *> &FieldDecls) :
3359 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
3361 void invoke(ParsingFieldDeclarator &FD) override {
3362 // Install the declarator into the current TagDecl.
3363 Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl,
3364 FD.D.getDeclSpec().getSourceRange().getBegin(),
3365 FD.D, FD.BitfieldSize);
3366 FieldDecls.push_back(Field);
3369 } Callback(*this, TagDecl, FieldDecls);
3371 // Parse all the comma separated declarators.
3372 ParsingDeclSpec DS(*this);
3373 ParseStructDeclaration(DS, Callback);
3374 } else { // Handle @defs
3376 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
3377 Diag(Tok, diag::err_unexpected_at);
3378 SkipUntil(tok::semi);
3382 ExpectAndConsume(tok::l_paren);
3383 if (!Tok.is(tok::identifier)) {
3384 Diag(Tok, diag::err_expected) << tok::identifier;
3385 SkipUntil(tok::semi);
3388 SmallVector<Decl *, 16> Fields;
3389 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
3390 Tok.getIdentifierInfo(), Fields);
3391 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
3393 ExpectAndConsume(tok::r_paren);
3396 if (TryConsumeToken(tok::semi))
3399 if (Tok.is(tok::r_brace)) {
3400 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
3404 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
3405 // Skip to end of block or statement to avoid ext-warning on extra ';'.
3406 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
3407 // If we stopped at a ';', eat it.
3408 TryConsumeToken(tok::semi);
3413 ParsedAttributes attrs(AttrFactory);
3414 // If attributes exist after struct contents, parse them.
3415 MaybeParseGNUAttributes(attrs);
3417 Actions.ActOnFields(getCurScope(),
3418 RecordLoc, TagDecl, FieldDecls,
3419 T.getOpenLocation(), T.getCloseLocation(),
3422 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
3423 T.getCloseLocation());
3426 /// ParseEnumSpecifier
3427 /// enum-specifier: [C99 6.7.2.2]
3428 /// 'enum' identifier[opt] '{' enumerator-list '}'
3429 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
3430 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
3431 /// '}' attributes[opt]
3432 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
3434 /// 'enum' identifier
3435 /// [GNU] 'enum' attributes[opt] identifier
3437 /// [C++11] enum-head '{' enumerator-list[opt] '}'
3438 /// [C++11] enum-head '{' enumerator-list ',' '}'
3440 /// enum-head: [C++11]
3441 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
3442 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
3443 /// identifier enum-base[opt]
3445 /// enum-key: [C++11]
3450 /// enum-base: [C++11]
3451 /// ':' type-specifier-seq
3453 /// [C++] elaborated-type-specifier:
3454 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
3456 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
3457 const ParsedTemplateInfo &TemplateInfo,
3458 AccessSpecifier AS, DeclSpecContext DSC) {
3459 // Parse the tag portion of this.
3460 if (Tok.is(tok::code_completion)) {
3461 // Code completion for an enum name.
3462 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
3463 return cutOffParsing();
3466 // If attributes exist after tag, parse them.
3467 ParsedAttributesWithRange attrs(AttrFactory);
3468 MaybeParseGNUAttributes(attrs);
3469 MaybeParseCXX11Attributes(attrs);
3471 // If declspecs exist after tag, parse them.
3472 while (Tok.is(tok::kw___declspec))
3473 ParseMicrosoftDeclSpec(attrs);
3475 SourceLocation ScopedEnumKWLoc;
3476 bool IsScopedUsingClassTag = false;
3478 // In C++11, recognize 'enum class' and 'enum struct'.
3479 if (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct)) {
3480 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
3481 : diag::ext_scoped_enum);
3482 IsScopedUsingClassTag = Tok.is(tok::kw_class);
3483 ScopedEnumKWLoc = ConsumeToken();
3485 // Attributes are not allowed between these keywords. Diagnose,
3486 // but then just treat them like they appeared in the right place.
3487 ProhibitAttributes(attrs);
3489 // They are allowed afterwards, though.
3490 MaybeParseGNUAttributes(attrs);
3491 MaybeParseCXX11Attributes(attrs);
3492 while (Tok.is(tok::kw___declspec))
3493 ParseMicrosoftDeclSpec(attrs);
3496 // C++11 [temp.explicit]p12:
3497 // The usual access controls do not apply to names used to specify
3498 // explicit instantiations.
3499 // We extend this to also cover explicit specializations. Note that
3500 // we don't suppress if this turns out to be an elaborated type
3502 bool shouldDelayDiagsInTag =
3503 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3504 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3505 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
3507 // Enum definitions should not be parsed in a trailing-return-type.
3508 bool AllowDeclaration = DSC != DSC_trailing;
3510 bool AllowFixedUnderlyingType = AllowDeclaration &&
3511 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
3512 getLangOpts().ObjC2);
3514 CXXScopeSpec &SS = DS.getTypeSpecScope();
3515 if (getLangOpts().CPlusPlus) {
3516 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
3517 // if a fixed underlying type is allowed.
3518 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
3520 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
3521 /*EnteringContext=*/true))
3524 if (SS.isSet() && Tok.isNot(tok::identifier)) {
3525 Diag(Tok, diag::err_expected) << tok::identifier;
3526 if (Tok.isNot(tok::l_brace)) {
3527 // Has no name and is not a definition.
3528 // Skip the rest of this declarator, up until the comma or semicolon.
3529 SkipUntil(tok::comma, StopAtSemi);
3535 // Must have either 'enum name' or 'enum {...}'.
3536 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
3537 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
3538 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
3540 // Skip the rest of this declarator, up until the comma or semicolon.
3541 SkipUntil(tok::comma, StopAtSemi);
3545 // If an identifier is present, consume and remember it.
3546 IdentifierInfo *Name = nullptr;
3547 SourceLocation NameLoc;
3548 if (Tok.is(tok::identifier)) {
3549 Name = Tok.getIdentifierInfo();
3550 NameLoc = ConsumeToken();
3553 if (!Name && ScopedEnumKWLoc.isValid()) {
3554 // C++0x 7.2p2: The optional identifier shall not be omitted in the
3555 // declaration of a scoped enumeration.
3556 Diag(Tok, diag::err_scoped_enum_missing_identifier);
3557 ScopedEnumKWLoc = SourceLocation();
3558 IsScopedUsingClassTag = false;
3561 // Okay, end the suppression area. We'll decide whether to emit the
3562 // diagnostics in a second.
3563 if (shouldDelayDiagsInTag)
3564 diagsFromTag.done();
3566 TypeResult BaseType;
3568 // Parse the fixed underlying type.
3569 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
3570 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
3571 bool PossibleBitfield = false;
3572 if (CanBeBitfield) {
3573 // If we're in class scope, this can either be an enum declaration with
3574 // an underlying type, or a declaration of a bitfield member. We try to
3575 // use a simple disambiguation scheme first to catch the common cases
3576 // (integer literal, sizeof); if it's still ambiguous, we then consider
3577 // anything that's a simple-type-specifier followed by '(' as an
3578 // expression. This suffices because function types are not valid
3579 // underlying types anyway.
3580 EnterExpressionEvaluationContext Unevaluated(Actions,
3581 Sema::ConstantEvaluated);
3582 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
3583 // If the next token starts an expression, we know we're parsing a
3584 // bit-field. This is the common case.
3585 if (TPR == TPResult::True)
3586 PossibleBitfield = true;
3587 // If the next token starts a type-specifier-seq, it may be either a
3588 // a fixed underlying type or the start of a function-style cast in C++;
3589 // lookahead one more token to see if it's obvious that we have a
3590 // fixed underlying type.
3591 else if (TPR == TPResult::False &&
3592 GetLookAheadToken(2).getKind() == tok::semi) {
3596 // We have the start of a type-specifier-seq, so we have to perform
3597 // tentative parsing to determine whether we have an expression or a
3599 TentativeParsingAction TPA(*this);
3604 // If we see a type specifier followed by an open-brace, we have an
3605 // ambiguity between an underlying type and a C++11 braced
3606 // function-style cast. Resolve this by always treating it as an
3608 // FIXME: The standard is not entirely clear on how to disambiguate in
3610 if ((getLangOpts().CPlusPlus &&
3611 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
3612 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
3613 // We'll parse this as a bitfield later.
3614 PossibleBitfield = true;
3617 // We have a type-specifier-seq.
3626 if (!PossibleBitfield) {
3628 BaseType = ParseTypeName(&Range);
3630 if (getLangOpts().CPlusPlus11) {
3631 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
3632 } else if (!getLangOpts().ObjC2) {
3633 if (getLangOpts().CPlusPlus)
3634 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
3636 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
3641 // There are four options here. If we have 'friend enum foo;' then this is a
3642 // friend declaration, and cannot have an accompanying definition. If we have
3643 // 'enum foo;', then this is a forward declaration. If we have
3644 // 'enum foo {...' then this is a definition. Otherwise we have something
3645 // like 'enum foo xyz', a reference.
3647 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
3648 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
3649 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
3651 Sema::TagUseKind TUK;
3652 if (!AllowDeclaration) {
3653 TUK = Sema::TUK_Reference;
3654 } else if (Tok.is(tok::l_brace)) {
3655 if (DS.isFriendSpecified()) {
3656 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
3657 << SourceRange(DS.getFriendSpecLoc());
3659 SkipUntil(tok::r_brace, StopAtSemi);
3660 TUK = Sema::TUK_Friend;
3662 TUK = Sema::TUK_Definition;
3664 } else if (!isTypeSpecifier(DSC) &&
3665 (Tok.is(tok::semi) ||
3666 (Tok.isAtStartOfLine() &&
3667 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
3668 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
3669 if (Tok.isNot(tok::semi)) {
3670 // A semicolon was missing after this declaration. Diagnose and recover.
3671 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
3673 Tok.setKind(tok::semi);
3676 TUK = Sema::TUK_Reference;
3679 // If this is an elaborated type specifier, and we delayed
3680 // diagnostics before, just merge them into the current pool.
3681 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
3682 diagsFromTag.redelay();
3685 MultiTemplateParamsArg TParams;
3686 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
3687 TUK != Sema::TUK_Reference) {
3688 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
3689 // Skip the rest of this declarator, up until the comma or semicolon.
3690 Diag(Tok, diag::err_enum_template);
3691 SkipUntil(tok::comma, StopAtSemi);
3695 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
3696 // Enumerations can't be explicitly instantiated.
3697 DS.SetTypeSpecError();
3698 Diag(StartLoc, diag::err_explicit_instantiation_enum);
3702 assert(TemplateInfo.TemplateParams && "no template parameters");
3703 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
3704 TemplateInfo.TemplateParams->size());
3707 if (TUK == Sema::TUK_Reference)
3708 ProhibitAttributes(attrs);
3710 if (!Name && TUK != Sema::TUK_Definition) {
3711 Diag(Tok, diag::err_enumerator_unnamed_no_def);
3713 // Skip the rest of this declarator, up until the comma or semicolon.
3714 SkipUntil(tok::comma, StopAtSemi);
3719 bool IsDependent = false;
3720 const char *PrevSpec = nullptr;
3722 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
3723 StartLoc, SS, Name, NameLoc, attrs.getList(),
3724 AS, DS.getModulePrivateSpecLoc(), TParams,
3725 Owned, IsDependent, ScopedEnumKWLoc,
3726 IsScopedUsingClassTag, BaseType,
3727 DSC == DSC_type_specifier);
3730 // This enum has a dependent nested-name-specifier. Handle it as a
3733 DS.SetTypeSpecError();
3734 Diag(Tok, diag::err_expected_type_name_after_typename);
3738 TypeResult Type = Actions.ActOnDependentTag(
3739 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
3740 if (Type.isInvalid()) {
3741 DS.SetTypeSpecError();
3745 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
3746 NameLoc.isValid() ? NameLoc : StartLoc,
3747 PrevSpec, DiagID, Type.get(),
3748 Actions.getASTContext().getPrintingPolicy()))
3749 Diag(StartLoc, DiagID) << PrevSpec;
3755 // The action failed to produce an enumeration tag. If this is a
3756 // definition, consume the entire definition.
3757 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
3759 SkipUntil(tok::r_brace, StopAtSemi);
3762 DS.SetTypeSpecError();
3766 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference)
3767 ParseEnumBody(StartLoc, TagDecl);
3769 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
3770 NameLoc.isValid() ? NameLoc : StartLoc,
3771 PrevSpec, DiagID, TagDecl, Owned,
3772 Actions.getASTContext().getPrintingPolicy()))
3773 Diag(StartLoc, DiagID) << PrevSpec;
3776 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
3777 /// enumerator-list:
3779 /// enumerator-list ',' enumerator
3781 /// enumeration-constant
3782 /// enumeration-constant '=' constant-expression
3783 /// enumeration-constant:
3786 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
3787 // Enter the scope of the enum body and start the definition.
3788 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
3789 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
3791 BalancedDelimiterTracker T(*this, tok::l_brace);
3794 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
3795 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
3796 Diag(Tok, diag::error_empty_enum);
3798 SmallVector<Decl *, 32> EnumConstantDecls;
3800 Decl *LastEnumConstDecl = nullptr;
3802 // Parse the enumerator-list.
3803 while (Tok.isNot(tok::r_brace)) {
3804 // Parse enumerator. If failed, try skipping till the start of the next
3805 // enumerator definition.
3806 if (Tok.isNot(tok::identifier)) {
3807 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3808 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
3809 TryConsumeToken(tok::comma))
3813 IdentifierInfo *Ident = Tok.getIdentifierInfo();
3814 SourceLocation IdentLoc = ConsumeToken();
3816 // If attributes exist after the enumerator, parse them.
3817 ParsedAttributesWithRange attrs(AttrFactory);
3818 MaybeParseGNUAttributes(attrs);
3819 MaybeParseCXX11Attributes(attrs);
3820 ProhibitAttributes(attrs);
3822 SourceLocation EqualLoc;
3823 ExprResult AssignedVal;
3824 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
3826 if (TryConsumeToken(tok::equal, EqualLoc)) {
3827 AssignedVal = ParseConstantExpression();
3828 if (AssignedVal.isInvalid())
3829 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
3832 // Install the enumerator constant into EnumDecl.
3833 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
3836 attrs.getList(), EqualLoc,
3838 PD.complete(EnumConstDecl);
3840 EnumConstantDecls.push_back(EnumConstDecl);
3841 LastEnumConstDecl = EnumConstDecl;
3843 if (Tok.is(tok::identifier)) {
3844 // We're missing a comma between enumerators.
3845 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3846 Diag(Loc, diag::err_enumerator_list_missing_comma)
3847 << FixItHint::CreateInsertion(Loc, ", ");
3851 // Emumerator definition must be finished, only comma or r_brace are
3853 SourceLocation CommaLoc;
3854 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
3855 if (EqualLoc.isValid())
3856 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
3859 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
3860 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
3861 if (TryConsumeToken(tok::comma, CommaLoc))
3868 // If comma is followed by r_brace, emit appropriate warning.
3869 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
3870 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
3871 Diag(CommaLoc, getLangOpts().CPlusPlus ?
3872 diag::ext_enumerator_list_comma_cxx :
3873 diag::ext_enumerator_list_comma_c)
3874 << FixItHint::CreateRemoval(CommaLoc);
3875 else if (getLangOpts().CPlusPlus11)
3876 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
3877 << FixItHint::CreateRemoval(CommaLoc);
3885 // If attributes exist after the identifier list, parse them.
3886 ParsedAttributes attrs(AttrFactory);
3887 MaybeParseGNUAttributes(attrs);
3889 Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(),
3890 EnumDecl, EnumConstantDecls,
3895 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl,
3896 T.getCloseLocation());
3898 // The next token must be valid after an enum definition. If not, a ';'
3899 // was probably forgotten.
3900 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
3901 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
3902 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
3903 // Push this token back into the preprocessor and change our current token
3904 // to ';' so that the rest of the code recovers as though there were an
3905 // ';' after the definition.
3907 Tok.setKind(tok::semi);
3911 /// isTypeSpecifierQualifier - Return true if the current token could be the
3912 /// start of a type-qualifier-list.
3913 bool Parser::isTypeQualifier() const {
3914 switch (Tok.getKind()) {
3915 default: return false;
3918 case tok::kw_volatile:
3919 case tok::kw_restrict:
3920 case tok::kw___private:
3921 case tok::kw___local:
3922 case tok::kw___global:
3923 case tok::kw___constant:
3924 case tok::kw___read_only:
3925 case tok::kw___read_write:
3926 case tok::kw___write_only:
3931 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
3932 /// is definitely a type-specifier. Return false if it isn't part of a type
3933 /// specifier or if we're not sure.
3934 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
3935 switch (Tok.getKind()) {
3936 default: return false;
3940 case tok::kw___int64:
3941 case tok::kw___int128:
3942 case tok::kw_signed:
3943 case tok::kw_unsigned:
3944 case tok::kw__Complex:
3945 case tok::kw__Imaginary:
3948 case tok::kw_wchar_t:
3949 case tok::kw_char16_t:
3950 case tok::kw_char32_t:
3954 case tok::kw_double:
3957 case tok::kw__Decimal32:
3958 case tok::kw__Decimal64:
3959 case tok::kw__Decimal128:
3960 case tok::kw___vector:
3962 // struct-or-union-specifier (C99) or class-specifier (C++)
3964 case tok::kw_struct:
3965 case tok::kw___interface:
3971 case tok::annot_typename:
3976 /// isTypeSpecifierQualifier - Return true if the current token could be the
3977 /// start of a specifier-qualifier-list.
3978 bool Parser::isTypeSpecifierQualifier() {
3979 switch (Tok.getKind()) {
3980 default: return false;
3982 case tok::identifier: // foo::bar
3983 if (TryAltiVecVectorToken())
3986 case tok::kw_typename: // typename T::type
3987 // Annotate typenames and C++ scope specifiers. If we get one, just
3988 // recurse to handle whatever we get.
3989 if (TryAnnotateTypeOrScopeToken())
3991 if (Tok.is(tok::identifier))
3993 return isTypeSpecifierQualifier();
3995 case tok::coloncolon: // ::foo::bar
3996 if (NextToken().is(tok::kw_new) || // ::new
3997 NextToken().is(tok::kw_delete)) // ::delete
4000 if (TryAnnotateTypeOrScopeToken())
4002 return isTypeSpecifierQualifier();
4004 // GNU attributes support.
4005 case tok::kw___attribute:
4006 // GNU typeof support.
4007 case tok::kw_typeof:
4012 case tok::kw___int64:
4013 case tok::kw___int128:
4014 case tok::kw_signed:
4015 case tok::kw_unsigned:
4016 case tok::kw__Complex:
4017 case tok::kw__Imaginary:
4020 case tok::kw_wchar_t:
4021 case tok::kw_char16_t:
4022 case tok::kw_char32_t:
4026 case tok::kw_double:
4029 case tok::kw__Decimal32:
4030 case tok::kw__Decimal64:
4031 case tok::kw__Decimal128:
4032 case tok::kw___vector:
4034 // struct-or-union-specifier (C99) or class-specifier (C++)
4036 case tok::kw_struct:
4037 case tok::kw___interface:
4044 case tok::kw_volatile:
4045 case tok::kw_restrict:
4047 // Debugger support.
4048 case tok::kw___unknown_anytype:
4051 case tok::annot_typename:
4054 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4056 return getLangOpts().ObjC1;
4058 case tok::kw___cdecl:
4059 case tok::kw___stdcall:
4060 case tok::kw___fastcall:
4061 case tok::kw___thiscall:
4063 case tok::kw___ptr64:
4064 case tok::kw___ptr32:
4065 case tok::kw___pascal:
4066 case tok::kw___unaligned:
4068 case tok::kw___private:
4069 case tok::kw___local:
4070 case tok::kw___global:
4071 case tok::kw___constant:
4072 case tok::kw___read_only:
4073 case tok::kw___read_write:
4074 case tok::kw___write_only:
4079 case tok::kw__Atomic:
4084 /// isDeclarationSpecifier() - Return true if the current token is part of a
4085 /// declaration specifier.
4087 /// \param DisambiguatingWithExpression True to indicate that the purpose of
4088 /// this check is to disambiguate between an expression and a declaration.
4089 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4090 switch (Tok.getKind()) {
4091 default: return false;
4093 case tok::identifier: // foo::bar
4094 // Unfortunate hack to support "Class.factoryMethod" notation.
4095 if (getLangOpts().ObjC1 && NextToken().is(tok::period))
4097 if (TryAltiVecVectorToken())
4100 case tok::kw_decltype: // decltype(T())::type
4101 case tok::kw_typename: // typename T::type
4102 // Annotate typenames and C++ scope specifiers. If we get one, just
4103 // recurse to handle whatever we get.
4104 if (TryAnnotateTypeOrScopeToken())
4106 if (Tok.is(tok::identifier))
4109 // If we're in Objective-C and we have an Objective-C class type followed
4110 // by an identifier and then either ':' or ']', in a place where an
4111 // expression is permitted, then this is probably a class message send
4112 // missing the initial '['. In this case, we won't consider this to be
4113 // the start of a declaration.
4114 if (DisambiguatingWithExpression &&
4115 isStartOfObjCClassMessageMissingOpenBracket())
4118 return isDeclarationSpecifier();
4120 case tok::coloncolon: // ::foo::bar
4121 if (NextToken().is(tok::kw_new) || // ::new
4122 NextToken().is(tok::kw_delete)) // ::delete
4125 // Annotate typenames and C++ scope specifiers. If we get one, just
4126 // recurse to handle whatever we get.
4127 if (TryAnnotateTypeOrScopeToken())
4129 return isDeclarationSpecifier();
4131 // storage-class-specifier
4132 case tok::kw_typedef:
4133 case tok::kw_extern:
4134 case tok::kw___private_extern__:
4135 case tok::kw_static:
4137 case tok::kw_register:
4138 case tok::kw___thread:
4139 case tok::kw_thread_local:
4140 case tok::kw__Thread_local:
4143 case tok::kw___module_private__:
4146 case tok::kw___unknown_anytype:
4151 case tok::kw___int64:
4152 case tok::kw___int128:
4153 case tok::kw_signed:
4154 case tok::kw_unsigned:
4155 case tok::kw__Complex:
4156 case tok::kw__Imaginary:
4159 case tok::kw_wchar_t:
4160 case tok::kw_char16_t:
4161 case tok::kw_char32_t:
4166 case tok::kw_double:
4169 case tok::kw__Decimal32:
4170 case tok::kw__Decimal64:
4171 case tok::kw__Decimal128:
4172 case tok::kw___vector:
4174 // struct-or-union-specifier (C99) or class-specifier (C++)
4176 case tok::kw_struct:
4178 case tok::kw___interface:
4184 case tok::kw_volatile:
4185 case tok::kw_restrict:
4187 // function-specifier
4188 case tok::kw_inline:
4189 case tok::kw_virtual:
4190 case tok::kw_explicit:
4191 case tok::kw__Noreturn:
4193 // alignment-specifier
4194 case tok::kw__Alignas:
4197 case tok::kw_friend:
4199 // static_assert-declaration
4200 case tok::kw__Static_assert:
4202 // GNU typeof support.
4203 case tok::kw_typeof:
4206 case tok::kw___attribute:
4208 // C++11 decltype and constexpr.
4209 case tok::annot_decltype:
4210 case tok::kw_constexpr:
4213 case tok::kw__Atomic:
4216 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4218 return getLangOpts().ObjC1;
4221 case tok::annot_typename:
4222 return !DisambiguatingWithExpression ||
4223 !isStartOfObjCClassMessageMissingOpenBracket();
4225 case tok::kw___declspec:
4226 case tok::kw___cdecl:
4227 case tok::kw___stdcall:
4228 case tok::kw___fastcall:
4229 case tok::kw___thiscall:
4231 case tok::kw___sptr:
4232 case tok::kw___uptr:
4233 case tok::kw___ptr64:
4234 case tok::kw___ptr32:
4235 case tok::kw___forceinline:
4236 case tok::kw___pascal:
4237 case tok::kw___unaligned:
4239 case tok::kw___private:
4240 case tok::kw___local:
4241 case tok::kw___global:
4242 case tok::kw___constant:
4243 case tok::kw___read_only:
4244 case tok::kw___read_write:
4245 case tok::kw___write_only:
4251 bool Parser::isConstructorDeclarator(bool IsUnqualified) {
4252 TentativeParsingAction TPA(*this);
4254 // Parse the C++ scope specifier.
4256 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
4257 /*EnteringContext=*/true)) {
4262 // Parse the constructor name.
4263 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
4264 // We already know that we have a constructor name; just consume
4272 // Current class name must be followed by a left parenthesis.
4273 if (Tok.isNot(tok::l_paren)) {
4279 // A right parenthesis, or ellipsis followed by a right parenthesis signals
4280 // that we have a constructor.
4281 if (Tok.is(tok::r_paren) ||
4282 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
4287 // A C++11 attribute here signals that we have a constructor, and is an
4288 // attribute on the first constructor parameter.
4289 if (getLangOpts().CPlusPlus11 &&
4290 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
4291 /*OuterMightBeMessageSend*/ true)) {
4296 // If we need to, enter the specified scope.
4297 DeclaratorScopeObj DeclScopeObj(*this, SS);
4298 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
4299 DeclScopeObj.EnterDeclaratorScope();
4301 // Optionally skip Microsoft attributes.
4302 ParsedAttributes Attrs(AttrFactory);
4303 MaybeParseMicrosoftAttributes(Attrs);
4305 // Check whether the next token(s) are part of a declaration
4306 // specifier, in which case we have the start of a parameter and,
4307 // therefore, we know that this is a constructor.
4308 bool IsConstructor = false;
4309 if (isDeclarationSpecifier())
4310 IsConstructor = true;
4311 else if (Tok.is(tok::identifier) ||
4312 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
4313 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
4314 // This might be a parenthesized member name, but is more likely to
4315 // be a constructor declaration with an invalid argument type. Keep
4317 if (Tok.is(tok::annot_cxxscope))
4321 // If this is not a constructor, we must be parsing a declarator,
4322 // which must have one of the following syntactic forms (see the
4323 // grammar extract at the start of ParseDirectDeclarator):
4324 switch (Tok.getKind()) {
4329 // C(X [ [attribute]]);
4330 case tok::coloncolon:
4333 // Assume this isn't a constructor, rather than assuming it's a
4334 // constructor with an unnamed parameter of an ill-formed type.
4339 if (NextToken().is(tok::colon) || NextToken().is(tok::kw_try)) {
4340 // Assume these were meant to be constructors:
4341 // C(X) : (the name of a bit-field cannot be parenthesized).
4342 // C(X) try (this is otherwise ill-formed).
4343 IsConstructor = true;
4345 if (NextToken().is(tok::semi) || NextToken().is(tok::l_brace)) {
4346 // If we have a constructor name within the class definition,
4347 // assume these were meant to be constructors:
4350 // ... because otherwise we would be declaring a non-static data
4351 // member that is ill-formed because it's of the same type as its
4352 // surrounding class.
4354 // FIXME: We can actually do this whether or not the name is qualified,
4355 // because if it is qualified in this context it must be being used as
4356 // a constructor name. However, we do not implement that rule correctly
4357 // currently, so we're somewhat conservative here.
4358 IsConstructor = IsUnqualified;
4363 IsConstructor = true;
4369 return IsConstructor;
4372 /// ParseTypeQualifierListOpt
4373 /// type-qualifier-list: [C99 6.7.5]
4375 /// [vendor] attributes
4376 /// [ only if VendorAttributesAllowed=true ]
4377 /// type-qualifier-list type-qualifier
4378 /// [vendor] type-qualifier-list attributes
4379 /// [ only if VendorAttributesAllowed=true ]
4380 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
4381 /// [ only if CXX11AttributesAllowed=true ]
4382 /// Note: vendor can be GNU, MS, etc.
4384 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
4385 bool VendorAttributesAllowed,
4386 bool CXX11AttributesAllowed,
4388 bool IdentifierRequired) {
4389 if (getLangOpts().CPlusPlus11 && CXX11AttributesAllowed &&
4390 isCXX11AttributeSpecifier()) {
4391 ParsedAttributesWithRange attrs(AttrFactory);
4392 ParseCXX11Attributes(attrs);
4393 DS.takeAttributesFrom(attrs);
4396 SourceLocation EndLoc;
4399 bool isInvalid = false;
4400 const char *PrevSpec = nullptr;
4401 unsigned DiagID = 0;
4402 SourceLocation Loc = Tok.getLocation();
4404 switch (Tok.getKind()) {
4405 case tok::code_completion:
4406 Actions.CodeCompleteTypeQualifiers(DS);
4407 return cutOffParsing();
4410 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
4413 case tok::kw_volatile:
4414 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4417 case tok::kw_restrict:
4418 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4421 case tok::kw__Atomic:
4423 goto DoneWithTypeQuals;
4424 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4428 // OpenCL qualifiers:
4429 case tok::kw___private:
4430 case tok::kw___global:
4431 case tok::kw___local:
4432 case tok::kw___constant:
4433 case tok::kw___read_only:
4434 case tok::kw___write_only:
4435 case tok::kw___read_write:
4436 ParseOpenCLQualifiers(DS.getAttributes());
4439 case tok::kw___uptr:
4440 // GNU libc headers in C mode use '__uptr' as an identifer which conflicts
4441 // with the MS modifier keyword.
4442 if (VendorAttributesAllowed && !getLangOpts().CPlusPlus &&
4443 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
4444 if (TryKeywordIdentFallback(false))
4447 case tok::kw___sptr:
4449 case tok::kw___ptr64:
4450 case tok::kw___ptr32:
4451 case tok::kw___cdecl:
4452 case tok::kw___stdcall:
4453 case tok::kw___fastcall:
4454 case tok::kw___thiscall:
4455 case tok::kw___unaligned:
4456 if (VendorAttributesAllowed) {
4457 ParseMicrosoftTypeAttributes(DS.getAttributes());
4460 goto DoneWithTypeQuals;
4461 case tok::kw___pascal:
4462 if (VendorAttributesAllowed) {
4463 ParseBorlandTypeAttributes(DS.getAttributes());
4466 goto DoneWithTypeQuals;
4467 case tok::kw___attribute:
4468 if (VendorAttributesAllowed) {
4469 ParseGNUAttributes(DS.getAttributes());
4470 continue; // do *not* consume the next token!
4472 // otherwise, FALL THROUGH!
4475 // If this is not a type-qualifier token, we're done reading type
4476 // qualifiers. First verify that DeclSpec's are consistent.
4477 DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy());
4478 if (EndLoc.isValid())
4479 DS.SetRangeEnd(EndLoc);
4483 // If the specifier combination wasn't legal, issue a diagnostic.
4485 assert(PrevSpec && "Method did not return previous specifier!");
4486 Diag(Tok, DiagID) << PrevSpec;
4488 EndLoc = ConsumeToken();
4493 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
4495 void Parser::ParseDeclarator(Declarator &D) {
4496 /// This implements the 'declarator' production in the C grammar, then checks
4497 /// for well-formedness and issues diagnostics.
4498 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
4501 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang) {
4502 if (Kind == tok::star || Kind == tok::caret)
4505 // We parse rvalue refs in C++03, because otherwise the errors are scary.
4506 if (!Lang.CPlusPlus)
4509 return Kind == tok::amp || Kind == tok::ampamp;
4512 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
4513 /// is parsed by the function passed to it. Pass null, and the direct-declarator
4514 /// isn't parsed at all, making this function effectively parse the C++
4515 /// ptr-operator production.
4517 /// If the grammar of this construct is extended, matching changes must also be
4518 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
4519 /// isConstructorDeclarator.
4521 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
4522 /// [C] pointer[opt] direct-declarator
4523 /// [C++] direct-declarator
4524 /// [C++] ptr-operator declarator
4526 /// pointer: [C99 6.7.5]
4527 /// '*' type-qualifier-list[opt]
4528 /// '*' type-qualifier-list[opt] pointer
4531 /// '*' cv-qualifier-seq[opt]
4534 /// [GNU] '&' restrict[opt] attributes[opt]
4535 /// [GNU?] '&&' restrict[opt] attributes[opt]
4536 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
4537 void Parser::ParseDeclaratorInternal(Declarator &D,
4538 DirectDeclParseFunction DirectDeclParser) {
4539 if (Diags.hasAllExtensionsSilenced())
4542 // C++ member pointers start with a '::' or a nested-name.
4543 // Member pointers get special handling, since there's no place for the
4544 // scope spec in the generic path below.
4545 if (getLangOpts().CPlusPlus &&
4546 (Tok.is(tok::coloncolon) ||
4547 (Tok.is(tok::identifier) &&
4548 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
4549 Tok.is(tok::annot_cxxscope))) {
4550 bool EnteringContext = D.getContext() == Declarator::FileContext ||
4551 D.getContext() == Declarator::MemberContext;
4553 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext);
4555 if (SS.isNotEmpty()) {
4556 if (Tok.isNot(tok::star)) {
4557 // The scope spec really belongs to the direct-declarator.
4558 if (D.mayHaveIdentifier())
4559 D.getCXXScopeSpec() = SS;
4561 AnnotateScopeToken(SS, true);
4563 if (DirectDeclParser)
4564 (this->*DirectDeclParser)(D);
4568 SourceLocation Loc = ConsumeToken();
4570 DeclSpec DS(AttrFactory);
4571 ParseTypeQualifierListOpt(DS);
4572 D.ExtendWithDeclSpec(DS);
4574 // Recurse to parse whatever is left.
4575 ParseDeclaratorInternal(D, DirectDeclParser);
4577 // Sema will have to catch (syntactically invalid) pointers into global
4578 // scope. It has to catch pointers into namespace scope anyway.
4579 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
4582 /* Don't replace range end. */SourceLocation());
4587 tok::TokenKind Kind = Tok.getKind();
4588 // Not a pointer, C++ reference, or block.
4589 if (!isPtrOperatorToken(Kind, getLangOpts())) {
4590 if (DirectDeclParser)
4591 (this->*DirectDeclParser)(D);
4595 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
4596 // '&&' -> rvalue reference
4597 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
4600 if (Kind == tok::star || Kind == tok::caret) {
4602 DeclSpec DS(AttrFactory);
4604 // FIXME: GNU attributes are not allowed here in a new-type-id.
4605 ParseTypeQualifierListOpt(DS, true, true, true, !D.mayOmitIdentifier());
4606 D.ExtendWithDeclSpec(DS);
4608 // Recursively parse the declarator.
4609 ParseDeclaratorInternal(D, DirectDeclParser);
4610 if (Kind == tok::star)
4611 // Remember that we parsed a pointer type, and remember the type-quals.
4612 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
4613 DS.getConstSpecLoc(),
4614 DS.getVolatileSpecLoc(),
4615 DS.getRestrictSpecLoc()),
4619 // Remember that we parsed a Block type, and remember the type-quals.
4620 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
4626 DeclSpec DS(AttrFactory);
4628 // Complain about rvalue references in C++03, but then go on and build
4630 if (Kind == tok::ampamp)
4631 Diag(Loc, getLangOpts().CPlusPlus11 ?
4632 diag::warn_cxx98_compat_rvalue_reference :
4633 diag::ext_rvalue_reference);
4635 // GNU-style and C++11 attributes are allowed here, as is restrict.
4636 ParseTypeQualifierListOpt(DS);
4637 D.ExtendWithDeclSpec(DS);
4639 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
4640 // cv-qualifiers are introduced through the use of a typedef or of a
4641 // template type argument, in which case the cv-qualifiers are ignored.
4642 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
4643 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4644 Diag(DS.getConstSpecLoc(),
4645 diag::err_invalid_reference_qualifier_application) << "const";
4646 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4647 Diag(DS.getVolatileSpecLoc(),
4648 diag::err_invalid_reference_qualifier_application) << "volatile";
4649 // 'restrict' is permitted as an extension.
4650 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4651 Diag(DS.getAtomicSpecLoc(),
4652 diag::err_invalid_reference_qualifier_application) << "_Atomic";
4655 // Recursively parse the declarator.
4656 ParseDeclaratorInternal(D, DirectDeclParser);
4658 if (D.getNumTypeObjects() > 0) {
4659 // C++ [dcl.ref]p4: There shall be no references to references.
4660 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
4661 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
4662 if (const IdentifierInfo *II = D.getIdentifier())
4663 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
4666 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
4669 // Once we've complained about the reference-to-reference, we
4670 // can go ahead and build the (technically ill-formed)
4671 // declarator: reference collapsing will take care of it.
4675 // Remember that we parsed a reference type.
4676 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
4683 // When correcting from misplaced brackets before the identifier, the location
4684 // is saved inside the declarator so that other diagnostic messages can use
4685 // them. This extracts and returns that location, or returns the provided
4686 // location if a stored location does not exist.
4687 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
4688 SourceLocation Loc) {
4689 if (D.getName().StartLocation.isInvalid() &&
4690 D.getName().EndLocation.isValid())
4691 return D.getName().EndLocation;
4696 /// ParseDirectDeclarator
4697 /// direct-declarator: [C99 6.7.5]
4698 /// [C99] identifier
4699 /// '(' declarator ')'
4700 /// [GNU] '(' attributes declarator ')'
4701 /// [C90] direct-declarator '[' constant-expression[opt] ']'
4702 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
4703 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
4704 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
4705 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
4706 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
4707 /// attribute-specifier-seq[opt]
4708 /// direct-declarator '(' parameter-type-list ')'
4709 /// direct-declarator '(' identifier-list[opt] ')'
4710 /// [GNU] direct-declarator '(' parameter-forward-declarations
4711 /// parameter-type-list[opt] ')'
4712 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
4713 /// cv-qualifier-seq[opt] exception-specification[opt]
4714 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
4715 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
4716 /// ref-qualifier[opt] exception-specification[opt]
4717 /// [C++] declarator-id
4718 /// [C++11] declarator-id attribute-specifier-seq[opt]
4720 /// declarator-id: [C++ 8]
4721 /// '...'[opt] id-expression
4722 /// '::'[opt] nested-name-specifier[opt] type-name
4724 /// id-expression: [C++ 5.1]
4728 /// unqualified-id: [C++ 5.1]
4730 /// operator-function-id
4731 /// conversion-function-id
4735 /// Note, any additional constructs added here may need corresponding changes
4736 /// in isConstructorDeclarator.
4737 void Parser::ParseDirectDeclarator(Declarator &D) {
4738 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
4740 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
4741 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
4742 // this context it is a bitfield. Also in range-based for statement colon
4743 // may delimit for-range-declaration.
4744 ColonProtectionRAIIObject X(*this,
4745 D.getContext() == Declarator::MemberContext ||
4746 (D.getContext() == Declarator::ForContext &&
4747 getLangOpts().CPlusPlus11));
4749 // ParseDeclaratorInternal might already have parsed the scope.
4750 if (D.getCXXScopeSpec().isEmpty()) {
4751 bool EnteringContext = D.getContext() == Declarator::FileContext ||
4752 D.getContext() == Declarator::MemberContext;
4753 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(),
4757 if (D.getCXXScopeSpec().isValid()) {
4758 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
4759 // Change the declaration context for name lookup, until this function
4760 // is exited (and the declarator has been parsed).
4761 DeclScopeObj.EnterDeclaratorScope();
4764 // C++0x [dcl.fct]p14:
4765 // There is a syntactic ambiguity when an ellipsis occurs at the end
4766 // of a parameter-declaration-clause without a preceding comma. In
4767 // this case, the ellipsis is parsed as part of the
4768 // abstract-declarator if the type of the parameter names a template
4769 // parameter pack that has not been expanded; otherwise, it is parsed
4770 // as part of the parameter-declaration-clause.
4771 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
4772 !((D.getContext() == Declarator::PrototypeContext ||
4773 D.getContext() == Declarator::LambdaExprParameterContext ||
4774 D.getContext() == Declarator::BlockLiteralContext) &&
4775 NextToken().is(tok::r_paren) &&
4776 !D.hasGroupingParens() &&
4777 !Actions.containsUnexpandedParameterPacks(D))) {
4778 SourceLocation EllipsisLoc = ConsumeToken();
4779 if (isPtrOperatorToken(Tok.getKind(), getLangOpts())) {
4780 // The ellipsis was put in the wrong place. Recover, and explain to
4781 // the user what they should have done.
4783 if (EllipsisLoc.isValid())
4784 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
4787 D.setEllipsisLoc(EllipsisLoc);
4789 // The ellipsis can't be followed by a parenthesized declarator. We
4790 // check for that in ParseParenDeclarator, after we have disambiguated
4791 // the l_paren token.
4794 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
4795 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
4796 // We found something that indicates the start of an unqualified-id.
4797 // Parse that unqualified-id.
4798 bool AllowConstructorName;
4799 if (D.getDeclSpec().hasTypeSpecifier())
4800 AllowConstructorName = false;
4801 else if (D.getCXXScopeSpec().isSet())
4802 AllowConstructorName =
4803 (D.getContext() == Declarator::FileContext ||
4804 D.getContext() == Declarator::MemberContext);
4806 AllowConstructorName = (D.getContext() == Declarator::MemberContext);
4808 SourceLocation TemplateKWLoc;
4809 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
4810 /*EnteringContext=*/true,
4811 /*AllowDestructorName=*/true,
4812 AllowConstructorName,
4816 // Once we're past the identifier, if the scope was bad, mark the
4817 // whole declarator bad.
4818 D.getCXXScopeSpec().isInvalid()) {
4819 D.SetIdentifier(nullptr, Tok.getLocation());
4820 D.setInvalidType(true);
4822 // Parsed the unqualified-id; update range information and move along.
4823 if (D.getSourceRange().getBegin().isInvalid())
4824 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
4825 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
4827 goto PastIdentifier;
4829 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
4830 assert(!getLangOpts().CPlusPlus &&
4831 "There's a C++-specific check for tok::identifier above");
4832 assert(Tok.getIdentifierInfo() && "Not an identifier?");
4833 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
4834 D.SetRangeEnd(Tok.getLocation());
4836 goto PastIdentifier;
4837 } else if (Tok.is(tok::identifier) && D.diagnoseIdentifier()) {
4838 // A virt-specifier isn't treated as an identifier if it appears after a
4839 // trailing-return-type.
4840 if (D.getContext() != Declarator::TrailingReturnContext ||
4841 !isCXX11VirtSpecifier(Tok)) {
4842 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
4843 << FixItHint::CreateRemoval(Tok.getLocation());
4844 D.SetIdentifier(nullptr, Tok.getLocation());
4846 goto PastIdentifier;
4850 if (Tok.is(tok::l_paren)) {
4851 // direct-declarator: '(' declarator ')'
4852 // direct-declarator: '(' attributes declarator ')'
4853 // Example: 'char (*X)' or 'int (*XX)(void)'
4854 ParseParenDeclarator(D);
4856 // If the declarator was parenthesized, we entered the declarator
4857 // scope when parsing the parenthesized declarator, then exited
4858 // the scope already. Re-enter the scope, if we need to.
4859 if (D.getCXXScopeSpec().isSet()) {
4860 // If there was an error parsing parenthesized declarator, declarator
4861 // scope may have been entered before. Don't do it again.
4862 if (!D.isInvalidType() &&
4863 Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
4864 // Change the declaration context for name lookup, until this function
4865 // is exited (and the declarator has been parsed).
4866 DeclScopeObj.EnterDeclaratorScope();
4868 } else if (D.mayOmitIdentifier()) {
4869 // This could be something simple like "int" (in which case the declarator
4870 // portion is empty), if an abstract-declarator is allowed.
4871 D.SetIdentifier(nullptr, Tok.getLocation());
4873 // The grammar for abstract-pack-declarator does not allow grouping parens.
4874 // FIXME: Revisit this once core issue 1488 is resolved.
4875 if (D.hasEllipsis() && D.hasGroupingParens())
4876 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
4877 diag::ext_abstract_pack_declarator_parens);
4879 if (Tok.getKind() == tok::annot_pragma_parser_crash)
4881 if (Tok.is(tok::l_square))
4882 return ParseMisplacedBracketDeclarator(D);
4883 if (D.getContext() == Declarator::MemberContext) {
4884 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
4885 diag::err_expected_member_name_or_semi)
4886 << (D.getDeclSpec().isEmpty() ? SourceRange()
4887 : D.getDeclSpec().getSourceRange());
4888 } else if (getLangOpts().CPlusPlus) {
4889 if (Tok.is(tok::period) || Tok.is(tok::arrow))
4890 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
4892 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
4893 if (Tok.isAtStartOfLine() && Loc.isValid())
4894 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
4895 << getLangOpts().CPlusPlus;
4897 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
4898 diag::err_expected_unqualified_id)
4899 << getLangOpts().CPlusPlus;
4902 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
4903 diag::err_expected_either)
4904 << tok::identifier << tok::l_paren;
4906 D.SetIdentifier(nullptr, Tok.getLocation());
4907 D.setInvalidType(true);
4911 assert(D.isPastIdentifier() &&
4912 "Haven't past the location of the identifier yet?");
4914 // Don't parse attributes unless we have parsed an unparenthesized name.
4915 if (D.hasName() && !D.getNumTypeObjects())
4916 MaybeParseCXX11Attributes(D);
4919 if (Tok.is(tok::l_paren)) {
4920 // Enter function-declaration scope, limiting any declarators to the
4921 // function prototype scope, including parameter declarators.
4922 ParseScope PrototypeScope(this,
4923 Scope::FunctionPrototypeScope|Scope::DeclScope|
4924 (D.isFunctionDeclaratorAFunctionDeclaration()
4925 ? Scope::FunctionDeclarationScope : 0));
4927 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
4928 // In such a case, check if we actually have a function declarator; if it
4929 // is not, the declarator has been fully parsed.
4930 bool IsAmbiguous = false;
4931 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
4932 // The name of the declarator, if any, is tentatively declared within
4933 // a possible direct initializer.
4934 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
4935 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
4936 TentativelyDeclaredIdentifiers.pop_back();
4937 if (!IsFunctionDecl)
4940 ParsedAttributes attrs(AttrFactory);
4941 BalancedDelimiterTracker T(*this, tok::l_paren);
4943 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
4944 PrototypeScope.Exit();
4945 } else if (Tok.is(tok::l_square)) {
4946 ParseBracketDeclarator(D);
4953 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
4954 /// only called before the identifier, so these are most likely just grouping
4955 /// parens for precedence. If we find that these are actually function
4956 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
4958 /// direct-declarator:
4959 /// '(' declarator ')'
4960 /// [GNU] '(' attributes declarator ')'
4961 /// direct-declarator '(' parameter-type-list ')'
4962 /// direct-declarator '(' identifier-list[opt] ')'
4963 /// [GNU] direct-declarator '(' parameter-forward-declarations
4964 /// parameter-type-list[opt] ')'
4966 void Parser::ParseParenDeclarator(Declarator &D) {
4967 BalancedDelimiterTracker T(*this, tok::l_paren);
4970 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
4972 // Eat any attributes before we look at whether this is a grouping or function
4973 // declarator paren. If this is a grouping paren, the attribute applies to
4974 // the type being built up, for example:
4975 // int (__attribute__(()) *x)(long y)
4976 // If this ends up not being a grouping paren, the attribute applies to the
4977 // first argument, for example:
4978 // int (__attribute__(()) int x)
4979 // In either case, we need to eat any attributes to be able to determine what
4980 // sort of paren this is.
4982 ParsedAttributes attrs(AttrFactory);
4983 bool RequiresArg = false;
4984 if (Tok.is(tok::kw___attribute)) {
4985 ParseGNUAttributes(attrs);
4987 // We require that the argument list (if this is a non-grouping paren) be
4988 // present even if the attribute list was empty.
4992 // Eat any Microsoft extensions.
4993 ParseMicrosoftTypeAttributes(attrs);
4995 // Eat any Borland extensions.
4996 if (Tok.is(tok::kw___pascal))
4997 ParseBorlandTypeAttributes(attrs);
4999 // If we haven't past the identifier yet (or where the identifier would be
5000 // stored, if this is an abstract declarator), then this is probably just
5001 // grouping parens. However, if this could be an abstract-declarator, then
5002 // this could also be the start of function arguments (consider 'void()').
5005 if (!D.mayOmitIdentifier()) {
5006 // If this can't be an abstract-declarator, this *must* be a grouping
5007 // paren, because we haven't seen the identifier yet.
5009 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
5010 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
5011 NextToken().is(tok::r_paren)) || // C++ int(...)
5012 isDeclarationSpecifier() || // 'int(int)' is a function.
5013 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
5014 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
5015 // considered to be a type, not a K&R identifier-list.
5018 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
5022 // If this is a grouping paren, handle:
5023 // direct-declarator: '(' declarator ')'
5024 // direct-declarator: '(' attributes declarator ')'
5026 SourceLocation EllipsisLoc = D.getEllipsisLoc();
5027 D.setEllipsisLoc(SourceLocation());
5029 bool hadGroupingParens = D.hasGroupingParens();
5030 D.setGroupingParens(true);
5031 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5034 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
5035 T.getCloseLocation()),
5036 attrs, T.getCloseLocation());
5038 D.setGroupingParens(hadGroupingParens);
5040 // An ellipsis cannot be placed outside parentheses.
5041 if (EllipsisLoc.isValid())
5042 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5047 // Okay, if this wasn't a grouping paren, it must be the start of a function
5048 // argument list. Recognize that this declarator will never have an
5049 // identifier (and remember where it would have been), then call into
5050 // ParseFunctionDeclarator to handle of argument list.
5051 D.SetIdentifier(nullptr, Tok.getLocation());
5053 // Enter function-declaration scope, limiting any declarators to the
5054 // function prototype scope, including parameter declarators.
5055 ParseScope PrototypeScope(this,
5056 Scope::FunctionPrototypeScope | Scope::DeclScope |
5057 (D.isFunctionDeclaratorAFunctionDeclaration()
5058 ? Scope::FunctionDeclarationScope : 0));
5059 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
5060 PrototypeScope.Exit();
5063 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
5064 /// declarator D up to a paren, which indicates that we are parsing function
5067 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
5068 /// immediately after the open paren - they should be considered to be the
5069 /// first argument of a parameter.
5071 /// If RequiresArg is true, then the first argument of the function is required
5072 /// to be present and required to not be an identifier list.
5074 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
5075 /// (C++11) ref-qualifier[opt], exception-specification[opt],
5076 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
5078 /// [C++11] exception-specification:
5079 /// dynamic-exception-specification
5080 /// noexcept-specification
5082 void Parser::ParseFunctionDeclarator(Declarator &D,
5083 ParsedAttributes &FirstArgAttrs,
5084 BalancedDelimiterTracker &Tracker,
5087 assert(getCurScope()->isFunctionPrototypeScope() &&
5088 "Should call from a Function scope");
5089 // lparen is already consumed!
5090 assert(D.isPastIdentifier() && "Should not call before identifier!");
5092 // This should be true when the function has typed arguments.
5093 // Otherwise, it is treated as a K&R-style function.
5094 bool HasProto = false;
5095 // Build up an array of information about the parsed arguments.
5096 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
5097 // Remember where we see an ellipsis, if any.
5098 SourceLocation EllipsisLoc;
5100 DeclSpec DS(AttrFactory);
5101 bool RefQualifierIsLValueRef = true;
5102 SourceLocation RefQualifierLoc;
5103 SourceLocation ConstQualifierLoc;
5104 SourceLocation VolatileQualifierLoc;
5105 ExceptionSpecificationType ESpecType = EST_None;
5106 SourceRange ESpecRange;
5107 SmallVector<ParsedType, 2> DynamicExceptions;
5108 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5109 ExprResult NoexceptExpr;
5110 ParsedAttributes FnAttrs(AttrFactory);
5111 TypeResult TrailingReturnType;
5113 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
5114 EndLoc is the end location for the function declarator.
5115 They differ for trailing return types. */
5116 SourceLocation StartLoc, LocalEndLoc, EndLoc;
5117 SourceLocation LParenLoc, RParenLoc;
5118 LParenLoc = Tracker.getOpenLocation();
5119 StartLoc = LParenLoc;
5121 if (isFunctionDeclaratorIdentifierList()) {
5123 Diag(Tok, diag::err_argument_required_after_attribute);
5125 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
5127 Tracker.consumeClose();
5128 RParenLoc = Tracker.getCloseLocation();
5129 LocalEndLoc = RParenLoc;
5132 if (Tok.isNot(tok::r_paren))
5133 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
5135 else if (RequiresArg)
5136 Diag(Tok, diag::err_argument_required_after_attribute);
5138 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
5140 // If we have the closing ')', eat it.
5141 Tracker.consumeClose();
5142 RParenLoc = Tracker.getCloseLocation();
5143 LocalEndLoc = RParenLoc;
5146 if (getLangOpts().CPlusPlus) {
5147 // FIXME: Accept these components in any order, and produce fixits to
5148 // correct the order if the user gets it wrong. Ideally we should deal
5149 // with the virt-specifier-seq and pure-specifier in the same way.
5151 // Parse cv-qualifier-seq[opt].
5152 ParseTypeQualifierListOpt(DS, /*VendorAttributesAllowed*/ false,
5153 /*CXX11AttributesAllowed*/ false,
5154 /*AtomicAllowed*/ false);
5155 if (!DS.getSourceRange().getEnd().isInvalid()) {
5156 EndLoc = DS.getSourceRange().getEnd();
5157 ConstQualifierLoc = DS.getConstSpecLoc();
5158 VolatileQualifierLoc = DS.getVolatileSpecLoc();
5161 // Parse ref-qualifier[opt].
5162 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
5163 Diag(Tok, getLangOpts().CPlusPlus11 ?
5164 diag::warn_cxx98_compat_ref_qualifier :
5165 diag::ext_ref_qualifier);
5167 RefQualifierIsLValueRef = Tok.is(tok::amp);
5168 RefQualifierLoc = ConsumeToken();
5169 EndLoc = RefQualifierLoc;
5172 // C++11 [expr.prim.general]p3:
5173 // If a declaration declares a member function or member function
5174 // template of a class X, the expression this is a prvalue of type
5175 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5176 // and the end of the function-definition, member-declarator, or
5178 // FIXME: currently, "static" case isn't handled correctly.
5179 bool IsCXX11MemberFunction =
5180 getLangOpts().CPlusPlus11 &&
5181 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5182 (D.getContext() == Declarator::MemberContext
5183 ? !D.getDeclSpec().isFriendSpecified()
5184 : D.getContext() == Declarator::FileContext &&
5185 D.getCXXScopeSpec().isValid() &&
5186 Actions.CurContext->isRecord());
5187 Sema::CXXThisScopeRAII ThisScope(Actions,
5188 dyn_cast<CXXRecordDecl>(Actions.CurContext),
5189 DS.getTypeQualifiers() |
5190 (D.getDeclSpec().isConstexprSpecified() &&
5191 !getLangOpts().CPlusPlus1y
5192 ? Qualifiers::Const : 0),
5193 IsCXX11MemberFunction);
5195 // Parse exception-specification[opt].
5196 ESpecType = tryParseExceptionSpecification(ESpecRange,
5198 DynamicExceptionRanges,
5200 if (ESpecType != EST_None)
5201 EndLoc = ESpecRange.getEnd();
5203 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
5204 // after the exception-specification.
5205 MaybeParseCXX11Attributes(FnAttrs);
5207 // Parse trailing-return-type[opt].
5208 LocalEndLoc = EndLoc;
5209 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
5210 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
5211 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
5212 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5213 LocalEndLoc = Tok.getLocation();
5215 TrailingReturnType = ParseTrailingReturnType(Range);
5216 EndLoc = Range.getEnd();
5221 // Remember that we parsed a function type, and remember the attributes.
5222 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
5225 ParamInfo.data(), ParamInfo.size(),
5226 EllipsisLoc, RParenLoc,
5227 DS.getTypeQualifiers(),
5228 RefQualifierIsLValueRef,
5229 RefQualifierLoc, ConstQualifierLoc,
5230 VolatileQualifierLoc,
5231 /*MutableLoc=*/SourceLocation(),
5232 ESpecType, ESpecRange.getBegin(),
5233 DynamicExceptions.data(),
5234 DynamicExceptionRanges.data(),
5235 DynamicExceptions.size(),
5236 NoexceptExpr.isUsable() ?
5237 NoexceptExpr.get() : nullptr,
5238 StartLoc, LocalEndLoc, D,
5239 TrailingReturnType),
5243 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
5244 /// identifier list form for a K&R-style function: void foo(a,b,c)
5246 /// Note that identifier-lists are only allowed for normal declarators, not for
5247 /// abstract-declarators.
5248 bool Parser::isFunctionDeclaratorIdentifierList() {
5249 return !getLangOpts().CPlusPlus
5250 && Tok.is(tok::identifier)
5251 && !TryAltiVecVectorToken()
5252 // K&R identifier lists can't have typedefs as identifiers, per C99
5254 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
5255 // Identifier lists follow a really simple grammar: the identifiers can
5256 // be followed *only* by a ", identifier" or ")". However, K&R
5257 // identifier lists are really rare in the brave new modern world, and
5258 // it is very common for someone to typo a type in a non-K&R style
5259 // list. If we are presented with something like: "void foo(intptr x,
5260 // float y)", we don't want to start parsing the function declarator as
5261 // though it is a K&R style declarator just because intptr is an
5264 // To handle this, we check to see if the token after the first
5265 // identifier is a "," or ")". Only then do we parse it as an
5267 && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren));
5270 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
5271 /// we found a K&R-style identifier list instead of a typed parameter list.
5273 /// After returning, ParamInfo will hold the parsed parameters.
5275 /// identifier-list: [C99 6.7.5]
5277 /// identifier-list ',' identifier
5279 void Parser::ParseFunctionDeclaratorIdentifierList(
5281 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
5282 // If there was no identifier specified for the declarator, either we are in
5283 // an abstract-declarator, or we are in a parameter declarator which was found
5284 // to be abstract. In abstract-declarators, identifier lists are not valid:
5286 if (!D.getIdentifier())
5287 Diag(Tok, diag::ext_ident_list_in_param);
5289 // Maintain an efficient lookup of params we have seen so far.
5290 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
5293 // If this isn't an identifier, report the error and skip until ')'.
5294 if (Tok.isNot(tok::identifier)) {
5295 Diag(Tok, diag::err_expected) << tok::identifier;
5296 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
5297 // Forget we parsed anything.
5302 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
5304 // Reject 'typedef int y; int test(x, y)', but continue parsing.
5305 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
5306 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
5308 // Verify that the argument identifier has not already been mentioned.
5309 if (!ParamsSoFar.insert(ParmII)) {
5310 Diag(Tok, diag::err_param_redefinition) << ParmII;
5312 // Remember this identifier in ParamInfo.
5313 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
5318 // Eat the identifier.
5320 // The list continues if we see a comma.
5321 } while (TryConsumeToken(tok::comma));
5324 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
5325 /// after the opening parenthesis. This function will not parse a K&R-style
5326 /// identifier list.
5328 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
5329 /// caller parsed those arguments immediately after the open paren - they should
5330 /// be considered to be part of the first parameter.
5332 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
5333 /// be the location of the ellipsis, if any was parsed.
5335 /// parameter-type-list: [C99 6.7.5]
5337 /// parameter-list ',' '...'
5338 /// [C++] parameter-list '...'
5340 /// parameter-list: [C99 6.7.5]
5341 /// parameter-declaration
5342 /// parameter-list ',' parameter-declaration
5344 /// parameter-declaration: [C99 6.7.5]
5345 /// declaration-specifiers declarator
5346 /// [C++] declaration-specifiers declarator '=' assignment-expression
5347 /// [C++11] initializer-clause
5348 /// [GNU] declaration-specifiers declarator attributes
5349 /// declaration-specifiers abstract-declarator[opt]
5350 /// [C++] declaration-specifiers abstract-declarator[opt]
5351 /// '=' assignment-expression
5352 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
5353 /// [C++11] attribute-specifier-seq parameter-declaration
5355 void Parser::ParseParameterDeclarationClause(
5357 ParsedAttributes &FirstArgAttrs,
5358 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
5359 SourceLocation &EllipsisLoc) {
5361 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
5362 // before deciding this was a parameter-declaration-clause.
5363 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
5366 // Parse the declaration-specifiers.
5367 // Just use the ParsingDeclaration "scope" of the declarator.
5368 DeclSpec DS(AttrFactory);
5370 // Parse any C++11 attributes.
5371 MaybeParseCXX11Attributes(DS.getAttributes());
5373 // Skip any Microsoft attributes before a param.
5374 MaybeParseMicrosoftAttributes(DS.getAttributes());
5376 SourceLocation DSStart = Tok.getLocation();
5378 // If the caller parsed attributes for the first argument, add them now.
5379 // Take them so that we only apply the attributes to the first parameter.
5380 // FIXME: If we can leave the attributes in the token stream somehow, we can
5381 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
5383 DS.takeAttributesFrom(FirstArgAttrs);
5385 ParseDeclarationSpecifiers(DS);
5388 // Parse the declarator. This is "PrototypeContext" or
5389 // "LambdaExprParameterContext", because we must accept either
5390 // 'declarator' or 'abstract-declarator' here.
5391 Declarator ParmDeclarator(DS,
5392 D.getContext() == Declarator::LambdaExprContext ?
5393 Declarator::LambdaExprParameterContext :
5394 Declarator::PrototypeContext);
5395 ParseDeclarator(ParmDeclarator);
5397 // Parse GNU attributes, if present.
5398 MaybeParseGNUAttributes(ParmDeclarator);
5400 // Remember this parsed parameter in ParamInfo.
5401 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
5403 // DefArgToks is used when the parsing of default arguments needs
5405 CachedTokens *DefArgToks = nullptr;
5407 // If no parameter was specified, verify that *something* was specified,
5408 // otherwise we have a missing type and identifier.
5409 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
5410 ParmDeclarator.getNumTypeObjects() == 0) {
5411 // Completely missing, emit error.
5412 Diag(DSStart, diag::err_missing_param);
5414 // Otherwise, we have something. Add it and let semantic analysis try
5415 // to grok it and add the result to the ParamInfo we are building.
5417 // Inform the actions module about the parameter declarator, so it gets
5418 // added to the current scope.
5419 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(),
5421 // Parse the default argument, if any. We parse the default
5422 // arguments in all dialects; the semantic analysis in
5423 // ActOnParamDefaultArgument will reject the default argument in
5425 if (Tok.is(tok::equal)) {
5426 SourceLocation EqualLoc = Tok.getLocation();
5428 // Parse the default argument
5429 if (D.getContext() == Declarator::MemberContext) {
5430 // If we're inside a class definition, cache the tokens
5431 // corresponding to the default argument. We'll actually parse
5432 // them when we see the end of the class definition.
5433 // FIXME: Can we use a smart pointer for Toks?
5434 DefArgToks = new CachedTokens;
5436 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
5438 DefArgToks = nullptr;
5439 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
5441 // Mark the end of the default argument so that we know when to
5442 // stop when we parse it later on.
5444 DefArgEnd.startToken();
5445 DefArgEnd.setKind(tok::cxx_defaultarg_end);
5446 DefArgEnd.setLocation(Tok.getLocation());
5447 DefArgToks->push_back(DefArgEnd);
5448 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
5449 (*DefArgToks)[1].getLocation());
5455 // The argument isn't actually potentially evaluated unless it is
5457 EnterExpressionEvaluationContext Eval(Actions,
5458 Sema::PotentiallyEvaluatedIfUsed,
5461 ExprResult DefArgResult;
5462 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
5463 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
5464 DefArgResult = ParseBraceInitializer();
5466 DefArgResult = ParseAssignmentExpression();
5467 if (DefArgResult.isInvalid()) {
5468 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
5469 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
5471 // Inform the actions module about the default argument
5472 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
5473 DefArgResult.get());
5478 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
5479 ParmDeclarator.getIdentifierLoc(),
5480 Param, DefArgToks));
5483 if (TryConsumeToken(tok::ellipsis, EllipsisLoc) &&
5484 !getLangOpts().CPlusPlus) {
5485 // We have ellipsis without a preceding ',', which is ill-formed
5486 // in C. Complain and provide the fix.
5487 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
5488 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
5492 // If the next token is a comma, consume it and keep reading arguments.
5493 } while (TryConsumeToken(tok::comma));
5496 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5497 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5498 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5499 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5500 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5501 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5502 /// attribute-specifier-seq[opt]
5503 void Parser::ParseBracketDeclarator(Declarator &D) {
5504 if (CheckProhibitedCXX11Attribute())
5507 BalancedDelimiterTracker T(*this, tok::l_square);
5510 // C array syntax has many features, but by-far the most common is [] and [4].
5511 // This code does a fast path to handle some of the most obvious cases.
5512 if (Tok.getKind() == tok::r_square) {
5514 ParsedAttributes attrs(AttrFactory);
5515 MaybeParseCXX11Attributes(attrs);
5517 // Remember that we parsed the empty array type.
5518 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
5519 T.getOpenLocation(),
5520 T.getCloseLocation()),
5521 attrs, T.getCloseLocation());
5523 } else if (Tok.getKind() == tok::numeric_constant &&
5524 GetLookAheadToken(1).is(tok::r_square)) {
5525 // [4] is very common. Parse the numeric constant expression.
5526 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
5530 ParsedAttributes attrs(AttrFactory);
5531 MaybeParseCXX11Attributes(attrs);
5533 // Remember that we parsed a array type, and remember its features.
5534 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false,
5536 T.getOpenLocation(),
5537 T.getCloseLocation()),
5538 attrs, T.getCloseLocation());
5542 // If valid, this location is the position where we read the 'static' keyword.
5543 SourceLocation StaticLoc;
5544 TryConsumeToken(tok::kw_static, StaticLoc);
5546 // If there is a type-qualifier-list, read it now.
5547 // Type qualifiers in an array subscript are a C99 feature.
5548 DeclSpec DS(AttrFactory);
5549 ParseTypeQualifierListOpt(DS, false /*no attributes*/);
5551 // If we haven't already read 'static', check to see if there is one after the
5552 // type-qualifier-list.
5553 if (!StaticLoc.isValid())
5554 TryConsumeToken(tok::kw_static, StaticLoc);
5556 // Handle "direct-declarator [ type-qual-list[opt] * ]".
5557 bool isStar = false;
5558 ExprResult NumElements;
5560 // Handle the case where we have '[*]' as the array size. However, a leading
5561 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
5562 // the token after the star is a ']'. Since stars in arrays are
5563 // infrequent, use of lookahead is not costly here.
5564 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
5565 ConsumeToken(); // Eat the '*'.
5567 if (StaticLoc.isValid()) {
5568 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
5569 StaticLoc = SourceLocation(); // Drop the static.
5572 } else if (Tok.isNot(tok::r_square)) {
5573 // Note, in C89, this production uses the constant-expr production instead
5574 // of assignment-expr. The only difference is that assignment-expr allows
5575 // things like '=' and '*='. Sema rejects these in C89 mode because they
5576 // are not i-c-e's, so we don't need to distinguish between the two here.
5578 // Parse the constant-expression or assignment-expression now (depending
5580 if (getLangOpts().CPlusPlus) {
5581 NumElements = ParseConstantExpression();
5583 EnterExpressionEvaluationContext Unevaluated(Actions,
5584 Sema::ConstantEvaluated);
5585 NumElements = ParseAssignmentExpression();
5589 // If there was an error parsing the assignment-expression, recover.
5590 if (NumElements.isInvalid()) {
5591 D.setInvalidType(true);
5592 // If the expression was invalid, skip it.
5593 SkipUntil(tok::r_square, StopAtSemi);
5599 ParsedAttributes attrs(AttrFactory);
5600 MaybeParseCXX11Attributes(attrs);
5602 // Remember that we parsed a array type, and remember its features.
5603 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
5604 StaticLoc.isValid(), isStar,
5606 T.getOpenLocation(),
5607 T.getCloseLocation()),
5608 attrs, T.getCloseLocation());
5611 /// Diagnose brackets before an identifier.
5612 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
5613 assert(Tok.is(tok::l_square) && "Missing opening bracket");
5614 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
5616 SourceLocation StartBracketLoc = Tok.getLocation();
5617 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
5619 while (Tok.is(tok::l_square)) {
5620 ParseBracketDeclarator(TempDeclarator);
5623 // Stuff the location of the start of the brackets into the Declarator.
5624 // The diagnostics from ParseDirectDeclarator will make more sense if
5625 // they use this location instead.
5626 if (Tok.is(tok::semi))
5627 D.getName().EndLocation = StartBracketLoc;
5629 SourceLocation SuggestParenLoc = Tok.getLocation();
5631 // Now that the brackets are removed, try parsing the declarator again.
5632 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5634 // Something went wrong parsing the brackets, in which case,
5635 // ParseBracketDeclarator has emitted an error, and we don't need to emit
5637 if (TempDeclarator.getNumTypeObjects() == 0)
5640 // Determine if parens will need to be suggested in the diagnostic.
5641 bool NeedParens = false;
5642 if (D.getNumTypeObjects() != 0) {
5643 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
5644 case DeclaratorChunk::Pointer:
5645 case DeclaratorChunk::Reference:
5646 case DeclaratorChunk::BlockPointer:
5647 case DeclaratorChunk::MemberPointer:
5650 case DeclaratorChunk::Array:
5651 case DeclaratorChunk::Function:
5652 case DeclaratorChunk::Paren:
5658 // Create a DeclaratorChunk for the inserted parens.
5659 ParsedAttributes attrs(AttrFactory);
5660 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
5661 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), attrs,
5665 // Adding back the bracket info to the end of the Declarator.
5666 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
5667 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
5668 ParsedAttributes attrs(AttrFactory);
5669 attrs.set(Chunk.Common.AttrList);
5670 D.AddTypeInfo(Chunk, attrs, SourceLocation());
5673 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
5674 // If parentheses are required, always suggest them.
5675 if (!D.getIdentifier() && !NeedParens)
5678 SourceLocation EndBracketLoc = TempDeclarator.getLocEnd();
5680 // Generate the move bracket error message.
5681 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
5682 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
5685 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
5686 << getLangOpts().CPlusPlus
5687 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
5688 << FixItHint::CreateInsertion(EndLoc, ")")
5689 << FixItHint::CreateInsertionFromRange(
5690 EndLoc, CharSourceRange(BracketRange, true))
5691 << FixItHint::CreateRemoval(BracketRange);
5693 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
5694 << getLangOpts().CPlusPlus
5695 << FixItHint::CreateInsertionFromRange(
5696 EndLoc, CharSourceRange(BracketRange, true))
5697 << FixItHint::CreateRemoval(BracketRange);
5701 /// [GNU] typeof-specifier:
5702 /// typeof ( expressions )
5703 /// typeof ( type-name )
5704 /// [GNU/C++] typeof unary-expression
5706 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
5707 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
5709 SourceLocation StartLoc = ConsumeToken();
5711 const bool hasParens = Tok.is(tok::l_paren);
5713 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
5714 Sema::ReuseLambdaContextDecl);
5718 SourceRange CastRange;
5719 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
5722 DS.setTypeofParensRange(CastRange);
5724 if (CastRange.getEnd().isInvalid())
5725 // FIXME: Not accurate, the range gets one token more than it should.
5726 DS.SetRangeEnd(Tok.getLocation());
5728 DS.SetRangeEnd(CastRange.getEnd());
5732 DS.SetTypeSpecError();
5736 const char *PrevSpec = nullptr;
5738 // Check for duplicate type specifiers (e.g. "int typeof(int)").
5739 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
5741 Actions.getASTContext().getPrintingPolicy()))
5742 Diag(StartLoc, DiagID) << PrevSpec;
5746 // If we get here, the operand to the typeof was an expresion.
5747 if (Operand.isInvalid()) {
5748 DS.SetTypeSpecError();
5752 // We might need to transform the operand if it is potentially evaluated.
5753 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
5754 if (Operand.isInvalid()) {
5755 DS.SetTypeSpecError();
5759 const char *PrevSpec = nullptr;
5761 // Check for duplicate type specifiers (e.g. "int typeof(int)").
5762 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
5763 DiagID, Operand.get(),
5764 Actions.getASTContext().getPrintingPolicy()))
5765 Diag(StartLoc, DiagID) << PrevSpec;
5768 /// [C11] atomic-specifier:
5769 /// _Atomic ( type-name )
5771 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
5772 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
5773 "Not an atomic specifier");
5775 SourceLocation StartLoc = ConsumeToken();
5776 BalancedDelimiterTracker T(*this, tok::l_paren);
5777 if (T.consumeOpen())
5780 TypeResult Result = ParseTypeName();
5781 if (Result.isInvalid()) {
5782 SkipUntil(tok::r_paren, StopAtSemi);
5789 if (T.getCloseLocation().isInvalid())
5792 DS.setTypeofParensRange(T.getRange());
5793 DS.SetRangeEnd(T.getCloseLocation());
5795 const char *PrevSpec = nullptr;
5797 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
5798 DiagID, Result.get(),
5799 Actions.getASTContext().getPrintingPolicy()))
5800 Diag(StartLoc, DiagID) << PrevSpec;
5804 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
5805 /// from TryAltiVecVectorToken.
5806 bool Parser::TryAltiVecVectorTokenOutOfLine() {
5807 Token Next = NextToken();
5808 switch (Next.getKind()) {
5809 default: return false;
5812 case tok::kw_signed:
5813 case tok::kw_unsigned:
5818 case tok::kw_double:
5820 case tok::kw___pixel:
5821 Tok.setKind(tok::kw___vector);
5823 case tok::identifier:
5824 if (Next.getIdentifierInfo() == Ident_pixel) {
5825 Tok.setKind(tok::kw___vector);
5828 if (Next.getIdentifierInfo() == Ident_bool) {
5829 Tok.setKind(tok::kw___vector);
5836 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
5837 const char *&PrevSpec, unsigned &DiagID,
5839 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
5840 if (Tok.getIdentifierInfo() == Ident_vector) {
5841 Token Next = NextToken();
5842 switch (Next.getKind()) {
5845 case tok::kw_signed:
5846 case tok::kw_unsigned:
5851 case tok::kw_double:
5853 case tok::kw___pixel:
5854 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
5856 case tok::identifier:
5857 if (Next.getIdentifierInfo() == Ident_pixel) {
5858 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
5861 if (Next.getIdentifierInfo() == Ident_bool) {
5862 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
5869 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
5870 DS.isTypeAltiVecVector()) {
5871 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
5873 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
5874 DS.isTypeAltiVecVector()) {
5875 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);