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.isAnnotation())
148 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
152 SourceLocation AttrNameLoc = ConsumeToken();
154 if (Tok.isNot(tok::l_paren)) {
155 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
156 AttributeList::AS_GNU);
160 // Handle "parameterized" attributes
161 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
162 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
163 SourceLocation(), AttributeList::AS_GNU, D);
167 // Handle attributes with arguments that require late parsing.
168 LateParsedAttribute *LA =
169 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
170 LateAttrs->push_back(LA);
172 // Attributes in a class are parsed at the end of the class, along
173 // with other late-parsed declarations.
174 if (!ClassStack.empty() && !LateAttrs->parseSoon())
175 getCurrentClass().LateParsedDeclarations.push_back(LA);
177 // consume everything up to and including the matching right parens
178 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false);
182 Eof.setLocation(Tok.getLocation());
183 LA->Toks.push_back(Eof);
186 if (ExpectAndConsume(tok::r_paren))
187 SkipUntil(tok::r_paren, StopAtSemi);
188 SourceLocation Loc = Tok.getLocation();
189 if (ExpectAndConsume(tok::r_paren))
190 SkipUntil(tok::r_paren, StopAtSemi);
196 /// \brief Normalizes an attribute name by dropping prefixed and suffixed __.
197 static StringRef normalizeAttrName(StringRef Name) {
198 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
199 Name = Name.drop_front(2).drop_back(2);
203 /// \brief Determine whether the given attribute has an identifier argument.
204 static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
205 #define CLANG_ATTR_IDENTIFIER_ARG_LIST
206 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
207 #include "clang/Parse/AttrParserStringSwitches.inc"
209 #undef CLANG_ATTR_IDENTIFIER_ARG_LIST
212 /// \brief Determine whether the given attribute parses a type argument.
213 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
214 #define CLANG_ATTR_TYPE_ARG_LIST
215 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
216 #include "clang/Parse/AttrParserStringSwitches.inc"
218 #undef CLANG_ATTR_TYPE_ARG_LIST
221 /// \brief Determine whether the given attribute requires parsing its arguments
222 /// in an unevaluated context or not.
223 static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
224 #define CLANG_ATTR_ARG_CONTEXT_LIST
225 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
226 #include "clang/Parse/AttrParserStringSwitches.inc"
228 #undef CLANG_ATTR_ARG_CONTEXT_LIST
231 IdentifierLoc *Parser::ParseIdentifierLoc() {
232 assert(Tok.is(tok::identifier) && "expected an identifier");
233 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
235 Tok.getIdentifierInfo());
240 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
241 SourceLocation AttrNameLoc,
242 ParsedAttributes &Attrs,
243 SourceLocation *EndLoc,
244 IdentifierInfo *ScopeName,
245 SourceLocation ScopeLoc,
246 AttributeList::Syntax Syntax) {
247 BalancedDelimiterTracker Parens(*this, tok::l_paren);
248 Parens.consumeOpen();
251 if (Tok.isNot(tok::r_paren))
254 if (Parens.consumeClose())
261 Attrs.addNewTypeAttr(&AttrName,
262 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
263 ScopeName, ScopeLoc, T.get(), Syntax);
265 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
266 ScopeName, ScopeLoc, nullptr, 0, Syntax);
269 unsigned Parser::ParseAttributeArgsCommon(
270 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
271 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
272 SourceLocation ScopeLoc, AttributeList::Syntax Syntax) {
273 // Ignore the left paren location for now.
277 if (Tok.is(tok::identifier)) {
278 // If this attribute wants an 'identifier' argument, make it so.
279 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName);
280 AttributeList::Kind AttrKind =
281 AttributeList::getKind(AttrName, ScopeName, Syntax);
283 // If we don't know how to parse this attribute, but this is the only
284 // token in this argument, assume it's meant to be an identifier.
285 if (AttrKind == AttributeList::UnknownAttribute ||
286 AttrKind == AttributeList::IgnoredAttribute) {
287 const Token &Next = NextToken();
288 IsIdentifierArg = Next.is(tok::r_paren) || Next.is(tok::comma);
292 ArgExprs.push_back(ParseIdentifierLoc());
295 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
297 if (!ArgExprs.empty())
300 // Parse the non-empty comma-separated list of expressions.
302 std::unique_ptr<EnterExpressionEvaluationContext> Unevaluated;
303 if (attributeParsedArgsUnevaluated(*AttrName))
305 new EnterExpressionEvaluationContext(Actions, Sema::Unevaluated));
308 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
309 if (ArgExpr.isInvalid()) {
310 SkipUntil(tok::r_paren, StopAtSemi);
313 ArgExprs.push_back(ArgExpr.get());
314 // Eat the comma, move to the next argument
315 } while (TryConsumeToken(tok::comma));
318 SourceLocation RParen = Tok.getLocation();
319 if (!ExpectAndConsume(tok::r_paren)) {
320 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
321 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
322 ArgExprs.data(), ArgExprs.size(), Syntax);
328 return static_cast<unsigned>(ArgExprs.size());
331 /// Parse the arguments to a parameterized GNU attribute or
332 /// a C++11 attribute in "gnu" namespace.
333 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
334 SourceLocation AttrNameLoc,
335 ParsedAttributes &Attrs,
336 SourceLocation *EndLoc,
337 IdentifierInfo *ScopeName,
338 SourceLocation ScopeLoc,
339 AttributeList::Syntax Syntax,
342 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
344 AttributeList::Kind AttrKind =
345 AttributeList::getKind(AttrName, ScopeName, Syntax);
347 if (AttrKind == AttributeList::AT_Availability) {
348 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
351 } else if (AttrKind == AttributeList::AT_ObjCBridgeRelated) {
352 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
353 ScopeName, ScopeLoc, Syntax);
355 } else if (AttrKind == AttributeList::AT_TypeTagForDatatype) {
356 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
357 ScopeName, ScopeLoc, Syntax);
359 } else if (attributeIsTypeArgAttr(*AttrName)) {
360 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
365 // These may refer to the function arguments, but need to be parsed early to
366 // participate in determining whether it's a redeclaration.
367 std::unique_ptr<ParseScope> PrototypeScope;
368 if (AttrName->isStr("enable_if") && D && D->isFunctionDeclarator()) {
369 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
370 PrototypeScope.reset(new ParseScope(this, Scope::FunctionPrototypeScope |
371 Scope::FunctionDeclarationScope |
373 for (unsigned i = 0; i != FTI.NumParams; ++i) {
374 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
375 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
379 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
383 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
384 SourceLocation AttrNameLoc,
385 ParsedAttributes &Attrs) {
386 // If the attribute isn't known, we will not attempt to parse any
388 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
389 getTargetInfo().getTriple(), getLangOpts())) {
390 // Eat the left paren, then skip to the ending right paren.
392 SkipUntil(tok::r_paren);
396 SourceLocation OpenParenLoc = Tok.getLocation();
398 if (AttrName->getName() == "property") {
399 // The property declspec is more complex in that it can take one or two
400 // assignment expressions as a parameter, but the lhs of the assignment
401 // must be named get or put.
403 BalancedDelimiterTracker T(*this, tok::l_paren);
404 T.expectAndConsume(diag::err_expected_lparen_after,
405 AttrName->getNameStart(), tok::r_paren);
410 AK_Get = 1 // indices into AccessorNames
412 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
413 bool HasInvalidAccessor = false;
415 // Parse the accessor specifications.
417 // Stop if this doesn't look like an accessor spec.
418 if (!Tok.is(tok::identifier)) {
419 // If the user wrote a completely empty list, use a special diagnostic.
420 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
421 AccessorNames[AK_Put] == nullptr &&
422 AccessorNames[AK_Get] == nullptr) {
423 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
427 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
432 SourceLocation KindLoc = Tok.getLocation();
433 StringRef KindStr = Tok.getIdentifierInfo()->getName();
434 if (KindStr == "get") {
436 } else if (KindStr == "put") {
439 // Recover from the common mistake of using 'set' instead of 'put'.
440 } else if (KindStr == "set") {
441 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
442 << FixItHint::CreateReplacement(KindLoc, "put");
445 // Handle the mistake of forgetting the accessor kind by skipping
447 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
448 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
450 HasInvalidAccessor = true;
451 goto next_property_accessor;
453 // Otherwise, complain about the unknown accessor kind.
455 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
456 HasInvalidAccessor = true;
459 // Try to keep parsing unless it doesn't look like an accessor spec.
460 if (!NextToken().is(tok::equal))
464 // Consume the identifier.
468 if (!TryConsumeToken(tok::equal)) {
469 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
474 // Expect the method name.
475 if (!Tok.is(tok::identifier)) {
476 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
480 if (Kind == AK_Invalid) {
481 // Just drop invalid accessors.
482 } else if (AccessorNames[Kind] != nullptr) {
483 // Complain about the repeated accessor, ignore it, and keep parsing.
484 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
486 AccessorNames[Kind] = Tok.getIdentifierInfo();
490 next_property_accessor:
491 // Keep processing accessors until we run out.
492 if (TryConsumeToken(tok::comma))
495 // If we run into the ')', stop without consuming it.
496 if (Tok.is(tok::r_paren))
499 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
503 // Only add the property attribute if it was well-formed.
504 if (!HasInvalidAccessor)
505 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
506 AccessorNames[AK_Get], AccessorNames[AK_Put],
507 AttributeList::AS_Declspec);
509 return !HasInvalidAccessor;
513 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
514 SourceLocation(), AttributeList::AS_Declspec);
516 // If this attribute's args were parsed, and it was expected to have
517 // arguments but none were provided, emit a diagnostic.
518 const AttributeList *Attr = Attrs.getList();
519 if (Attr && Attr->getMaxArgs() && !NumArgs) {
520 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
526 /// [MS] decl-specifier:
527 /// __declspec ( extended-decl-modifier-seq )
529 /// [MS] extended-decl-modifier-seq:
530 /// extended-decl-modifier[opt]
531 /// extended-decl-modifier extended-decl-modifier-seq
532 void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
533 SourceLocation *End) {
534 assert((getLangOpts().MicrosoftExt || getLangOpts().Borland ||
535 getLangOpts().CUDA) &&
536 "Incorrect language options for parsing __declspec");
537 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
539 while (Tok.is(tok::kw___declspec)) {
541 BalancedDelimiterTracker T(*this, tok::l_paren);
542 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
546 // An empty declspec is perfectly legal and should not warn. Additionally,
547 // you can specify multiple attributes per declspec.
548 while (Tok.isNot(tok::r_paren)) {
549 // Attribute not present.
550 if (TryConsumeToken(tok::comma))
553 // We expect either a well-known identifier or a generic string. Anything
554 // else is a malformed declspec.
555 bool IsString = Tok.getKind() == tok::string_literal;
556 if (!IsString && Tok.getKind() != tok::identifier &&
557 Tok.getKind() != tok::kw_restrict) {
558 Diag(Tok, diag::err_ms_declspec_type);
563 IdentifierInfo *AttrName;
564 SourceLocation AttrNameLoc;
566 SmallString<8> StrBuffer;
567 bool Invalid = false;
568 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
573 AttrName = PP.getIdentifierInfo(Str);
574 AttrNameLoc = ConsumeStringToken();
576 AttrName = Tok.getIdentifierInfo();
577 AttrNameLoc = ConsumeToken();
580 bool AttrHandled = false;
582 // Parse attribute arguments.
583 if (Tok.is(tok::l_paren))
584 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
585 else if (AttrName->getName() == "property")
586 // The property attribute must have an argument list.
587 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
588 << AttrName->getName();
591 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
592 AttributeList::AS_Declspec);
596 *End = T.getCloseLocation();
600 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
601 // Treat these like attributes
603 switch (Tok.getKind()) {
604 case tok::kw___fastcall:
605 case tok::kw___stdcall:
606 case tok::kw___thiscall:
607 case tok::kw___cdecl:
608 case tok::kw___vectorcall:
609 case tok::kw___ptr64:
611 case tok::kw___ptr32:
612 case tok::kw___unaligned:
614 case tok::kw___uptr: {
615 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
616 SourceLocation AttrNameLoc = ConsumeToken();
617 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
618 AttributeList::AS_Keyword);
627 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
628 SourceLocation StartLoc = Tok.getLocation();
629 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
631 if (EndLoc.isValid()) {
632 SourceRange Range(StartLoc, EndLoc);
633 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
637 SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
638 SourceLocation EndLoc;
641 switch (Tok.getKind()) {
643 case tok::kw_volatile:
644 case tok::kw___fastcall:
645 case tok::kw___stdcall:
646 case tok::kw___thiscall:
647 case tok::kw___cdecl:
648 case tok::kw___vectorcall:
649 case tok::kw___ptr32:
650 case tok::kw___ptr64:
652 case tok::kw___unaligned:
655 EndLoc = ConsumeToken();
663 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
664 // Treat these like attributes
665 while (Tok.is(tok::kw___pascal)) {
666 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
667 SourceLocation AttrNameLoc = ConsumeToken();
668 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
669 AttributeList::AS_Keyword);
673 void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
674 // Treat these like attributes
675 while (Tok.is(tok::kw___kernel)) {
676 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
677 SourceLocation AttrNameLoc = ConsumeToken();
678 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
679 AttributeList::AS_Keyword);
683 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
684 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
685 SourceLocation AttrNameLoc = Tok.getLocation();
686 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
687 AttributeList::AS_Keyword);
690 static bool VersionNumberSeparator(const char Separator) {
691 return (Separator == '.' || Separator == '_');
694 /// \brief Parse a version number.
698 /// simple-integer ',' simple-integer
699 /// simple-integer ',' simple-integer ',' simple-integer
700 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
701 Range = Tok.getLocation();
703 if (!Tok.is(tok::numeric_constant)) {
704 Diag(Tok, diag::err_expected_version);
705 SkipUntil(tok::comma, tok::r_paren,
706 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
707 return VersionTuple();
710 // Parse the major (and possibly minor and subminor) versions, which
711 // are stored in the numeric constant. We utilize a quirk of the
712 // lexer, which is that it handles something like 1.2.3 as a single
713 // numeric constant, rather than two separate tokens.
714 SmallString<512> Buffer;
715 Buffer.resize(Tok.getLength()+1);
716 const char *ThisTokBegin = &Buffer[0];
718 // Get the spelling of the token, which eliminates trigraphs, etc.
719 bool Invalid = false;
720 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
722 return VersionTuple();
724 // Parse the major version.
725 unsigned AfterMajor = 0;
727 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
728 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
732 if (AfterMajor == 0) {
733 Diag(Tok, diag::err_expected_version);
734 SkipUntil(tok::comma, tok::r_paren,
735 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
736 return VersionTuple();
739 if (AfterMajor == ActualLength) {
742 // We only had a single version component.
744 Diag(Tok, diag::err_zero_version);
745 return VersionTuple();
748 return VersionTuple(Major);
751 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
752 if (!VersionNumberSeparator(AfterMajorSeparator)
753 || (AfterMajor + 1 == ActualLength)) {
754 Diag(Tok, diag::err_expected_version);
755 SkipUntil(tok::comma, tok::r_paren,
756 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
757 return VersionTuple();
760 // Parse the minor version.
761 unsigned AfterMinor = AfterMajor + 1;
763 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
764 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
768 if (AfterMinor == ActualLength) {
771 // We had major.minor.
772 if (Major == 0 && Minor == 0) {
773 Diag(Tok, diag::err_zero_version);
774 return VersionTuple();
777 return VersionTuple(Major, Minor, (AfterMajorSeparator == '_'));
780 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
781 // If what follows is not a '.' or '_', we have a problem.
782 if (!VersionNumberSeparator(AfterMinorSeparator)) {
783 Diag(Tok, diag::err_expected_version);
784 SkipUntil(tok::comma, tok::r_paren,
785 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
786 return VersionTuple();
789 // Warn if separators, be it '.' or '_', do not match.
790 if (AfterMajorSeparator != AfterMinorSeparator)
791 Diag(Tok, diag::warn_expected_consistent_version_separator);
793 // Parse the subminor version.
794 unsigned AfterSubminor = AfterMinor + 1;
795 unsigned Subminor = 0;
796 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
797 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
801 if (AfterSubminor != ActualLength) {
802 Diag(Tok, diag::err_expected_version);
803 SkipUntil(tok::comma, tok::r_paren,
804 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
805 return VersionTuple();
808 return VersionTuple(Major, Minor, Subminor, (AfterMajorSeparator == '_'));
811 /// \brief Parse the contents of the "availability" attribute.
813 /// availability-attribute:
814 /// 'availability' '(' platform ',' version-arg-list, opt-message')'
819 /// version-arg-list:
821 /// version-arg ',' version-arg-list
824 /// 'introduced' '=' version
825 /// 'deprecated' '=' version
826 /// 'obsoleted' = version
829 /// 'message' '=' <string>
830 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
831 SourceLocation AvailabilityLoc,
832 ParsedAttributes &attrs,
833 SourceLocation *endLoc,
834 IdentifierInfo *ScopeName,
835 SourceLocation ScopeLoc,
836 AttributeList::Syntax Syntax) {
837 enum { Introduced, Deprecated, Obsoleted, Unknown };
838 AvailabilityChange Changes[Unknown];
839 ExprResult MessageExpr;
842 BalancedDelimiterTracker T(*this, tok::l_paren);
843 if (T.consumeOpen()) {
844 Diag(Tok, diag::err_expected) << tok::l_paren;
848 // Parse the platform name,
849 if (Tok.isNot(tok::identifier)) {
850 Diag(Tok, diag::err_availability_expected_platform);
851 SkipUntil(tok::r_paren, StopAtSemi);
854 IdentifierLoc *Platform = ParseIdentifierLoc();
856 // Parse the ',' following the platform name.
857 if (ExpectAndConsume(tok::comma)) {
858 SkipUntil(tok::r_paren, StopAtSemi);
862 // If we haven't grabbed the pointers for the identifiers
863 // "introduced", "deprecated", and "obsoleted", do so now.
864 if (!Ident_introduced) {
865 Ident_introduced = PP.getIdentifierInfo("introduced");
866 Ident_deprecated = PP.getIdentifierInfo("deprecated");
867 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
868 Ident_unavailable = PP.getIdentifierInfo("unavailable");
869 Ident_message = PP.getIdentifierInfo("message");
872 // Parse the set of introductions/deprecations/removals.
873 SourceLocation UnavailableLoc;
875 if (Tok.isNot(tok::identifier)) {
876 Diag(Tok, diag::err_availability_expected_change);
877 SkipUntil(tok::r_paren, StopAtSemi);
880 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
881 SourceLocation KeywordLoc = ConsumeToken();
883 if (Keyword == Ident_unavailable) {
884 if (UnavailableLoc.isValid()) {
885 Diag(KeywordLoc, diag::err_availability_redundant)
886 << Keyword << SourceRange(UnavailableLoc);
888 UnavailableLoc = KeywordLoc;
892 if (Tok.isNot(tok::equal)) {
893 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
894 SkipUntil(tok::r_paren, StopAtSemi);
898 if (Keyword == Ident_message) {
899 if (Tok.isNot(tok::string_literal)) {
900 Diag(Tok, diag::err_expected_string_literal)
901 << /*Source='availability attribute'*/2;
902 SkipUntil(tok::r_paren, StopAtSemi);
905 MessageExpr = ParseStringLiteralExpression();
906 // Also reject wide string literals.
907 if (StringLiteral *MessageStringLiteral =
908 cast_or_null<StringLiteral>(MessageExpr.get())) {
909 if (MessageStringLiteral->getCharByteWidth() != 1) {
910 Diag(MessageStringLiteral->getSourceRange().getBegin(),
911 diag::err_expected_string_literal)
912 << /*Source='availability attribute'*/ 2;
913 SkipUntil(tok::r_paren, StopAtSemi);
920 // Special handling of 'NA' only when applied to introduced or
922 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
923 Tok.is(tok::identifier)) {
924 IdentifierInfo *NA = Tok.getIdentifierInfo();
925 if (NA->getName() == "NA") {
927 if (Keyword == Ident_introduced)
928 UnavailableLoc = KeywordLoc;
933 SourceRange VersionRange;
934 VersionTuple Version = ParseVersionTuple(VersionRange);
936 if (Version.empty()) {
937 SkipUntil(tok::r_paren, StopAtSemi);
942 if (Keyword == Ident_introduced)
944 else if (Keyword == Ident_deprecated)
946 else if (Keyword == Ident_obsoleted)
951 if (Index < Unknown) {
952 if (!Changes[Index].KeywordLoc.isInvalid()) {
953 Diag(KeywordLoc, diag::err_availability_redundant)
955 << SourceRange(Changes[Index].KeywordLoc,
956 Changes[Index].VersionRange.getEnd());
959 Changes[Index].KeywordLoc = KeywordLoc;
960 Changes[Index].Version = Version;
961 Changes[Index].VersionRange = VersionRange;
963 Diag(KeywordLoc, diag::err_availability_unknown_change)
964 << Keyword << VersionRange;
967 } while (TryConsumeToken(tok::comma));
970 if (T.consumeClose())
974 *endLoc = T.getCloseLocation();
976 // The 'unavailable' availability cannot be combined with any other
977 // availability changes. Make sure that hasn't happened.
978 if (UnavailableLoc.isValid()) {
979 bool Complained = false;
980 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
981 if (Changes[Index].KeywordLoc.isValid()) {
983 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
984 << SourceRange(Changes[Index].KeywordLoc,
985 Changes[Index].VersionRange.getEnd());
989 // Clear out the availability.
990 Changes[Index] = AvailabilityChange();
995 // Record this attribute
996 attrs.addNew(&Availability,
997 SourceRange(AvailabilityLoc, T.getCloseLocation()),
1000 Changes[Introduced],
1001 Changes[Deprecated],
1003 UnavailableLoc, MessageExpr.get(),
1007 /// \brief Parse the contents of the "objc_bridge_related" attribute.
1008 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1012 /// opt-class_method:
1013 /// Identifier: | <empty>
1015 /// opt-instance_method:
1016 /// Identifier | <empty>
1018 void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1019 SourceLocation ObjCBridgeRelatedLoc,
1020 ParsedAttributes &attrs,
1021 SourceLocation *endLoc,
1022 IdentifierInfo *ScopeName,
1023 SourceLocation ScopeLoc,
1024 AttributeList::Syntax Syntax) {
1026 BalancedDelimiterTracker T(*this, tok::l_paren);
1027 if (T.consumeOpen()) {
1028 Diag(Tok, diag::err_expected) << tok::l_paren;
1032 // Parse the related class name.
1033 if (Tok.isNot(tok::identifier)) {
1034 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1035 SkipUntil(tok::r_paren, StopAtSemi);
1038 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1039 if (ExpectAndConsume(tok::comma)) {
1040 SkipUntil(tok::r_paren, StopAtSemi);
1044 // Parse optional class method name.
1045 IdentifierLoc *ClassMethod = nullptr;
1046 if (Tok.is(tok::identifier)) {
1047 ClassMethod = ParseIdentifierLoc();
1048 if (!TryConsumeToken(tok::colon)) {
1049 Diag(Tok, diag::err_objcbridge_related_selector_name);
1050 SkipUntil(tok::r_paren, StopAtSemi);
1054 if (!TryConsumeToken(tok::comma)) {
1055 if (Tok.is(tok::colon))
1056 Diag(Tok, diag::err_objcbridge_related_selector_name);
1058 Diag(Tok, diag::err_expected) << tok::comma;
1059 SkipUntil(tok::r_paren, StopAtSemi);
1063 // Parse optional instance method name.
1064 IdentifierLoc *InstanceMethod = nullptr;
1065 if (Tok.is(tok::identifier))
1066 InstanceMethod = ParseIdentifierLoc();
1067 else if (Tok.isNot(tok::r_paren)) {
1068 Diag(Tok, diag::err_expected) << tok::r_paren;
1069 SkipUntil(tok::r_paren, StopAtSemi);
1074 if (T.consumeClose())
1078 *endLoc = T.getCloseLocation();
1080 // Record this attribute
1081 attrs.addNew(&ObjCBridgeRelated,
1082 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1083 ScopeName, ScopeLoc,
1090 // Late Parsed Attributes:
1091 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1093 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1095 void Parser::LateParsedClass::ParseLexedAttributes() {
1096 Self->ParseLexedAttributes(*Class);
1099 void Parser::LateParsedAttribute::ParseLexedAttributes() {
1100 Self->ParseLexedAttribute(*this, true, false);
1103 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1104 /// scope appropriately.
1105 void Parser::ParseLexedAttributes(ParsingClass &Class) {
1106 // Deal with templates
1107 // FIXME: Test cases to make sure this does the right thing for templates.
1108 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1109 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1111 if (HasTemplateScope)
1112 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1114 // Set or update the scope flags.
1115 bool AlreadyHasClassScope = Class.TopLevelClass;
1116 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
1117 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1118 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1120 // Enter the scope of nested classes
1121 if (!AlreadyHasClassScope)
1122 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1123 Class.TagOrTemplate);
1124 if (!Class.LateParsedDeclarations.empty()) {
1125 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1126 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1130 if (!AlreadyHasClassScope)
1131 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1132 Class.TagOrTemplate);
1136 /// \brief Parse all attributes in LAs, and attach them to Decl D.
1137 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1138 bool EnterScope, bool OnDefinition) {
1139 assert(LAs.parseSoon() &&
1140 "Attribute list should be marked for immediate parsing.");
1141 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1144 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1151 /// \brief Finish parsing an attribute for which parsing was delayed.
1152 /// This will be called at the end of parsing a class declaration
1153 /// for each LateParsedAttribute. We consume the saved tokens and
1154 /// create an attribute with the arguments filled in. We add this
1155 /// to the Attribute list for the decl.
1156 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1157 bool EnterScope, bool OnDefinition) {
1158 // Create a fake EOF so that attribute parsing won't go off the end of the
1161 AttrEnd.startToken();
1162 AttrEnd.setKind(tok::eof);
1163 AttrEnd.setLocation(Tok.getLocation());
1164 AttrEnd.setEofData(LA.Toks.data());
1165 LA.Toks.push_back(AttrEnd);
1167 // Append the current token at the end of the new token stream so that it
1168 // doesn't get lost.
1169 LA.Toks.push_back(Tok);
1170 PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false);
1171 // Consume the previously pushed token.
1172 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1174 ParsedAttributes Attrs(AttrFactory);
1175 SourceLocation endLoc;
1177 if (LA.Decls.size() > 0) {
1178 Decl *D = LA.Decls[0];
1179 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1180 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1182 // Allow 'this' within late-parsed attributes.
1183 Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0,
1184 ND && ND->isCXXInstanceMember());
1186 if (LA.Decls.size() == 1) {
1187 // If the Decl is templatized, add template parameters to scope.
1188 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1189 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1190 if (HasTemplateScope)
1191 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1193 // If the Decl is on a function, add function parameters to the scope.
1194 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1195 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunScope);
1197 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1199 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1200 nullptr, SourceLocation(), AttributeList::AS_GNU,
1204 Actions.ActOnExitFunctionContext();
1205 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1207 if (HasTemplateScope) {
1211 // If there are multiple decls, then the decl cannot be within the
1213 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1214 nullptr, SourceLocation(), AttributeList::AS_GNU,
1218 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1221 const AttributeList *AL = Attrs.getList();
1222 if (OnDefinition && AL && !AL->isCXX11Attribute() &&
1224 Diag(Tok, diag::warn_attribute_on_function_definition)
1227 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
1228 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1230 // Due to a parsing error, we either went over the cached tokens or
1231 // there are still cached tokens left, so we skip the leftover tokens.
1232 while (Tok.isNot(tok::eof))
1235 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1239 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1240 SourceLocation AttrNameLoc,
1241 ParsedAttributes &Attrs,
1242 SourceLocation *EndLoc,
1243 IdentifierInfo *ScopeName,
1244 SourceLocation ScopeLoc,
1245 AttributeList::Syntax Syntax) {
1246 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1248 BalancedDelimiterTracker T(*this, tok::l_paren);
1251 if (Tok.isNot(tok::identifier)) {
1252 Diag(Tok, diag::err_expected) << tok::identifier;
1256 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1258 if (ExpectAndConsume(tok::comma)) {
1263 SourceRange MatchingCTypeRange;
1264 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1265 if (MatchingCType.isInvalid()) {
1270 bool LayoutCompatible = false;
1271 bool MustBeNull = false;
1272 while (TryConsumeToken(tok::comma)) {
1273 if (Tok.isNot(tok::identifier)) {
1274 Diag(Tok, diag::err_expected) << tok::identifier;
1278 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1279 if (Flag->isStr("layout_compatible"))
1280 LayoutCompatible = true;
1281 else if (Flag->isStr("must_be_null"))
1284 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1288 ConsumeToken(); // consume flag
1291 if (!T.consumeClose()) {
1292 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1293 ArgumentKind, MatchingCType.get(),
1294 LayoutCompatible, MustBeNull, Syntax);
1298 *EndLoc = T.getCloseLocation();
1301 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1302 /// of a C++11 attribute-specifier in a location where an attribute is not
1303 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1306 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1307 /// this doesn't appear to actually be an attribute-specifier, and the caller
1308 /// should try to parse it.
1309 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1310 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1312 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1313 case CAK_NotAttributeSpecifier:
1314 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1317 case CAK_InvalidAttributeSpecifier:
1318 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1321 case CAK_AttributeSpecifier:
1322 // Parse and discard the attributes.
1323 SourceLocation BeginLoc = ConsumeBracket();
1325 SkipUntil(tok::r_square);
1326 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1327 SourceLocation EndLoc = ConsumeBracket();
1328 Diag(BeginLoc, diag::err_attributes_not_allowed)
1329 << SourceRange(BeginLoc, EndLoc);
1332 llvm_unreachable("All cases handled above.");
1335 /// \brief We have found the opening square brackets of a C++11
1336 /// attribute-specifier in a location where an attribute is not permitted, but
1337 /// we know where the attributes ought to be written. Parse them anyway, and
1338 /// provide a fixit moving them to the right place.
1339 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1340 SourceLocation CorrectLocation) {
1341 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1342 Tok.is(tok::kw_alignas));
1344 // Consume the attributes.
1345 SourceLocation Loc = Tok.getLocation();
1346 ParseCXX11Attributes(Attrs);
1347 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1349 Diag(Loc, diag::err_attributes_not_allowed)
1350 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1351 << FixItHint::CreateRemoval(AttrRange);
1354 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
1355 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
1359 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs) {
1360 AttributeList *AttrList = attrs.getList();
1362 if (AttrList->isCXX11Attribute()) {
1363 Diag(AttrList->getLoc(), diag::err_attribute_not_type_attr)
1364 << AttrList->getName();
1365 AttrList->setInvalid();
1367 AttrList = AttrList->getNext();
1371 // As an exception to the rule, __declspec(align(...)) before the
1372 // class-key affects the type instead of the variable.
1373 void Parser::handleDeclspecAlignBeforeClassKey(ParsedAttributesWithRange &Attrs,
1375 Sema::TagUseKind TUK) {
1376 if (TUK == Sema::TUK_Reference)
1379 ParsedAttributes &PA = DS.getAttributes();
1380 AttributeList *AL = PA.getList();
1381 AttributeList *Prev = nullptr;
1383 AttributeList *Next = AL->getNext();
1385 // We only consider attributes using the appropriate '__declspec' spelling,
1386 // this behavior doesn't extend to any other spellings.
1387 if (AL->getKind() == AttributeList::AT_Aligned &&
1388 AL->isDeclspecAttribute()) {
1389 // Stitch the attribute into the tag's attribute list.
1390 AL->setNext(nullptr);
1393 // Remove the attribute from the variable's attribute list.
1395 // Set the last variable attribute's next attribute to be the attribute
1396 // after the current one.
1397 Prev->setNext(Next);
1399 // Removing the head of the list requires us to reset the head to the
1411 /// ParseDeclaration - Parse a full 'declaration', which consists of
1412 /// declaration-specifiers, some number of declarators, and a semicolon.
1413 /// 'Context' should be a Declarator::TheContext value. This returns the
1414 /// location of the semicolon in DeclEnd.
1416 /// declaration: [C99 6.7]
1417 /// block-declaration ->
1418 /// simple-declaration
1420 /// [C++] template-declaration
1421 /// [C++] namespace-definition
1422 /// [C++] using-directive
1423 /// [C++] using-declaration
1424 /// [C++11/C11] static_assert-declaration
1425 /// others... [FIXME]
1427 Parser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context,
1428 SourceLocation &DeclEnd,
1429 ParsedAttributesWithRange &attrs) {
1430 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1431 // Must temporarily exit the objective-c container scope for
1432 // parsing c none objective-c decls.
1433 ObjCDeclContextSwitch ObjCDC(*this);
1435 Decl *SingleDecl = nullptr;
1436 Decl *OwnedType = nullptr;
1437 switch (Tok.getKind()) {
1438 case tok::kw_template:
1439 case tok::kw_export:
1440 ProhibitAttributes(attrs);
1441 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
1443 case tok::kw_inline:
1444 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1445 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1446 ProhibitAttributes(attrs);
1447 SourceLocation InlineLoc = ConsumeToken();
1448 SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc);
1451 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
1453 case tok::kw_namespace:
1454 ProhibitAttributes(attrs);
1455 SingleDecl = ParseNamespace(Context, DeclEnd);
1458 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1459 DeclEnd, attrs, &OwnedType);
1461 case tok::kw_static_assert:
1462 case tok::kw__Static_assert:
1463 ProhibitAttributes(attrs);
1464 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1467 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
1470 // This routine returns a DeclGroup, if the thing we parsed only contains a
1471 // single decl, convert it now. Alias declarations can also declare a type;
1472 // include that too if it is present.
1473 return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType);
1476 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1477 /// declaration-specifiers init-declarator-list[opt] ';'
1478 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1479 /// init-declarator-list ';'
1480 ///[C90/C++]init-declarator-list ';' [TODO]
1481 /// [OMP] threadprivate-directive [TODO]
1483 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1484 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1486 /// If RequireSemi is false, this does not check for a ';' at the end of the
1487 /// declaration. If it is true, it checks for and eats it.
1489 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1490 /// of a simple-declaration. If we find that we are, we also parse the
1491 /// for-range-initializer, and place it here.
1492 Parser::DeclGroupPtrTy
1493 Parser::ParseSimpleDeclaration(unsigned Context,
1494 SourceLocation &DeclEnd,
1495 ParsedAttributesWithRange &Attrs,
1496 bool RequireSemi, ForRangeInit *FRI) {
1497 // Parse the common declaration-specifiers piece.
1498 ParsingDeclSpec DS(*this);
1500 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1501 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1503 // If we had a free-standing type definition with a missing semicolon, we
1504 // may get this far before the problem becomes obvious.
1505 if (DS.hasTagDefinition() &&
1506 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1507 return DeclGroupPtrTy();
1509 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1510 // declaration-specifiers init-declarator-list[opt] ';'
1511 if (Tok.is(tok::semi)) {
1512 ProhibitAttributes(Attrs);
1513 DeclEnd = Tok.getLocation();
1514 if (RequireSemi) ConsumeToken();
1515 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1517 DS.complete(TheDecl);
1518 return Actions.ConvertDeclToDeclGroup(TheDecl);
1521 DS.takeAttributesFrom(Attrs);
1522 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1525 /// Returns true if this might be the start of a declarator, or a common typo
1526 /// for a declarator.
1527 bool Parser::MightBeDeclarator(unsigned Context) {
1528 switch (Tok.getKind()) {
1529 case tok::annot_cxxscope:
1530 case tok::annot_template_id:
1532 case tok::code_completion:
1533 case tok::coloncolon:
1535 case tok::kw___attribute:
1536 case tok::kw_operator:
1543 return getLangOpts().CPlusPlus;
1545 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1546 return Context == Declarator::MemberContext && getLangOpts().CPlusPlus11 &&
1547 NextToken().is(tok::l_square);
1549 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1550 return Context == Declarator::MemberContext || getLangOpts().CPlusPlus;
1552 case tok::identifier:
1553 switch (NextToken().getKind()) {
1554 case tok::code_completion:
1555 case tok::coloncolon:
1558 case tok::equalequal: // Might be a typo for '='.
1559 case tok::kw_alignas:
1561 case tok::kw___attribute:
1573 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1574 // and in block scope it's probably a label. Inside a class definition,
1575 // this is a bit-field.
1576 return Context == Declarator::MemberContext ||
1577 (getLangOpts().CPlusPlus && Context == Declarator::FileContext);
1579 case tok::identifier: // Possible virt-specifier.
1580 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1591 /// Skip until we reach something which seems like a sensible place to pick
1592 /// up parsing after a malformed declaration. This will sometimes stop sooner
1593 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1594 void Parser::SkipMalformedDecl() {
1596 switch (Tok.getKind()) {
1598 // Skip until matching }, then stop. We've probably skipped over
1599 // a malformed class or function definition or similar.
1601 SkipUntil(tok::r_brace);
1602 if (Tok.is(tok::comma) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try)) {
1603 // This declaration isn't over yet. Keep skipping.
1606 TryConsumeToken(tok::semi);
1611 SkipUntil(tok::r_square);
1616 SkipUntil(tok::r_paren);
1626 case tok::kw_inline:
1627 // 'inline namespace' at the start of a line is almost certainly
1628 // a good place to pick back up parsing, except in an Objective-C
1629 // @interface context.
1630 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1631 (!ParsingInObjCContainer || CurParsedObjCImpl))
1635 case tok::kw_namespace:
1636 // 'namespace' at the start of a line is almost certainly a good
1637 // place to pick back up parsing, except in an Objective-C
1638 // @interface context.
1639 if (Tok.isAtStartOfLine() &&
1640 (!ParsingInObjCContainer || CurParsedObjCImpl))
1645 // @end is very much like } in Objective-C contexts.
1646 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1647 ParsingInObjCContainer)
1653 // - and + probably start new method declarations in Objective-C contexts.
1654 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1659 case tok::annot_module_begin:
1660 case tok::annot_module_end:
1661 case tok::annot_module_include:
1672 /// ParseDeclGroup - Having concluded that this is either a function
1673 /// definition or a group of object declarations, actually parse the
1675 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1677 SourceLocation *DeclEnd,
1678 ForRangeInit *FRI) {
1679 // Parse the first declarator.
1680 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
1683 // Bail out if the first declarator didn't seem well-formed.
1684 if (!D.hasName() && !D.mayOmitIdentifier()) {
1685 SkipMalformedDecl();
1686 return DeclGroupPtrTy();
1689 // Save late-parsed attributes for now; they need to be parsed in the
1690 // appropriate function scope after the function Decl has been constructed.
1691 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1692 LateParsedAttrList LateParsedAttrs(true);
1693 if (D.isFunctionDeclarator()) {
1694 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1696 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1697 // attribute. If we find the keyword here, tell the user to put it
1698 // at the start instead.
1699 if (Tok.is(tok::kw__Noreturn)) {
1700 SourceLocation Loc = ConsumeToken();
1701 const char *PrevSpec;
1704 // We can offer a fixit if it's valid to mark this function as _Noreturn
1705 // and we don't have any other declarators in this declaration.
1706 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1707 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1708 Fixit &= Tok.is(tok::semi) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try);
1710 Diag(Loc, diag::err_c11_noreturn_misplaced)
1711 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
1712 << (Fixit ? FixItHint::CreateInsertion(D.getLocStart(), "_Noreturn ")
1717 // Check to see if we have a function *definition* which must have a body.
1718 if (D.isFunctionDeclarator() &&
1719 // Look at the next token to make sure that this isn't a function
1720 // declaration. We have to check this because __attribute__ might be the
1721 // start of a function definition in GCC-extended K&R C.
1722 !isDeclarationAfterDeclarator()) {
1724 // Function definitions are only allowed at file scope and in C++ classes.
1725 // The C++ inline method definition case is handled elsewhere, so we only
1726 // need to handle the file scope definition case.
1727 if (Context == Declarator::FileContext) {
1728 if (isStartOfFunctionDefinition(D)) {
1729 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1730 Diag(Tok, diag::err_function_declared_typedef);
1732 // Recover by treating the 'typedef' as spurious.
1733 DS.ClearStorageClassSpecs();
1737 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1738 return Actions.ConvertDeclToDeclGroup(TheDecl);
1741 if (isDeclarationSpecifier()) {
1742 // If there is an invalid declaration specifier right after the
1743 // function prototype, then we must be in a missing semicolon case
1744 // where this isn't actually a body. Just fall through into the code
1745 // that handles it as a prototype, and let the top-level code handle
1746 // the erroneous declspec where it would otherwise expect a comma or
1749 Diag(Tok, diag::err_expected_fn_body);
1750 SkipUntil(tok::semi);
1751 return DeclGroupPtrTy();
1754 if (Tok.is(tok::l_brace)) {
1755 Diag(Tok, diag::err_function_definition_not_allowed);
1756 SkipMalformedDecl();
1757 return DeclGroupPtrTy();
1762 if (ParseAsmAttributesAfterDeclarator(D))
1763 return DeclGroupPtrTy();
1765 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1766 // must parse and analyze the for-range-initializer before the declaration is
1769 // Handle the Objective-C for-in loop variable similarly, although we
1770 // don't need to parse the container in advance.
1771 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
1772 bool IsForRangeLoop = false;
1773 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
1774 IsForRangeLoop = true;
1775 if (Tok.is(tok::l_brace))
1776 FRI->RangeExpr = ParseBraceInitializer();
1778 FRI->RangeExpr = ParseExpression();
1781 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1783 Actions.ActOnCXXForRangeDecl(ThisDecl);
1784 Actions.FinalizeDeclaration(ThisDecl);
1785 D.complete(ThisDecl);
1786 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
1789 SmallVector<Decl *, 8> DeclsInGroup;
1790 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
1791 D, ParsedTemplateInfo(), FRI);
1792 if (LateParsedAttrs.size() > 0)
1793 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
1794 D.complete(FirstDecl);
1796 DeclsInGroup.push_back(FirstDecl);
1798 bool ExpectSemi = Context != Declarator::ForContext;
1800 // If we don't have a comma, it is either the end of the list (a ';') or an
1802 SourceLocation CommaLoc;
1803 while (TryConsumeToken(tok::comma, CommaLoc)) {
1804 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
1805 // This comma was followed by a line-break and something which can't be
1806 // the start of a declarator. The comma was probably a typo for a
1808 Diag(CommaLoc, diag::err_expected_semi_declaration)
1809 << FixItHint::CreateReplacement(CommaLoc, ";");
1814 // Parse the next declarator.
1816 D.setCommaLoc(CommaLoc);
1818 // Accept attributes in an init-declarator. In the first declarator in a
1819 // declaration, these would be part of the declspec. In subsequent
1820 // declarators, they become part of the declarator itself, so that they
1821 // don't apply to declarators after *this* one. Examples:
1822 // short __attribute__((common)) var; -> declspec
1823 // short var __attribute__((common)); -> declarator
1824 // short x, __attribute__((common)) var; -> declarator
1825 MaybeParseGNUAttributes(D);
1827 // MSVC parses but ignores qualifiers after the comma as an extension.
1828 if (getLangOpts().MicrosoftExt)
1829 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
1832 if (!D.isInvalidType()) {
1833 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
1834 D.complete(ThisDecl);
1836 DeclsInGroup.push_back(ThisDecl);
1841 *DeclEnd = Tok.getLocation();
1844 ExpectAndConsumeSemi(Context == Declarator::FileContext
1845 ? diag::err_invalid_token_after_toplevel_declarator
1846 : diag::err_expected_semi_declaration)) {
1847 // Okay, there was no semicolon and one was expected. If we see a
1848 // declaration specifier, just assume it was missing and continue parsing.
1849 // Otherwise things are very confused and we skip to recover.
1850 if (!isDeclarationSpecifier()) {
1851 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1852 TryConsumeToken(tok::semi);
1856 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
1859 /// Parse an optional simple-asm-expr and attributes, and attach them to a
1860 /// declarator. Returns true on an error.
1861 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
1862 // If a simple-asm-expr is present, parse it.
1863 if (Tok.is(tok::kw_asm)) {
1865 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1866 if (AsmLabel.isInvalid()) {
1867 SkipUntil(tok::semi, StopBeforeMatch);
1871 D.setAsmLabel(AsmLabel.get());
1875 MaybeParseGNUAttributes(D);
1879 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
1880 /// declarator'. This method parses the remainder of the declaration
1881 /// (including any attributes or initializer, among other things) and
1882 /// finalizes the declaration.
1884 /// init-declarator: [C99 6.7]
1886 /// declarator '=' initializer
1887 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
1888 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
1889 /// [C++] declarator initializer[opt]
1891 /// [C++] initializer:
1892 /// [C++] '=' initializer-clause
1893 /// [C++] '(' expression-list ')'
1894 /// [C++0x] '=' 'default' [TODO]
1895 /// [C++0x] '=' 'delete'
1896 /// [C++0x] braced-init-list
1898 /// According to the standard grammar, =default and =delete are function
1899 /// definitions, but that definitely doesn't fit with the parser here.
1901 Decl *Parser::ParseDeclarationAfterDeclarator(
1902 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
1903 if (ParseAsmAttributesAfterDeclarator(D))
1906 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
1909 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
1910 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
1911 // Inform the current actions module that we just parsed this declarator.
1912 Decl *ThisDecl = nullptr;
1913 switch (TemplateInfo.Kind) {
1914 case ParsedTemplateInfo::NonTemplate:
1915 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1918 case ParsedTemplateInfo::Template:
1919 case ParsedTemplateInfo::ExplicitSpecialization: {
1920 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
1921 *TemplateInfo.TemplateParams,
1923 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
1924 // Re-direct this decl to refer to the templated decl so that we can
1926 ThisDecl = VT->getTemplatedDecl();
1929 case ParsedTemplateInfo::ExplicitInstantiation: {
1930 if (Tok.is(tok::semi)) {
1931 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
1932 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
1933 if (ThisRes.isInvalid()) {
1934 SkipUntil(tok::semi, StopBeforeMatch);
1937 ThisDecl = ThisRes.get();
1939 // FIXME: This check should be for a variable template instantiation only.
1941 // Check that this is a valid instantiation
1942 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
1943 // If the declarator-id is not a template-id, issue a diagnostic and
1944 // recover by ignoring the 'template' keyword.
1945 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1946 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1947 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1949 SourceLocation LAngleLoc =
1950 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1951 Diag(D.getIdentifierLoc(),
1952 diag::err_explicit_instantiation_with_definition)
1953 << SourceRange(TemplateInfo.TemplateLoc)
1954 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1956 // Recover as if it were an explicit specialization.
1957 TemplateParameterLists FakedParamLists;
1958 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1959 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr,
1963 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
1970 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
1972 // Parse declarator '=' initializer.
1973 // If a '==' or '+=' is found, suggest a fixit to '='.
1974 if (isTokenEqualOrEqualTypo()) {
1975 SourceLocation EqualLoc = ConsumeToken();
1977 if (Tok.is(tok::kw_delete)) {
1978 if (D.isFunctionDeclarator())
1979 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1982 Diag(ConsumeToken(), diag::err_deleted_non_function);
1983 } else if (Tok.is(tok::kw_default)) {
1984 if (D.isFunctionDeclarator())
1985 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1988 Diag(ConsumeToken(), diag::err_default_special_members);
1990 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1992 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1995 if (Tok.is(tok::code_completion)) {
1996 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
1997 Actions.FinalizeDeclaration(ThisDecl);
2002 ExprResult Init(ParseInitializer());
2004 // If this is the only decl in (possibly) range based for statement,
2005 // our best guess is that the user meant ':' instead of '='.
2006 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2007 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2008 << FixItHint::CreateReplacement(EqualLoc, ":");
2009 // We are trying to stop parser from looking for ';' in this for
2010 // statement, therefore preventing spurious errors to be issued.
2011 FRI->ColonLoc = EqualLoc;
2013 FRI->RangeExpr = Init;
2016 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2017 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2021 if (Init.isInvalid()) {
2022 SmallVector<tok::TokenKind, 2> StopTokens;
2023 StopTokens.push_back(tok::comma);
2024 if (D.getContext() == Declarator::ForContext)
2025 StopTokens.push_back(tok::r_paren);
2026 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2027 Actions.ActOnInitializerError(ThisDecl);
2029 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2030 /*DirectInit=*/false, TypeContainsAuto);
2032 } else if (Tok.is(tok::l_paren)) {
2033 // Parse C++ direct initializer: '(' expression-list ')'
2034 BalancedDelimiterTracker T(*this, tok::l_paren);
2038 CommaLocsTy CommaLocs;
2040 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2042 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
2045 if (ParseExpressionList(Exprs, CommaLocs, [&] {
2046 Actions.CodeCompleteConstructor(getCurScope(),
2047 cast<VarDecl>(ThisDecl)->getType()->getCanonicalTypeInternal(),
2048 ThisDecl->getLocation(), Exprs);
2050 Actions.ActOnInitializerError(ThisDecl);
2051 SkipUntil(tok::r_paren, StopAtSemi);
2053 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2054 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2061 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2062 "Unexpected number of commas!");
2064 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2065 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2069 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2070 T.getCloseLocation(),
2072 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2073 /*DirectInit=*/true, TypeContainsAuto);
2075 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2076 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
2077 // Parse C++0x braced-init-list.
2078 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2080 if (D.getCXXScopeSpec().isSet()) {
2082 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
2085 ExprResult Init(ParseBraceInitializer());
2087 if (D.getCXXScopeSpec().isSet()) {
2088 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2092 if (Init.isInvalid()) {
2093 Actions.ActOnInitializerError(ThisDecl);
2095 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2096 /*DirectInit=*/true, TypeContainsAuto);
2099 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
2102 Actions.FinalizeDeclaration(ThisDecl);
2107 /// ParseSpecifierQualifierList
2108 /// specifier-qualifier-list:
2109 /// type-specifier specifier-qualifier-list[opt]
2110 /// type-qualifier specifier-qualifier-list[opt]
2111 /// [GNU] attributes specifier-qualifier-list[opt]
2113 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2114 DeclSpecContext DSC) {
2115 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2116 /// parse declaration-specifiers and complain about extra stuff.
2117 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2118 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2120 // Validate declspec for type-name.
2121 unsigned Specs = DS.getParsedSpecifiers();
2122 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2123 Diag(Tok, diag::err_expected_type);
2124 DS.SetTypeSpecError();
2125 } else if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
2126 !DS.hasAttributes()) {
2127 Diag(Tok, diag::err_typename_requires_specqual);
2128 if (!DS.hasTypeSpecifier())
2129 DS.SetTypeSpecError();
2132 // Issue diagnostic and remove storage class if present.
2133 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2134 if (DS.getStorageClassSpecLoc().isValid())
2135 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2137 Diag(DS.getThreadStorageClassSpecLoc(),
2138 diag::err_typename_invalid_storageclass);
2139 DS.ClearStorageClassSpecs();
2142 // Issue diagnostic and remove function specfier if present.
2143 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2144 if (DS.isInlineSpecified())
2145 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2146 if (DS.isVirtualSpecified())
2147 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2148 if (DS.isExplicitSpecified())
2149 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2150 DS.ClearFunctionSpecs();
2153 // Issue diagnostic and remove constexpr specfier if present.
2154 if (DS.isConstexprSpecified()) {
2155 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2156 DS.ClearConstexprSpec();
2160 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2161 /// specified token is valid after the identifier in a declarator which
2162 /// immediately follows the declspec. For example, these things are valid:
2164 /// int x [ 4]; // direct-declarator
2165 /// int x ( int y); // direct-declarator
2166 /// int(int x ) // direct-declarator
2167 /// int x ; // simple-declaration
2168 /// int x = 17; // init-declarator-list
2169 /// int x , y; // init-declarator-list
2170 /// int x __asm__ ("foo"); // init-declarator-list
2171 /// int x : 4; // struct-declarator
2172 /// int x { 5}; // C++'0x unified initializers
2174 /// This is not, because 'x' does not immediately follow the declspec (though
2175 /// ')' happens to be valid anyway).
2178 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2179 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
2180 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
2181 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
2185 /// ParseImplicitInt - This method is called when we have an non-typename
2186 /// identifier in a declspec (which normally terminates the decl spec) when
2187 /// the declspec has no type specifier. In this case, the declspec is either
2188 /// malformed or is "implicit int" (in K&R and C89).
2190 /// This method handles diagnosing this prettily and returns false if the
2191 /// declspec is done being processed. If it recovers and thinks there may be
2192 /// other pieces of declspec after it, it returns true.
2194 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2195 const ParsedTemplateInfo &TemplateInfo,
2196 AccessSpecifier AS, DeclSpecContext DSC,
2197 ParsedAttributesWithRange &Attrs) {
2198 assert(Tok.is(tok::identifier) && "should have identifier");
2200 SourceLocation Loc = Tok.getLocation();
2201 // If we see an identifier that is not a type name, we normally would
2202 // parse it as the identifer being declared. However, when a typename
2203 // is typo'd or the definition is not included, this will incorrectly
2204 // parse the typename as the identifier name and fall over misparsing
2205 // later parts of the diagnostic.
2207 // As such, we try to do some look-ahead in cases where this would
2208 // otherwise be an "implicit-int" case to see if this is invalid. For
2209 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2210 // an identifier with implicit int, we'd get a parse error because the
2211 // next token is obviously invalid for a type. Parse these as a case
2212 // with an invalid type specifier.
2213 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2215 // Since we know that this either implicit int (which is rare) or an
2216 // error, do lookahead to try to do better recovery. This never applies
2217 // within a type specifier. Outside of C++, we allow this even if the
2218 // language doesn't "officially" support implicit int -- we support
2219 // implicit int as an extension in C99 and C11.
2220 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2221 isValidAfterIdentifierInDeclarator(NextToken())) {
2222 // If this token is valid for implicit int, e.g. "static x = 4", then
2223 // we just avoid eating the identifier, so it will be parsed as the
2224 // identifier in the declarator.
2228 if (getLangOpts().CPlusPlus &&
2229 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2230 // Don't require a type specifier if we have the 'auto' storage class
2231 // specifier in C++98 -- we'll promote it to a type specifier.
2233 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2237 // Otherwise, if we don't consume this token, we are going to emit an
2238 // error anyway. Try to recover from various common problems. Check
2239 // to see if this was a reference to a tag name without a tag specified.
2240 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2242 // C++ doesn't need this, and isTagName doesn't take SS.
2243 if (SS == nullptr) {
2244 const char *TagName = nullptr, *FixitTagName = nullptr;
2245 tok::TokenKind TagKind = tok::unknown;
2247 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2249 case DeclSpec::TST_enum:
2250 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2251 case DeclSpec::TST_union:
2252 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2253 case DeclSpec::TST_struct:
2254 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2255 case DeclSpec::TST_interface:
2256 TagName="__interface"; FixitTagName = "__interface ";
2257 TagKind=tok::kw___interface;break;
2258 case DeclSpec::TST_class:
2259 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2263 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2264 LookupResult R(Actions, TokenName, SourceLocation(),
2265 Sema::LookupOrdinaryName);
2267 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2268 << TokenName << TagName << getLangOpts().CPlusPlus
2269 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2271 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2272 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2274 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2275 << TokenName << TagName;
2278 // Parse this as a tag as if the missing tag were present.
2279 if (TagKind == tok::kw_enum)
2280 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
2282 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2283 /*EnteringContext*/ false, DSC_normal, Attrs);
2288 // Determine whether this identifier could plausibly be the name of something
2289 // being declared (with a missing type).
2290 if (!isTypeSpecifier(DSC) &&
2291 (!SS || DSC == DSC_top_level || DSC == DSC_class)) {
2292 // Look ahead to the next token to try to figure out what this declaration
2293 // was supposed to be.
2294 switch (NextToken().getKind()) {
2295 case tok::l_paren: {
2296 // static x(4); // 'x' is not a type
2297 // x(int n); // 'x' is not a type
2298 // x (*p)[]; // 'x' is a type
2300 // Since we're in an error case, we can afford to perform a tentative
2301 // parse to determine which case we're in.
2302 TentativeParsingAction PA(*this);
2304 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2307 if (TPR != TPResult::False) {
2308 // The identifier is followed by a parenthesized declarator.
2309 // It's supposed to be a type.
2313 // If we're in a context where we could be declaring a constructor,
2314 // check whether this is a constructor declaration with a bogus name.
2315 if (DSC == DSC_class || (DSC == DSC_top_level && SS)) {
2316 IdentifierInfo *II = Tok.getIdentifierInfo();
2317 if (Actions.isCurrentClassNameTypo(II, SS)) {
2318 Diag(Loc, diag::err_constructor_bad_name)
2319 << Tok.getIdentifierInfo() << II
2320 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2321 Tok.setIdentifierInfo(II);
2332 // This looks like a variable or function declaration. The type is
2333 // probably missing. We're done parsing decl-specifiers.
2335 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2339 // This is probably supposed to be a type. This includes cases like:
2341 // struct S { unsinged : 4; };
2346 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2347 // and attempt to recover.
2349 IdentifierInfo *II = Tok.getIdentifierInfo();
2350 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2351 getLangOpts().CPlusPlus &&
2352 NextToken().is(tok::less));
2354 // The action has suggested that the type T could be used. Set that as
2355 // the type in the declaration specifiers, consume the would-be type
2356 // name token, and we're done.
2357 const char *PrevSpec;
2359 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2360 Actions.getASTContext().getPrintingPolicy());
2361 DS.SetRangeEnd(Tok.getLocation());
2363 // There may be other declaration specifiers after this.
2365 } else if (II != Tok.getIdentifierInfo()) {
2366 // If no type was suggested, the correction is to a keyword
2367 Tok.setKind(II->getTokenID());
2368 // There may be other declaration specifiers after this.
2372 // Otherwise, the action had no suggestion for us. Mark this as an error.
2373 DS.SetTypeSpecError();
2374 DS.SetRangeEnd(Tok.getLocation());
2377 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2378 // avoid rippling error messages on subsequent uses of the same type,
2379 // could be useful if #include was forgotten.
2383 /// \brief Determine the declaration specifier context from the declarator
2386 /// \param Context the declarator context, which is one of the
2387 /// Declarator::TheContext enumerator values.
2388 Parser::DeclSpecContext
2389 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
2390 if (Context == Declarator::MemberContext)
2392 if (Context == Declarator::FileContext)
2393 return DSC_top_level;
2394 if (Context == Declarator::TemplateTypeArgContext)
2395 return DSC_template_type_arg;
2396 if (Context == Declarator::TrailingReturnContext)
2397 return DSC_trailing;
2398 if (Context == Declarator::AliasDeclContext ||
2399 Context == Declarator::AliasTemplateContext)
2400 return DSC_alias_declaration;
2404 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2406 /// FIXME: Simply returns an alignof() expression if the argument is a
2407 /// type. Ideally, the type should be propagated directly into Sema.
2410 /// [C11] constant-expression
2411 /// [C++0x] type-id ...[opt]
2412 /// [C++0x] assignment-expression ...[opt]
2413 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2414 SourceLocation &EllipsisLoc) {
2416 if (isTypeIdInParens()) {
2417 SourceLocation TypeLoc = Tok.getLocation();
2418 ParsedType Ty = ParseTypeName().get();
2419 SourceRange TypeRange(Start, Tok.getLocation());
2420 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2421 Ty.getAsOpaquePtr(), TypeRange);
2423 ER = ParseConstantExpression();
2425 if (getLangOpts().CPlusPlus11)
2426 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2431 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2432 /// attribute to Attrs.
2434 /// alignment-specifier:
2435 /// [C11] '_Alignas' '(' type-id ')'
2436 /// [C11] '_Alignas' '(' constant-expression ')'
2437 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2438 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2439 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2440 SourceLocation *EndLoc) {
2441 assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) &&
2442 "Not an alignment-specifier!");
2444 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2445 SourceLocation KWLoc = ConsumeToken();
2447 BalancedDelimiterTracker T(*this, tok::l_paren);
2448 if (T.expectAndConsume())
2451 SourceLocation EllipsisLoc;
2452 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2453 if (ArgExpr.isInvalid()) {
2460 *EndLoc = T.getCloseLocation();
2462 ArgsVector ArgExprs;
2463 ArgExprs.push_back(ArgExpr.get());
2464 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2465 AttributeList::AS_Keyword, EllipsisLoc);
2468 /// Determine whether we're looking at something that might be a declarator
2469 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2470 /// diagnose a missing semicolon after a prior tag definition in the decl
2473 /// \return \c true if an error occurred and this can't be any kind of
2476 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2477 DeclSpecContext DSContext,
2478 LateParsedAttrList *LateAttrs) {
2479 assert(DS.hasTagDefinition() && "shouldn't call this");
2481 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2483 if (getLangOpts().CPlusPlus &&
2484 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
2485 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id)) &&
2486 TryAnnotateCXXScopeToken(EnteringContext)) {
2487 SkipMalformedDecl();
2491 bool HasScope = Tok.is(tok::annot_cxxscope);
2492 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2493 Token AfterScope = HasScope ? NextToken() : Tok;
2495 // Determine whether the following tokens could possibly be a
2497 bool MightBeDeclarator = true;
2498 if (Tok.is(tok::kw_typename) || Tok.is(tok::annot_typename)) {
2499 // A declarator-id can't start with 'typename'.
2500 MightBeDeclarator = false;
2501 } else if (AfterScope.is(tok::annot_template_id)) {
2502 // If we have a type expressed as a template-id, this cannot be a
2503 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2504 TemplateIdAnnotation *Annot =
2505 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2506 if (Annot->Kind == TNK_Type_template)
2507 MightBeDeclarator = false;
2508 } else if (AfterScope.is(tok::identifier)) {
2509 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2511 // These tokens cannot come after the declarator-id in a
2512 // simple-declaration, and are likely to come after a type-specifier.
2513 if (Next.is(tok::star) || Next.is(tok::amp) || Next.is(tok::ampamp) ||
2514 Next.is(tok::identifier) || Next.is(tok::annot_cxxscope) ||
2515 Next.is(tok::coloncolon)) {
2516 // Missing a semicolon.
2517 MightBeDeclarator = false;
2518 } else if (HasScope) {
2519 // If the declarator-id has a scope specifier, it must redeclare a
2520 // previously-declared entity. If that's a type (and this is not a
2521 // typedef), that's an error.
2523 Actions.RestoreNestedNameSpecifierAnnotation(
2524 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2525 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2526 Sema::NameClassification Classification = Actions.ClassifyName(
2527 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2528 /*IsAddressOfOperand*/false);
2529 switch (Classification.getKind()) {
2530 case Sema::NC_Error:
2531 SkipMalformedDecl();
2534 case Sema::NC_Keyword:
2535 case Sema::NC_NestedNameSpecifier:
2536 llvm_unreachable("typo correction and nested name specifiers not "
2540 case Sema::NC_TypeTemplate:
2541 // Not a previously-declared non-type entity.
2542 MightBeDeclarator = false;
2545 case Sema::NC_Unknown:
2546 case Sema::NC_Expression:
2547 case Sema::NC_VarTemplate:
2548 case Sema::NC_FunctionTemplate:
2549 // Might be a redeclaration of a prior entity.
2555 if (MightBeDeclarator)
2558 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2559 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()),
2560 diag::err_expected_after)
2561 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2563 // Try to recover from the typo, by dropping the tag definition and parsing
2564 // the problematic tokens as a type.
2566 // FIXME: Split the DeclSpec into pieces for the standalone
2567 // declaration and pieces for the following declaration, instead
2568 // of assuming that all the other pieces attach to new declaration,
2569 // and call ParsedFreeStandingDeclSpec as appropriate.
2570 DS.ClearTypeSpecType();
2571 ParsedTemplateInfo NotATemplate;
2572 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2576 /// ParseDeclarationSpecifiers
2577 /// declaration-specifiers: [C99 6.7]
2578 /// storage-class-specifier declaration-specifiers[opt]
2579 /// type-specifier declaration-specifiers[opt]
2580 /// [C99] function-specifier declaration-specifiers[opt]
2581 /// [C11] alignment-specifier declaration-specifiers[opt]
2582 /// [GNU] attributes declaration-specifiers[opt]
2583 /// [Clang] '__module_private__' declaration-specifiers[opt]
2585 /// storage-class-specifier: [C99 6.7.1]
2592 /// [C++11] 'thread_local'
2593 /// [C11] '_Thread_local'
2594 /// [GNU] '__thread'
2595 /// function-specifier: [C99 6.7.4]
2598 /// [C++] 'explicit'
2599 /// [OpenCL] '__kernel'
2600 /// 'friend': [C++ dcl.friend]
2601 /// 'constexpr': [C++0x dcl.constexpr]
2604 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2605 const ParsedTemplateInfo &TemplateInfo,
2607 DeclSpecContext DSContext,
2608 LateParsedAttrList *LateAttrs) {
2609 if (DS.getSourceRange().isInvalid()) {
2610 // Start the range at the current token but make the end of the range
2611 // invalid. This will make the entire range invalid unless we successfully
2613 DS.SetRangeStart(Tok.getLocation());
2614 DS.SetRangeEnd(SourceLocation());
2617 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2618 bool AttrsLastTime = false;
2619 ParsedAttributesWithRange attrs(AttrFactory);
2620 // We use Sema's policy to get bool macros right.
2621 const PrintingPolicy &Policy = Actions.getPrintingPolicy();
2623 bool isInvalid = false;
2624 bool isStorageClass = false;
2625 const char *PrevSpec = nullptr;
2626 unsigned DiagID = 0;
2628 SourceLocation Loc = Tok.getLocation();
2630 switch (Tok.getKind()) {
2634 ProhibitAttributes(attrs);
2636 // Reject C++11 attributes that appertain to decl specifiers as
2637 // we don't support any C++11 attributes that appertain to decl
2638 // specifiers. This also conforms to what g++ 4.8 is doing.
2639 ProhibitCXX11Attributes(attrs);
2641 DS.takeAttributesFrom(attrs);
2644 // If this is not a declaration specifier token, we're done reading decl
2645 // specifiers. First verify that DeclSpec's are consistent.
2646 DS.Finish(Diags, PP, Policy);
2650 case tok::kw_alignas:
2651 if (!getLangOpts().CPlusPlus11 || !isCXX11AttributeSpecifier())
2652 goto DoneWithDeclSpec;
2654 ProhibitAttributes(attrs);
2655 // FIXME: It would be good to recover by accepting the attributes,
2656 // but attempting to do that now would cause serious
2657 // madness in terms of diagnostics.
2659 attrs.Range = SourceRange();
2661 ParseCXX11Attributes(attrs);
2662 AttrsLastTime = true;
2665 case tok::code_completion: {
2666 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2667 if (DS.hasTypeSpecifier()) {
2668 bool AllowNonIdentifiers
2669 = (getCurScope()->getFlags() & (Scope::ControlScope |
2671 Scope::TemplateParamScope |
2672 Scope::FunctionPrototypeScope |
2673 Scope::AtCatchScope)) == 0;
2674 bool AllowNestedNameSpecifiers
2675 = DSContext == DSC_top_level ||
2676 (DSContext == DSC_class && DS.isFriendSpecified());
2678 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
2679 AllowNonIdentifiers,
2680 AllowNestedNameSpecifiers);
2681 return cutOffParsing();
2684 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
2685 CCC = Sema::PCC_LocalDeclarationSpecifiers;
2686 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
2687 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
2688 : Sema::PCC_Template;
2689 else if (DSContext == DSC_class)
2690 CCC = Sema::PCC_Class;
2691 else if (CurParsedObjCImpl)
2692 CCC = Sema::PCC_ObjCImplementation;
2694 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
2695 return cutOffParsing();
2698 case tok::coloncolon: // ::foo::bar
2699 // C++ scope specifier. Annotate and loop, or bail out on error.
2700 if (TryAnnotateCXXScopeToken(EnteringContext)) {
2701 if (!DS.hasTypeSpecifier())
2702 DS.SetTypeSpecError();
2703 goto DoneWithDeclSpec;
2705 if (Tok.is(tok::coloncolon)) // ::new or ::delete
2706 goto DoneWithDeclSpec;
2709 case tok::annot_cxxscope: {
2710 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
2711 goto DoneWithDeclSpec;
2714 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2715 Tok.getAnnotationRange(),
2718 // We are looking for a qualified typename.
2719 Token Next = NextToken();
2720 if (Next.is(tok::annot_template_id) &&
2721 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
2722 ->Kind == TNK_Type_template) {
2723 // We have a qualified template-id, e.g., N::A<int>
2725 // C++ [class.qual]p2:
2726 // In a lookup in which the constructor is an acceptable lookup
2727 // result and the nested-name-specifier nominates a class C:
2729 // - if the name specified after the
2730 // nested-name-specifier, when looked up in C, is the
2731 // injected-class-name of C (Clause 9), or
2733 // - if the name specified after the nested-name-specifier
2734 // is the same as the identifier or the
2735 // simple-template-id's template-name in the last
2736 // component of the nested-name-specifier,
2738 // the name is instead considered to name the constructor of
2741 // Thus, if the template-name is actually the constructor
2742 // name, then the code is ill-formed; this interpretation is
2743 // reinforced by the NAD status of core issue 635.
2744 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
2745 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2747 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2748 if (isConstructorDeclarator(/*Unqualified*/false)) {
2749 // The user meant this to be an out-of-line constructor
2750 // definition, but template arguments are not allowed
2751 // there. Just allow this as a constructor; we'll
2752 // complain about it later.
2753 goto DoneWithDeclSpec;
2756 // The user meant this to name a type, but it actually names
2757 // a constructor with some extraneous template
2758 // arguments. Complain, then parse it as a type as the user
2760 Diag(TemplateId->TemplateNameLoc,
2761 diag::err_out_of_line_template_id_names_constructor)
2762 << TemplateId->Name;
2765 DS.getTypeSpecScope() = SS;
2766 ConsumeToken(); // The C++ scope.
2767 assert(Tok.is(tok::annot_template_id) &&
2768 "ParseOptionalCXXScopeSpecifier not working");
2769 AnnotateTemplateIdTokenAsType();
2773 if (Next.is(tok::annot_typename)) {
2774 DS.getTypeSpecScope() = SS;
2775 ConsumeToken(); // The C++ scope.
2776 if (Tok.getAnnotationValue()) {
2777 ParsedType T = getTypeAnnotation(Tok);
2778 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
2779 Tok.getAnnotationEndLoc(),
2780 PrevSpec, DiagID, T, Policy);
2785 DS.SetTypeSpecError();
2786 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2787 ConsumeToken(); // The typename
2790 if (Next.isNot(tok::identifier))
2791 goto DoneWithDeclSpec;
2793 // If we're in a context where the identifier could be a class name,
2794 // check whether this is a constructor declaration.
2795 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2796 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
2798 if (isConstructorDeclarator(/*Unqualified*/false))
2799 goto DoneWithDeclSpec;
2801 // As noted in C++ [class.qual]p2 (cited above), when the name
2802 // of the class is qualified in a context where it could name
2803 // a constructor, its a constructor name. However, we've
2804 // looked at the declarator, and the user probably meant this
2805 // to be a type. Complain that it isn't supposed to be treated
2806 // as a type, then proceed to parse it as a type.
2807 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
2808 << Next.getIdentifierInfo();
2811 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
2814 false, false, ParsedType(),
2815 /*IsCtorOrDtorName=*/false,
2816 /*NonTrivialSourceInfo=*/true);
2818 // If the referenced identifier is not a type, then this declspec is
2819 // erroneous: We already checked about that it has no type specifier, and
2820 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
2823 ConsumeToken(); // Eat the scope spec so the identifier is current.
2824 ParsedAttributesWithRange Attrs(AttrFactory);
2825 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
2826 if (!Attrs.empty()) {
2827 AttrsLastTime = true;
2828 attrs.takeAllFrom(Attrs);
2832 goto DoneWithDeclSpec;
2835 DS.getTypeSpecScope() = SS;
2836 ConsumeToken(); // The C++ scope.
2838 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2839 DiagID, TypeRep, Policy);
2843 DS.SetRangeEnd(Tok.getLocation());
2844 ConsumeToken(); // The typename.
2849 case tok::annot_typename: {
2850 // If we've previously seen a tag definition, we were almost surely
2851 // missing a semicolon after it.
2852 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
2853 goto DoneWithDeclSpec;
2855 if (Tok.getAnnotationValue()) {
2856 ParsedType T = getTypeAnnotation(Tok);
2857 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2860 DS.SetTypeSpecError();
2865 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2866 ConsumeToken(); // The typename
2868 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2869 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2870 // Objective-C interface.
2871 if (Tok.is(tok::less) && getLangOpts().ObjC1)
2872 ParseObjCProtocolQualifiers(DS);
2877 case tok::kw___is_signed:
2878 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
2879 // typically treats it as a trait. If we see __is_signed as it appears
2880 // in libstdc++, e.g.,
2882 // static const bool __is_signed;
2884 // then treat __is_signed as an identifier rather than as a keyword.
2885 if (DS.getTypeSpecType() == TST_bool &&
2886 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
2887 DS.getStorageClassSpec() == DeclSpec::SCS_static)
2888 TryKeywordIdentFallback(true);
2890 // We're done with the declaration-specifiers.
2891 goto DoneWithDeclSpec;
2894 case tok::kw___super:
2895 case tok::kw_decltype:
2896 case tok::identifier: {
2897 // This identifier can only be a typedef name if we haven't already seen
2898 // a type-specifier. Without this check we misparse:
2899 // typedef int X; struct Y { short X; }; as 'short int'.
2900 if (DS.hasTypeSpecifier())
2901 goto DoneWithDeclSpec;
2903 // In C++, check to see if this is a scope specifier like foo::bar::, if
2904 // so handle it as such. This is important for ctor parsing.
2905 if (getLangOpts().CPlusPlus) {
2906 if (TryAnnotateCXXScopeToken(EnteringContext)) {
2907 DS.SetTypeSpecError();
2908 goto DoneWithDeclSpec;
2910 if (!Tok.is(tok::identifier))
2914 // Check for need to substitute AltiVec keyword tokens.
2915 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
2918 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
2919 // allow the use of a typedef name as a type specifier.
2920 if (DS.isTypeAltiVecVector())
2921 goto DoneWithDeclSpec;
2923 ParsedType TypeRep =
2924 Actions.getTypeName(*Tok.getIdentifierInfo(),
2925 Tok.getLocation(), getCurScope());
2927 // MSVC: If we weren't able to parse a default template argument, and it's
2928 // just a simple identifier, create a DependentNameType. This will allow
2929 // us to defer the name lookup to template instantiation time, as long we
2930 // forge a NestedNameSpecifier for the current context.
2931 if (!TypeRep && DSContext == DSC_template_type_arg &&
2932 getLangOpts().MSVCCompat && getCurScope()->isTemplateParamScope()) {
2933 TypeRep = Actions.ActOnDelayedDefaultTemplateArg(
2934 *Tok.getIdentifierInfo(), Tok.getLocation());
2937 // If this is not a typedef name, don't parse it as part of the declspec,
2938 // it must be an implicit int or an error.
2940 ParsedAttributesWithRange Attrs(AttrFactory);
2941 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
2942 if (!Attrs.empty()) {
2943 AttrsLastTime = true;
2944 attrs.takeAllFrom(Attrs);
2948 goto DoneWithDeclSpec;
2951 // If we're in a context where the identifier could be a class name,
2952 // check whether this is a constructor declaration.
2953 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2954 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
2955 isConstructorDeclarator(/*Unqualified*/true))
2956 goto DoneWithDeclSpec;
2958 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2959 DiagID, TypeRep, Policy);
2963 DS.SetRangeEnd(Tok.getLocation());
2964 ConsumeToken(); // The identifier
2966 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2967 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2968 // Objective-C interface.
2969 if (Tok.is(tok::less) && getLangOpts().ObjC1)
2970 ParseObjCProtocolQualifiers(DS);
2972 // Need to support trailing type qualifiers (e.g. "id<p> const").
2973 // If a type specifier follows, it will be diagnosed elsewhere.
2978 case tok::annot_template_id: {
2979 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2980 if (TemplateId->Kind != TNK_Type_template) {
2981 // This template-id does not refer to a type name, so we're
2982 // done with the type-specifiers.
2983 goto DoneWithDeclSpec;
2986 // If we're in a context where the template-id could be a
2987 // constructor name or specialization, check whether this is a
2988 // constructor declaration.
2989 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2990 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
2991 isConstructorDeclarator(TemplateId->SS.isEmpty()))
2992 goto DoneWithDeclSpec;
2994 // Turn the template-id annotation token into a type annotation
2995 // token, then try again to parse it as a type-specifier.
2996 AnnotateTemplateIdTokenAsType();
3000 // GNU attributes support.
3001 case tok::kw___attribute:
3002 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3005 // Microsoft declspec support.
3006 case tok::kw___declspec:
3007 ParseMicrosoftDeclSpecs(DS.getAttributes());
3010 // Microsoft single token adornments.
3011 case tok::kw___forceinline: {
3012 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3013 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3014 SourceLocation AttrNameLoc = Tok.getLocation();
3015 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3016 nullptr, 0, AttributeList::AS_Keyword);
3020 case tok::kw___sptr:
3021 case tok::kw___uptr:
3022 case tok::kw___ptr64:
3023 case tok::kw___ptr32:
3025 case tok::kw___cdecl:
3026 case tok::kw___stdcall:
3027 case tok::kw___fastcall:
3028 case tok::kw___thiscall:
3029 case tok::kw___vectorcall:
3030 case tok::kw___unaligned:
3031 ParseMicrosoftTypeAttributes(DS.getAttributes());
3034 // Borland single token adornments.
3035 case tok::kw___pascal:
3036 ParseBorlandTypeAttributes(DS.getAttributes());
3039 // OpenCL single token adornments.
3040 case tok::kw___kernel:
3041 ParseOpenCLAttributes(DS.getAttributes());
3044 // storage-class-specifier
3045 case tok::kw_typedef:
3046 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3047 PrevSpec, DiagID, Policy);
3048 isStorageClass = true;
3050 case tok::kw_extern:
3051 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3052 Diag(Tok, diag::ext_thread_before) << "extern";
3053 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3054 PrevSpec, DiagID, Policy);
3055 isStorageClass = true;
3057 case tok::kw___private_extern__:
3058 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3059 Loc, PrevSpec, DiagID, Policy);
3060 isStorageClass = true;
3062 case tok::kw_static:
3063 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3064 Diag(Tok, diag::ext_thread_before) << "static";
3065 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3066 PrevSpec, DiagID, Policy);
3067 isStorageClass = true;
3070 if (getLangOpts().CPlusPlus11) {
3071 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3072 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3073 PrevSpec, DiagID, Policy);
3075 Diag(Tok, diag::ext_auto_storage_class)
3076 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3078 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3081 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3082 PrevSpec, DiagID, Policy);
3083 isStorageClass = true;
3085 case tok::kw_register:
3086 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3087 PrevSpec, DiagID, Policy);
3088 isStorageClass = true;
3090 case tok::kw_mutable:
3091 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3092 PrevSpec, DiagID, Policy);
3093 isStorageClass = true;
3095 case tok::kw___thread:
3096 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3098 isStorageClass = true;
3100 case tok::kw_thread_local:
3101 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3104 case tok::kw__Thread_local:
3105 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3106 Loc, PrevSpec, DiagID);
3107 isStorageClass = true;
3110 // function-specifier
3111 case tok::kw_inline:
3112 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3114 case tok::kw_virtual:
3115 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3117 case tok::kw_explicit:
3118 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
3120 case tok::kw__Noreturn:
3121 if (!getLangOpts().C11)
3122 Diag(Loc, diag::ext_c11_noreturn);
3123 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3126 // alignment-specifier
3127 case tok::kw__Alignas:
3128 if (!getLangOpts().C11)
3129 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
3130 ParseAlignmentSpecifier(DS.getAttributes());
3134 case tok::kw_friend:
3135 if (DSContext == DSC_class)
3136 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3138 PrevSpec = ""; // not actually used by the diagnostic
3139 DiagID = diag::err_friend_invalid_in_context;
3145 case tok::kw___module_private__:
3146 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3150 case tok::kw_constexpr:
3151 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3156 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3160 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
3161 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3164 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3167 case tok::kw___int64:
3168 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3171 case tok::kw_signed:
3172 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3175 case tok::kw_unsigned:
3176 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3179 case tok::kw__Complex:
3180 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3183 case tok::kw__Imaginary:
3184 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3188 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3192 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3196 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3199 case tok::kw___int128:
3200 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3204 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3208 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3211 case tok::kw_double:
3212 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3215 case tok::kw_wchar_t:
3216 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3219 case tok::kw_char16_t:
3220 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3223 case tok::kw_char32_t:
3224 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3229 if (Tok.is(tok::kw_bool) &&
3230 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3231 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3232 PrevSpec = ""; // Not used by the diagnostic.
3233 DiagID = diag::err_bool_redeclaration;
3234 // For better error recovery.
3235 Tok.setKind(tok::identifier);
3238 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3242 case tok::kw__Decimal32:
3243 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3246 case tok::kw__Decimal64:
3247 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3250 case tok::kw__Decimal128:
3251 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3254 case tok::kw___vector:
3255 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3257 case tok::kw___pixel:
3258 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3260 case tok::kw___bool:
3261 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3263 case tok::kw___unknown_anytype:
3264 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3265 PrevSpec, DiagID, Policy);
3270 case tok::kw_struct:
3271 case tok::kw___interface:
3272 case tok::kw_union: {
3273 tok::TokenKind Kind = Tok.getKind();
3276 // These are attributes following class specifiers.
3277 // To produce better diagnostic, we parse them when
3278 // parsing class specifier.
3279 ParsedAttributesWithRange Attributes(AttrFactory);
3280 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3281 EnteringContext, DSContext, Attributes);
3283 // If there are attributes following class specifier,
3284 // take them over and handle them here.
3285 if (!Attributes.empty()) {
3286 AttrsLastTime = true;
3287 attrs.takeAllFrom(Attributes);
3295 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3300 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3303 case tok::kw_volatile:
3304 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3307 case tok::kw_restrict:
3308 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3312 // C++ typename-specifier:
3313 case tok::kw_typename:
3314 if (TryAnnotateTypeOrScopeToken()) {
3315 DS.SetTypeSpecError();
3316 goto DoneWithDeclSpec;
3318 if (!Tok.is(tok::kw_typename))
3322 // GNU typeof support.
3323 case tok::kw_typeof:
3324 ParseTypeofSpecifier(DS);
3327 case tok::annot_decltype:
3328 ParseDecltypeSpecifier(DS);
3331 case tok::kw___underlying_type:
3332 ParseUnderlyingTypeSpecifier(DS);
3335 case tok::kw__Atomic:
3337 // If the _Atomic keyword is immediately followed by a left parenthesis,
3338 // it is interpreted as a type specifier (with a type name), not as a
3340 if (NextToken().is(tok::l_paren)) {
3341 ParseAtomicSpecifier(DS);
3344 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3348 // OpenCL qualifiers:
3349 case tok::kw___generic:
3350 // generic address space is introduced only in OpenCL v2.0
3351 // see OpenCL C Spec v2.0 s6.5.5
3352 if (Actions.getLangOpts().OpenCLVersion < 200) {
3353 DiagID = diag::err_opencl_unknown_type_specifier;
3354 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3358 case tok::kw___private:
3359 case tok::kw___global:
3360 case tok::kw___local:
3361 case tok::kw___constant:
3362 case tok::kw___read_only:
3363 case tok::kw___write_only:
3364 case tok::kw___read_write:
3365 ParseOpenCLQualifiers(DS.getAttributes());
3369 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3370 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3371 // but we support it.
3372 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
3373 goto DoneWithDeclSpec;
3375 if (!ParseObjCProtocolQualifiers(DS))
3376 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
3377 << FixItHint::CreateInsertion(Loc, "id")
3378 << SourceRange(Loc, DS.getSourceRange().getEnd());
3380 // Need to support trailing type qualifiers (e.g. "id<p> const").
3381 // If a type specifier follows, it will be diagnosed elsewhere.
3384 // If the specifier wasn't legal, issue a diagnostic.
3386 assert(PrevSpec && "Method did not return previous specifier!");
3389 if (DiagID == diag::ext_duplicate_declspec)
3391 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
3392 else if (DiagID == diag::err_opencl_unknown_type_specifier)
3393 Diag(Tok, DiagID) << PrevSpec << isStorageClass;
3395 Diag(Tok, DiagID) << PrevSpec;
3398 DS.SetRangeEnd(Tok.getLocation());
3399 if (DiagID != diag::err_bool_redeclaration)
3402 AttrsLastTime = false;
3406 /// ParseStructDeclaration - Parse a struct declaration without the terminating
3409 /// struct-declaration:
3410 /// specifier-qualifier-list struct-declarator-list
3411 /// [GNU] __extension__ struct-declaration
3412 /// [GNU] specifier-qualifier-list
3413 /// struct-declarator-list:
3414 /// struct-declarator
3415 /// struct-declarator-list ',' struct-declarator
3416 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3417 /// struct-declarator:
3419 /// [GNU] declarator attributes[opt]
3420 /// declarator[opt] ':' constant-expression
3421 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3423 void Parser::ParseStructDeclaration(
3424 ParsingDeclSpec &DS,
3425 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
3427 if (Tok.is(tok::kw___extension__)) {
3428 // __extension__ silences extension warnings in the subexpression.
3429 ExtensionRAIIObject O(Diags); // Use RAII to do this.
3431 return ParseStructDeclaration(DS, FieldsCallback);
3434 // Parse the common specifier-qualifiers-list piece.
3435 ParseSpecifierQualifierList(DS);
3437 // If there are no declarators, this is a free-standing declaration
3438 // specifier. Let the actions module cope with it.
3439 if (Tok.is(tok::semi)) {
3440 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
3442 DS.complete(TheDecl);
3446 // Read struct-declarators until we find the semicolon.
3447 bool FirstDeclarator = true;
3448 SourceLocation CommaLoc;
3450 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
3451 DeclaratorInfo.D.setCommaLoc(CommaLoc);
3453 // Attributes are only allowed here on successive declarators.
3454 if (!FirstDeclarator)
3455 MaybeParseGNUAttributes(DeclaratorInfo.D);
3457 /// struct-declarator: declarator
3458 /// struct-declarator: declarator[opt] ':' constant-expression
3459 if (Tok.isNot(tok::colon)) {
3460 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3461 ColonProtectionRAIIObject X(*this);
3462 ParseDeclarator(DeclaratorInfo.D);
3464 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
3466 if (TryConsumeToken(tok::colon)) {
3467 ExprResult Res(ParseConstantExpression());
3468 if (Res.isInvalid())
3469 SkipUntil(tok::semi, StopBeforeMatch);
3471 DeclaratorInfo.BitfieldSize = Res.get();
3474 // If attributes exist after the declarator, parse them.
3475 MaybeParseGNUAttributes(DeclaratorInfo.D);
3477 // We're done with this declarator; invoke the callback.
3478 FieldsCallback(DeclaratorInfo);
3480 // If we don't have a comma, it is either the end of the list (a ';')
3481 // or an error, bail out.
3482 if (!TryConsumeToken(tok::comma, CommaLoc))
3485 FirstDeclarator = false;
3489 /// ParseStructUnionBody
3490 /// struct-contents:
3491 /// struct-declaration-list
3493 /// [GNU] "struct-declaration-list" without terminatoring ';'
3494 /// struct-declaration-list:
3495 /// struct-declaration
3496 /// struct-declaration-list struct-declaration
3497 /// [OBC] '@' 'defs' '(' class-name ')'
3499 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
3500 unsigned TagType, Decl *TagDecl) {
3501 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3502 "parsing struct/union body");
3503 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
3505 BalancedDelimiterTracker T(*this, tok::l_brace);
3506 if (T.consumeOpen())
3509 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
3510 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3512 SmallVector<Decl *, 32> FieldDecls;
3514 // While we still have something to read, read the declarations in the struct.
3515 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
3516 // Each iteration of this loop reads one struct-declaration.
3518 // Check for extraneous top-level semicolon.
3519 if (Tok.is(tok::semi)) {
3520 ConsumeExtraSemi(InsideStruct, TagType);
3524 // Parse _Static_assert declaration.
3525 if (Tok.is(tok::kw__Static_assert)) {
3526 SourceLocation DeclEnd;
3527 ParseStaticAssertDeclaration(DeclEnd);
3531 if (Tok.is(tok::annot_pragma_pack)) {
3536 if (Tok.is(tok::annot_pragma_align)) {
3537 HandlePragmaAlign();
3541 if (!Tok.is(tok::at)) {
3542 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
3543 // Install the declarator into the current TagDecl.
3545 Actions.ActOnField(getCurScope(), TagDecl,
3546 FD.D.getDeclSpec().getSourceRange().getBegin(),
3547 FD.D, FD.BitfieldSize);
3548 FieldDecls.push_back(Field);
3552 // Parse all the comma separated declarators.
3553 ParsingDeclSpec DS(*this);
3554 ParseStructDeclaration(DS, CFieldCallback);
3555 } else { // Handle @defs
3557 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
3558 Diag(Tok, diag::err_unexpected_at);
3559 SkipUntil(tok::semi);
3563 ExpectAndConsume(tok::l_paren);
3564 if (!Tok.is(tok::identifier)) {
3565 Diag(Tok, diag::err_expected) << tok::identifier;
3566 SkipUntil(tok::semi);
3569 SmallVector<Decl *, 16> Fields;
3570 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
3571 Tok.getIdentifierInfo(), Fields);
3572 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
3574 ExpectAndConsume(tok::r_paren);
3577 if (TryConsumeToken(tok::semi))
3580 if (Tok.is(tok::r_brace)) {
3581 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
3585 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
3586 // Skip to end of block or statement to avoid ext-warning on extra ';'.
3587 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
3588 // If we stopped at a ';', eat it.
3589 TryConsumeToken(tok::semi);
3594 ParsedAttributes attrs(AttrFactory);
3595 // If attributes exist after struct contents, parse them.
3596 MaybeParseGNUAttributes(attrs);
3598 Actions.ActOnFields(getCurScope(),
3599 RecordLoc, TagDecl, FieldDecls,
3600 T.getOpenLocation(), T.getCloseLocation(),
3603 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
3604 T.getCloseLocation());
3607 /// ParseEnumSpecifier
3608 /// enum-specifier: [C99 6.7.2.2]
3609 /// 'enum' identifier[opt] '{' enumerator-list '}'
3610 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
3611 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
3612 /// '}' attributes[opt]
3613 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
3615 /// 'enum' identifier
3616 /// [GNU] 'enum' attributes[opt] identifier
3618 /// [C++11] enum-head '{' enumerator-list[opt] '}'
3619 /// [C++11] enum-head '{' enumerator-list ',' '}'
3621 /// enum-head: [C++11]
3622 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
3623 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
3624 /// identifier enum-base[opt]
3626 /// enum-key: [C++11]
3631 /// enum-base: [C++11]
3632 /// ':' type-specifier-seq
3634 /// [C++] elaborated-type-specifier:
3635 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
3637 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
3638 const ParsedTemplateInfo &TemplateInfo,
3639 AccessSpecifier AS, DeclSpecContext DSC) {
3640 // Parse the tag portion of this.
3641 if (Tok.is(tok::code_completion)) {
3642 // Code completion for an enum name.
3643 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
3644 return cutOffParsing();
3647 // If attributes exist after tag, parse them.
3648 ParsedAttributesWithRange attrs(AttrFactory);
3649 MaybeParseGNUAttributes(attrs);
3650 MaybeParseCXX11Attributes(attrs);
3651 MaybeParseMicrosoftDeclSpecs(attrs);
3653 SourceLocation ScopedEnumKWLoc;
3654 bool IsScopedUsingClassTag = false;
3656 // In C++11, recognize 'enum class' and 'enum struct'.
3657 if (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct)) {
3658 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
3659 : diag::ext_scoped_enum);
3660 IsScopedUsingClassTag = Tok.is(tok::kw_class);
3661 ScopedEnumKWLoc = ConsumeToken();
3663 // Attributes are not allowed between these keywords. Diagnose,
3664 // but then just treat them like they appeared in the right place.
3665 ProhibitAttributes(attrs);
3667 // They are allowed afterwards, though.
3668 MaybeParseGNUAttributes(attrs);
3669 MaybeParseCXX11Attributes(attrs);
3670 MaybeParseMicrosoftDeclSpecs(attrs);
3673 // C++11 [temp.explicit]p12:
3674 // The usual access controls do not apply to names used to specify
3675 // explicit instantiations.
3676 // We extend this to also cover explicit specializations. Note that
3677 // we don't suppress if this turns out to be an elaborated type
3679 bool shouldDelayDiagsInTag =
3680 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3681 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3682 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
3684 // Enum definitions should not be parsed in a trailing-return-type.
3685 bool AllowDeclaration = DSC != DSC_trailing;
3687 bool AllowFixedUnderlyingType = AllowDeclaration &&
3688 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
3689 getLangOpts().ObjC2);
3691 CXXScopeSpec &SS = DS.getTypeSpecScope();
3692 if (getLangOpts().CPlusPlus) {
3693 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
3694 // if a fixed underlying type is allowed.
3695 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
3698 if (ParseOptionalCXXScopeSpecifier(Spec, ParsedType(),
3699 /*EnteringContext=*/true))
3702 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
3703 Diag(Tok, diag::err_expected) << tok::identifier;
3704 if (Tok.isNot(tok::l_brace)) {
3705 // Has no name and is not a definition.
3706 // Skip the rest of this declarator, up until the comma or semicolon.
3707 SkipUntil(tok::comma, StopAtSemi);
3715 // Must have either 'enum name' or 'enum {...}'.
3716 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
3717 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
3718 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
3720 // Skip the rest of this declarator, up until the comma or semicolon.
3721 SkipUntil(tok::comma, StopAtSemi);
3725 // If an identifier is present, consume and remember it.
3726 IdentifierInfo *Name = nullptr;
3727 SourceLocation NameLoc;
3728 if (Tok.is(tok::identifier)) {
3729 Name = Tok.getIdentifierInfo();
3730 NameLoc = ConsumeToken();
3733 if (!Name && ScopedEnumKWLoc.isValid()) {
3734 // C++0x 7.2p2: The optional identifier shall not be omitted in the
3735 // declaration of a scoped enumeration.
3736 Diag(Tok, diag::err_scoped_enum_missing_identifier);
3737 ScopedEnumKWLoc = SourceLocation();
3738 IsScopedUsingClassTag = false;
3741 // Okay, end the suppression area. We'll decide whether to emit the
3742 // diagnostics in a second.
3743 if (shouldDelayDiagsInTag)
3744 diagsFromTag.done();
3746 TypeResult BaseType;
3748 // Parse the fixed underlying type.
3749 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
3750 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
3751 bool PossibleBitfield = false;
3752 if (CanBeBitfield) {
3753 // If we're in class scope, this can either be an enum declaration with
3754 // an underlying type, or a declaration of a bitfield member. We try to
3755 // use a simple disambiguation scheme first to catch the common cases
3756 // (integer literal, sizeof); if it's still ambiguous, we then consider
3757 // anything that's a simple-type-specifier followed by '(' as an
3758 // expression. This suffices because function types are not valid
3759 // underlying types anyway.
3760 EnterExpressionEvaluationContext Unevaluated(Actions,
3761 Sema::ConstantEvaluated);
3762 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
3763 // If the next token starts an expression, we know we're parsing a
3764 // bit-field. This is the common case.
3765 if (TPR == TPResult::True)
3766 PossibleBitfield = true;
3767 // If the next token starts a type-specifier-seq, it may be either a
3768 // a fixed underlying type or the start of a function-style cast in C++;
3769 // lookahead one more token to see if it's obvious that we have a
3770 // fixed underlying type.
3771 else if (TPR == TPResult::False &&
3772 GetLookAheadToken(2).getKind() == tok::semi) {
3776 // We have the start of a type-specifier-seq, so we have to perform
3777 // tentative parsing to determine whether we have an expression or a
3779 TentativeParsingAction TPA(*this);
3784 // If we see a type specifier followed by an open-brace, we have an
3785 // ambiguity between an underlying type and a C++11 braced
3786 // function-style cast. Resolve this by always treating it as an
3788 // FIXME: The standard is not entirely clear on how to disambiguate in
3790 if ((getLangOpts().CPlusPlus &&
3791 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
3792 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
3793 // We'll parse this as a bitfield later.
3794 PossibleBitfield = true;
3797 // We have a type-specifier-seq.
3806 if (!PossibleBitfield) {
3808 BaseType = ParseTypeName(&Range);
3810 if (getLangOpts().CPlusPlus11) {
3811 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
3812 } else if (!getLangOpts().ObjC2) {
3813 if (getLangOpts().CPlusPlus)
3814 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
3816 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
3821 // There are four options here. If we have 'friend enum foo;' then this is a
3822 // friend declaration, and cannot have an accompanying definition. If we have
3823 // 'enum foo;', then this is a forward declaration. If we have
3824 // 'enum foo {...' then this is a definition. Otherwise we have something
3825 // like 'enum foo xyz', a reference.
3827 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
3828 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
3829 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
3831 Sema::TagUseKind TUK;
3832 if (!AllowDeclaration) {
3833 TUK = Sema::TUK_Reference;
3834 } else if (Tok.is(tok::l_brace)) {
3835 if (DS.isFriendSpecified()) {
3836 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
3837 << SourceRange(DS.getFriendSpecLoc());
3839 SkipUntil(tok::r_brace, StopAtSemi);
3840 TUK = Sema::TUK_Friend;
3842 TUK = Sema::TUK_Definition;
3844 } else if (!isTypeSpecifier(DSC) &&
3845 (Tok.is(tok::semi) ||
3846 (Tok.isAtStartOfLine() &&
3847 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
3848 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
3849 if (Tok.isNot(tok::semi)) {
3850 // A semicolon was missing after this declaration. Diagnose and recover.
3851 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
3853 Tok.setKind(tok::semi);
3856 TUK = Sema::TUK_Reference;
3859 // If this is an elaborated type specifier, and we delayed
3860 // diagnostics before, just merge them into the current pool.
3861 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
3862 diagsFromTag.redelay();
3865 MultiTemplateParamsArg TParams;
3866 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
3867 TUK != Sema::TUK_Reference) {
3868 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
3869 // Skip the rest of this declarator, up until the comma or semicolon.
3870 Diag(Tok, diag::err_enum_template);
3871 SkipUntil(tok::comma, StopAtSemi);
3875 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
3876 // Enumerations can't be explicitly instantiated.
3877 DS.SetTypeSpecError();
3878 Diag(StartLoc, diag::err_explicit_instantiation_enum);
3882 assert(TemplateInfo.TemplateParams && "no template parameters");
3883 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
3884 TemplateInfo.TemplateParams->size());
3887 if (TUK == Sema::TUK_Reference)
3888 ProhibitAttributes(attrs);
3890 if (!Name && TUK != Sema::TUK_Definition) {
3891 Diag(Tok, diag::err_enumerator_unnamed_no_def);
3893 // Skip the rest of this declarator, up until the comma or semicolon.
3894 SkipUntil(tok::comma, StopAtSemi);
3898 handleDeclspecAlignBeforeClassKey(attrs, DS, TUK);
3900 Sema::SkipBodyInfo SkipBody;
3901 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
3902 NextToken().is(tok::identifier))
3903 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
3904 NextToken().getIdentifierInfo(),
3905 NextToken().getLocation());
3908 bool IsDependent = false;
3909 const char *PrevSpec = nullptr;
3911 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
3912 StartLoc, SS, Name, NameLoc, attrs.getList(),
3913 AS, DS.getModulePrivateSpecLoc(), TParams,
3914 Owned, IsDependent, ScopedEnumKWLoc,
3915 IsScopedUsingClassTag, BaseType,
3916 DSC == DSC_type_specifier, &SkipBody);
3918 if (SkipBody.ShouldSkip) {
3919 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
3921 BalancedDelimiterTracker T(*this, tok::l_brace);
3925 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
3926 NameLoc.isValid() ? NameLoc : StartLoc,
3927 PrevSpec, DiagID, TagDecl, Owned,
3928 Actions.getASTContext().getPrintingPolicy()))
3929 Diag(StartLoc, DiagID) << PrevSpec;
3934 // This enum has a dependent nested-name-specifier. Handle it as a
3937 DS.SetTypeSpecError();
3938 Diag(Tok, diag::err_expected_type_name_after_typename);
3942 TypeResult Type = Actions.ActOnDependentTag(
3943 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
3944 if (Type.isInvalid()) {
3945 DS.SetTypeSpecError();
3949 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
3950 NameLoc.isValid() ? NameLoc : StartLoc,
3951 PrevSpec, DiagID, Type.get(),
3952 Actions.getASTContext().getPrintingPolicy()))
3953 Diag(StartLoc, DiagID) << PrevSpec;
3959 // The action failed to produce an enumeration tag. If this is a
3960 // definition, consume the entire definition.
3961 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
3963 SkipUntil(tok::r_brace, StopAtSemi);
3966 DS.SetTypeSpecError();
3970 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference)
3971 ParseEnumBody(StartLoc, TagDecl);
3973 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
3974 NameLoc.isValid() ? NameLoc : StartLoc,
3975 PrevSpec, DiagID, TagDecl, Owned,
3976 Actions.getASTContext().getPrintingPolicy()))
3977 Diag(StartLoc, DiagID) << PrevSpec;
3980 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
3981 /// enumerator-list:
3983 /// enumerator-list ',' enumerator
3985 /// enumeration-constant attributes[opt]
3986 /// enumeration-constant attributes[opt] '=' constant-expression
3987 /// enumeration-constant:
3990 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
3991 // Enter the scope of the enum body and start the definition.
3992 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
3993 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
3995 BalancedDelimiterTracker T(*this, tok::l_brace);
3998 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
3999 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4000 Diag(Tok, diag::error_empty_enum);
4002 SmallVector<Decl *, 32> EnumConstantDecls;
4003 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4005 Decl *LastEnumConstDecl = nullptr;
4007 // Parse the enumerator-list.
4008 while (Tok.isNot(tok::r_brace)) {
4009 // Parse enumerator. If failed, try skipping till the start of the next
4010 // enumerator definition.
4011 if (Tok.isNot(tok::identifier)) {
4012 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4013 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4014 TryConsumeToken(tok::comma))
4018 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4019 SourceLocation IdentLoc = ConsumeToken();
4021 // If attributes exist after the enumerator, parse them.
4022 ParsedAttributesWithRange attrs(AttrFactory);
4023 MaybeParseGNUAttributes(attrs);
4024 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4025 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
4026 if (!getLangOpts().CPlusPlus1z)
4027 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
4028 << 1 /*enumerator*/;
4029 ParseCXX11Attributes(attrs);
4032 SourceLocation EqualLoc;
4033 ExprResult AssignedVal;
4034 EnumAvailabilityDiags.emplace_back(*this);
4036 if (TryConsumeToken(tok::equal, EqualLoc)) {
4037 AssignedVal = ParseConstantExpression();
4038 if (AssignedVal.isInvalid())
4039 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4042 // Install the enumerator constant into EnumDecl.
4043 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
4046 attrs.getList(), EqualLoc,
4048 EnumAvailabilityDiags.back().done();
4050 EnumConstantDecls.push_back(EnumConstDecl);
4051 LastEnumConstDecl = EnumConstDecl;
4053 if (Tok.is(tok::identifier)) {
4054 // We're missing a comma between enumerators.
4055 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
4056 Diag(Loc, diag::err_enumerator_list_missing_comma)
4057 << FixItHint::CreateInsertion(Loc, ", ");
4061 // Emumerator definition must be finished, only comma or r_brace are
4063 SourceLocation CommaLoc;
4064 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4065 if (EqualLoc.isValid())
4066 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4069 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4070 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4071 if (TryConsumeToken(tok::comma, CommaLoc))
4078 // If comma is followed by r_brace, emit appropriate warning.
4079 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4080 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4081 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4082 diag::ext_enumerator_list_comma_cxx :
4083 diag::ext_enumerator_list_comma_c)
4084 << FixItHint::CreateRemoval(CommaLoc);
4085 else if (getLangOpts().CPlusPlus11)
4086 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4087 << FixItHint::CreateRemoval(CommaLoc);
4095 // If attributes exist after the identifier list, parse them.
4096 ParsedAttributes attrs(AttrFactory);
4097 MaybeParseGNUAttributes(attrs);
4099 Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(),
4100 EnumDecl, EnumConstantDecls,
4104 // Now handle enum constant availability diagnostics.
4105 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4106 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4107 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4108 EnumAvailabilityDiags[i].redelay();
4109 PD.complete(EnumConstantDecls[i]);
4113 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl,
4114 T.getCloseLocation());
4116 // The next token must be valid after an enum definition. If not, a ';'
4117 // was probably forgotten.
4118 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4119 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4120 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4121 // Push this token back into the preprocessor and change our current token
4122 // to ';' so that the rest of the code recovers as though there were an
4123 // ';' after the definition.
4125 Tok.setKind(tok::semi);
4129 /// isTypeSpecifierQualifier - Return true if the current token could be the
4130 /// start of a type-qualifier-list.
4131 bool Parser::isTypeQualifier() const {
4132 switch (Tok.getKind()) {
4133 default: return false;
4136 case tok::kw_volatile:
4137 case tok::kw_restrict:
4138 case tok::kw___private:
4139 case tok::kw___local:
4140 case tok::kw___global:
4141 case tok::kw___constant:
4142 case tok::kw___generic:
4143 case tok::kw___read_only:
4144 case tok::kw___read_write:
4145 case tok::kw___write_only:
4150 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4151 /// is definitely a type-specifier. Return false if it isn't part of a type
4152 /// specifier or if we're not sure.
4153 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4154 switch (Tok.getKind()) {
4155 default: return false;
4159 case tok::kw___int64:
4160 case tok::kw___int128:
4161 case tok::kw_signed:
4162 case tok::kw_unsigned:
4163 case tok::kw__Complex:
4164 case tok::kw__Imaginary:
4167 case tok::kw_wchar_t:
4168 case tok::kw_char16_t:
4169 case tok::kw_char32_t:
4173 case tok::kw_double:
4176 case tok::kw__Decimal32:
4177 case tok::kw__Decimal64:
4178 case tok::kw__Decimal128:
4179 case tok::kw___vector:
4181 // struct-or-union-specifier (C99) or class-specifier (C++)
4183 case tok::kw_struct:
4184 case tok::kw___interface:
4190 case tok::annot_typename:
4195 /// isTypeSpecifierQualifier - Return true if the current token could be the
4196 /// start of a specifier-qualifier-list.
4197 bool Parser::isTypeSpecifierQualifier() {
4198 switch (Tok.getKind()) {
4199 default: return false;
4201 case tok::identifier: // foo::bar
4202 if (TryAltiVecVectorToken())
4205 case tok::kw_typename: // typename T::type
4206 // Annotate typenames and C++ scope specifiers. If we get one, just
4207 // recurse to handle whatever we get.
4208 if (TryAnnotateTypeOrScopeToken())
4210 if (Tok.is(tok::identifier))
4212 return isTypeSpecifierQualifier();
4214 case tok::coloncolon: // ::foo::bar
4215 if (NextToken().is(tok::kw_new) || // ::new
4216 NextToken().is(tok::kw_delete)) // ::delete
4219 if (TryAnnotateTypeOrScopeToken())
4221 return isTypeSpecifierQualifier();
4223 // GNU attributes support.
4224 case tok::kw___attribute:
4225 // GNU typeof support.
4226 case tok::kw_typeof:
4231 case tok::kw___int64:
4232 case tok::kw___int128:
4233 case tok::kw_signed:
4234 case tok::kw_unsigned:
4235 case tok::kw__Complex:
4236 case tok::kw__Imaginary:
4239 case tok::kw_wchar_t:
4240 case tok::kw_char16_t:
4241 case tok::kw_char32_t:
4245 case tok::kw_double:
4248 case tok::kw__Decimal32:
4249 case tok::kw__Decimal64:
4250 case tok::kw__Decimal128:
4251 case tok::kw___vector:
4253 // struct-or-union-specifier (C99) or class-specifier (C++)
4255 case tok::kw_struct:
4256 case tok::kw___interface:
4263 case tok::kw_volatile:
4264 case tok::kw_restrict:
4266 // Debugger support.
4267 case tok::kw___unknown_anytype:
4270 case tok::annot_typename:
4273 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4275 return getLangOpts().ObjC1;
4277 case tok::kw___cdecl:
4278 case tok::kw___stdcall:
4279 case tok::kw___fastcall:
4280 case tok::kw___thiscall:
4281 case tok::kw___vectorcall:
4283 case tok::kw___ptr64:
4284 case tok::kw___ptr32:
4285 case tok::kw___pascal:
4286 case tok::kw___unaligned:
4288 case tok::kw___private:
4289 case tok::kw___local:
4290 case tok::kw___global:
4291 case tok::kw___constant:
4292 case tok::kw___generic:
4293 case tok::kw___read_only:
4294 case tok::kw___read_write:
4295 case tok::kw___write_only:
4300 case tok::kw__Atomic:
4305 /// isDeclarationSpecifier() - Return true if the current token is part of a
4306 /// declaration specifier.
4308 /// \param DisambiguatingWithExpression True to indicate that the purpose of
4309 /// this check is to disambiguate between an expression and a declaration.
4310 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4311 switch (Tok.getKind()) {
4312 default: return false;
4314 case tok::identifier: // foo::bar
4315 // Unfortunate hack to support "Class.factoryMethod" notation.
4316 if (getLangOpts().ObjC1 && NextToken().is(tok::period))
4318 if (TryAltiVecVectorToken())
4321 case tok::kw_decltype: // decltype(T())::type
4322 case tok::kw_typename: // typename T::type
4323 // Annotate typenames and C++ scope specifiers. If we get one, just
4324 // recurse to handle whatever we get.
4325 if (TryAnnotateTypeOrScopeToken())
4327 if (Tok.is(tok::identifier))
4330 // If we're in Objective-C and we have an Objective-C class type followed
4331 // by an identifier and then either ':' or ']', in a place where an
4332 // expression is permitted, then this is probably a class message send
4333 // missing the initial '['. In this case, we won't consider this to be
4334 // the start of a declaration.
4335 if (DisambiguatingWithExpression &&
4336 isStartOfObjCClassMessageMissingOpenBracket())
4339 return isDeclarationSpecifier();
4341 case tok::coloncolon: // ::foo::bar
4342 if (NextToken().is(tok::kw_new) || // ::new
4343 NextToken().is(tok::kw_delete)) // ::delete
4346 // Annotate typenames and C++ scope specifiers. If we get one, just
4347 // recurse to handle whatever we get.
4348 if (TryAnnotateTypeOrScopeToken())
4350 return isDeclarationSpecifier();
4352 // storage-class-specifier
4353 case tok::kw_typedef:
4354 case tok::kw_extern:
4355 case tok::kw___private_extern__:
4356 case tok::kw_static:
4358 case tok::kw_register:
4359 case tok::kw___thread:
4360 case tok::kw_thread_local:
4361 case tok::kw__Thread_local:
4364 case tok::kw___module_private__:
4367 case tok::kw___unknown_anytype:
4372 case tok::kw___int64:
4373 case tok::kw___int128:
4374 case tok::kw_signed:
4375 case tok::kw_unsigned:
4376 case tok::kw__Complex:
4377 case tok::kw__Imaginary:
4380 case tok::kw_wchar_t:
4381 case tok::kw_char16_t:
4382 case tok::kw_char32_t:
4387 case tok::kw_double:
4390 case tok::kw__Decimal32:
4391 case tok::kw__Decimal64:
4392 case tok::kw__Decimal128:
4393 case tok::kw___vector:
4395 // struct-or-union-specifier (C99) or class-specifier (C++)
4397 case tok::kw_struct:
4399 case tok::kw___interface:
4405 case tok::kw_volatile:
4406 case tok::kw_restrict:
4408 // function-specifier
4409 case tok::kw_inline:
4410 case tok::kw_virtual:
4411 case tok::kw_explicit:
4412 case tok::kw__Noreturn:
4414 // alignment-specifier
4415 case tok::kw__Alignas:
4418 case tok::kw_friend:
4420 // static_assert-declaration
4421 case tok::kw__Static_assert:
4423 // GNU typeof support.
4424 case tok::kw_typeof:
4427 case tok::kw___attribute:
4429 // C++11 decltype and constexpr.
4430 case tok::annot_decltype:
4431 case tok::kw_constexpr:
4434 case tok::kw__Atomic:
4437 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4439 return getLangOpts().ObjC1;
4442 case tok::annot_typename:
4443 return !DisambiguatingWithExpression ||
4444 !isStartOfObjCClassMessageMissingOpenBracket();
4446 case tok::kw___declspec:
4447 case tok::kw___cdecl:
4448 case tok::kw___stdcall:
4449 case tok::kw___fastcall:
4450 case tok::kw___thiscall:
4451 case tok::kw___vectorcall:
4453 case tok::kw___sptr:
4454 case tok::kw___uptr:
4455 case tok::kw___ptr64:
4456 case tok::kw___ptr32:
4457 case tok::kw___forceinline:
4458 case tok::kw___pascal:
4459 case tok::kw___unaligned:
4461 case tok::kw___private:
4462 case tok::kw___local:
4463 case tok::kw___global:
4464 case tok::kw___constant:
4465 case tok::kw___generic:
4466 case tok::kw___read_only:
4467 case tok::kw___read_write:
4468 case tok::kw___write_only:
4474 bool Parser::isConstructorDeclarator(bool IsUnqualified) {
4475 TentativeParsingAction TPA(*this);
4477 // Parse the C++ scope specifier.
4479 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
4480 /*EnteringContext=*/true)) {
4485 // Parse the constructor name.
4486 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
4487 // We already know that we have a constructor name; just consume
4495 // Current class name must be followed by a left parenthesis.
4496 if (Tok.isNot(tok::l_paren)) {
4502 // A right parenthesis, or ellipsis followed by a right parenthesis signals
4503 // that we have a constructor.
4504 if (Tok.is(tok::r_paren) ||
4505 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
4510 // A C++11 attribute here signals that we have a constructor, and is an
4511 // attribute on the first constructor parameter.
4512 if (getLangOpts().CPlusPlus11 &&
4513 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
4514 /*OuterMightBeMessageSend*/ true)) {
4519 // If we need to, enter the specified scope.
4520 DeclaratorScopeObj DeclScopeObj(*this, SS);
4521 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
4522 DeclScopeObj.EnterDeclaratorScope();
4524 // Optionally skip Microsoft attributes.
4525 ParsedAttributes Attrs(AttrFactory);
4526 MaybeParseMicrosoftAttributes(Attrs);
4528 // Check whether the next token(s) are part of a declaration
4529 // specifier, in which case we have the start of a parameter and,
4530 // therefore, we know that this is a constructor.
4531 bool IsConstructor = false;
4532 if (isDeclarationSpecifier())
4533 IsConstructor = true;
4534 else if (Tok.is(tok::identifier) ||
4535 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
4536 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
4537 // This might be a parenthesized member name, but is more likely to
4538 // be a constructor declaration with an invalid argument type. Keep
4540 if (Tok.is(tok::annot_cxxscope))
4544 // If this is not a constructor, we must be parsing a declarator,
4545 // which must have one of the following syntactic forms (see the
4546 // grammar extract at the start of ParseDirectDeclarator):
4547 switch (Tok.getKind()) {
4552 // C(X [ [attribute]]);
4553 case tok::coloncolon:
4556 // Assume this isn't a constructor, rather than assuming it's a
4557 // constructor with an unnamed parameter of an ill-formed type.
4562 if (NextToken().is(tok::colon) || NextToken().is(tok::kw_try)) {
4563 // Assume these were meant to be constructors:
4564 // C(X) : (the name of a bit-field cannot be parenthesized).
4565 // C(X) try (this is otherwise ill-formed).
4566 IsConstructor = true;
4568 if (NextToken().is(tok::semi) || NextToken().is(tok::l_brace)) {
4569 // If we have a constructor name within the class definition,
4570 // assume these were meant to be constructors:
4573 // ... because otherwise we would be declaring a non-static data
4574 // member that is ill-formed because it's of the same type as its
4575 // surrounding class.
4577 // FIXME: We can actually do this whether or not the name is qualified,
4578 // because if it is qualified in this context it must be being used as
4579 // a constructor name. However, we do not implement that rule correctly
4580 // currently, so we're somewhat conservative here.
4581 IsConstructor = IsUnqualified;
4586 IsConstructor = true;
4592 return IsConstructor;
4595 /// ParseTypeQualifierListOpt
4596 /// type-qualifier-list: [C99 6.7.5]
4598 /// [vendor] attributes
4599 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
4600 /// type-qualifier-list type-qualifier
4601 /// [vendor] type-qualifier-list attributes
4602 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
4603 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
4604 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
4605 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
4606 /// AttrRequirements bitmask values.
4607 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, unsigned AttrReqs,
4609 bool IdentifierRequired) {
4610 if (getLangOpts().CPlusPlus11 && (AttrReqs & AR_CXX11AttributesParsed) &&
4611 isCXX11AttributeSpecifier()) {
4612 ParsedAttributesWithRange attrs(AttrFactory);
4613 ParseCXX11Attributes(attrs);
4614 DS.takeAttributesFrom(attrs);
4617 SourceLocation EndLoc;
4620 bool isInvalid = false;
4621 const char *PrevSpec = nullptr;
4622 unsigned DiagID = 0;
4623 SourceLocation Loc = Tok.getLocation();
4625 switch (Tok.getKind()) {
4626 case tok::code_completion:
4627 Actions.CodeCompleteTypeQualifiers(DS);
4628 return cutOffParsing();
4631 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
4634 case tok::kw_volatile:
4635 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4638 case tok::kw_restrict:
4639 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4642 case tok::kw__Atomic:
4644 goto DoneWithTypeQuals;
4645 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4649 // OpenCL qualifiers:
4650 case tok::kw___private:
4651 case tok::kw___global:
4652 case tok::kw___local:
4653 case tok::kw___constant:
4654 case tok::kw___generic:
4655 case tok::kw___read_only:
4656 case tok::kw___write_only:
4657 case tok::kw___read_write:
4658 ParseOpenCLQualifiers(DS.getAttributes());
4661 case tok::kw___uptr:
4662 // GNU libc headers in C mode use '__uptr' as an identifer which conflicts
4663 // with the MS modifier keyword.
4664 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
4665 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
4666 if (TryKeywordIdentFallback(false))
4669 case tok::kw___sptr:
4671 case tok::kw___ptr64:
4672 case tok::kw___ptr32:
4673 case tok::kw___cdecl:
4674 case tok::kw___stdcall:
4675 case tok::kw___fastcall:
4676 case tok::kw___thiscall:
4677 case tok::kw___vectorcall:
4678 case tok::kw___unaligned:
4679 if (AttrReqs & AR_DeclspecAttributesParsed) {
4680 ParseMicrosoftTypeAttributes(DS.getAttributes());
4683 goto DoneWithTypeQuals;
4684 case tok::kw___pascal:
4685 if (AttrReqs & AR_VendorAttributesParsed) {
4686 ParseBorlandTypeAttributes(DS.getAttributes());
4689 goto DoneWithTypeQuals;
4690 case tok::kw___attribute:
4691 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
4692 // When GNU attributes are expressly forbidden, diagnose their usage.
4693 Diag(Tok, diag::err_attributes_not_allowed);
4695 // Parse the attributes even if they are rejected to ensure that error
4696 // recovery is graceful.
4697 if (AttrReqs & AR_GNUAttributesParsed ||
4698 AttrReqs & AR_GNUAttributesParsedAndRejected) {
4699 ParseGNUAttributes(DS.getAttributes());
4700 continue; // do *not* consume the next token!
4702 // otherwise, FALL THROUGH!
4705 // If this is not a type-qualifier token, we're done reading type
4706 // qualifiers. First verify that DeclSpec's are consistent.
4707 DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy());
4708 if (EndLoc.isValid())
4709 DS.SetRangeEnd(EndLoc);
4713 // If the specifier combination wasn't legal, issue a diagnostic.
4715 assert(PrevSpec && "Method did not return previous specifier!");
4716 Diag(Tok, DiagID) << PrevSpec;
4718 EndLoc = ConsumeToken();
4723 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
4725 void Parser::ParseDeclarator(Declarator &D) {
4726 /// This implements the 'declarator' production in the C grammar, then checks
4727 /// for well-formedness and issues diagnostics.
4728 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
4731 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
4732 unsigned TheContext) {
4733 if (Kind == tok::star || Kind == tok::caret)
4736 if (!Lang.CPlusPlus)
4739 if (Kind == tok::amp)
4742 // We parse rvalue refs in C++03, because otherwise the errors are scary.
4743 // But we must not parse them in conversion-type-ids and new-type-ids, since
4744 // those can be legitimately followed by a && operator.
4745 // (The same thing can in theory happen after a trailing-return-type, but
4746 // since those are a C++11 feature, there is no rejects-valid issue there.)
4747 if (Kind == tok::ampamp)
4748 return Lang.CPlusPlus11 || (TheContext != Declarator::ConversionIdContext &&
4749 TheContext != Declarator::CXXNewContext);
4754 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
4755 /// is parsed by the function passed to it. Pass null, and the direct-declarator
4756 /// isn't parsed at all, making this function effectively parse the C++
4757 /// ptr-operator production.
4759 /// If the grammar of this construct is extended, matching changes must also be
4760 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
4761 /// isConstructorDeclarator.
4763 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
4764 /// [C] pointer[opt] direct-declarator
4765 /// [C++] direct-declarator
4766 /// [C++] ptr-operator declarator
4768 /// pointer: [C99 6.7.5]
4769 /// '*' type-qualifier-list[opt]
4770 /// '*' type-qualifier-list[opt] pointer
4773 /// '*' cv-qualifier-seq[opt]
4776 /// [GNU] '&' restrict[opt] attributes[opt]
4777 /// [GNU?] '&&' restrict[opt] attributes[opt]
4778 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
4779 void Parser::ParseDeclaratorInternal(Declarator &D,
4780 DirectDeclParseFunction DirectDeclParser) {
4781 if (Diags.hasAllExtensionsSilenced())
4784 // C++ member pointers start with a '::' or a nested-name.
4785 // Member pointers get special handling, since there's no place for the
4786 // scope spec in the generic path below.
4787 if (getLangOpts().CPlusPlus &&
4788 (Tok.is(tok::coloncolon) ||
4789 (Tok.is(tok::identifier) &&
4790 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
4791 Tok.is(tok::annot_cxxscope))) {
4792 bool EnteringContext = D.getContext() == Declarator::FileContext ||
4793 D.getContext() == Declarator::MemberContext;
4795 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext);
4797 if (SS.isNotEmpty()) {
4798 if (Tok.isNot(tok::star)) {
4799 // The scope spec really belongs to the direct-declarator.
4800 if (D.mayHaveIdentifier())
4801 D.getCXXScopeSpec() = SS;
4803 AnnotateScopeToken(SS, true);
4805 if (DirectDeclParser)
4806 (this->*DirectDeclParser)(D);
4810 SourceLocation Loc = ConsumeToken();
4812 DeclSpec DS(AttrFactory);
4813 ParseTypeQualifierListOpt(DS);
4814 D.ExtendWithDeclSpec(DS);
4816 // Recurse to parse whatever is left.
4817 ParseDeclaratorInternal(D, DirectDeclParser);
4819 // Sema will have to catch (syntactically invalid) pointers into global
4820 // scope. It has to catch pointers into namespace scope anyway.
4821 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
4824 /* Don't replace range end. */SourceLocation());
4829 tok::TokenKind Kind = Tok.getKind();
4830 // Not a pointer, C++ reference, or block.
4831 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
4832 if (DirectDeclParser)
4833 (this->*DirectDeclParser)(D);
4837 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
4838 // '&&' -> rvalue reference
4839 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
4842 if (Kind == tok::star || Kind == tok::caret) {
4844 DeclSpec DS(AttrFactory);
4846 // GNU attributes are not allowed here in a new-type-id, but Declspec and
4847 // C++11 attributes are allowed.
4848 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
4849 ((D.getContext() != Declarator::CXXNewContext)
4850 ? AR_GNUAttributesParsed
4851 : AR_GNUAttributesParsedAndRejected);
4852 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
4853 D.ExtendWithDeclSpec(DS);
4855 // Recursively parse the declarator.
4856 ParseDeclaratorInternal(D, DirectDeclParser);
4857 if (Kind == tok::star)
4858 // Remember that we parsed a pointer type, and remember the type-quals.
4859 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
4860 DS.getConstSpecLoc(),
4861 DS.getVolatileSpecLoc(),
4862 DS.getRestrictSpecLoc(),
4863 DS.getAtomicSpecLoc()),
4867 // Remember that we parsed a Block type, and remember the type-quals.
4868 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
4874 DeclSpec DS(AttrFactory);
4876 // Complain about rvalue references in C++03, but then go on and build
4878 if (Kind == tok::ampamp)
4879 Diag(Loc, getLangOpts().CPlusPlus11 ?
4880 diag::warn_cxx98_compat_rvalue_reference :
4881 diag::ext_rvalue_reference);
4883 // GNU-style and C++11 attributes are allowed here, as is restrict.
4884 ParseTypeQualifierListOpt(DS);
4885 D.ExtendWithDeclSpec(DS);
4887 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
4888 // cv-qualifiers are introduced through the use of a typedef or of a
4889 // template type argument, in which case the cv-qualifiers are ignored.
4890 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
4891 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4892 Diag(DS.getConstSpecLoc(),
4893 diag::err_invalid_reference_qualifier_application) << "const";
4894 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4895 Diag(DS.getVolatileSpecLoc(),
4896 diag::err_invalid_reference_qualifier_application) << "volatile";
4897 // 'restrict' is permitted as an extension.
4898 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4899 Diag(DS.getAtomicSpecLoc(),
4900 diag::err_invalid_reference_qualifier_application) << "_Atomic";
4903 // Recursively parse the declarator.
4904 ParseDeclaratorInternal(D, DirectDeclParser);
4906 if (D.getNumTypeObjects() > 0) {
4907 // C++ [dcl.ref]p4: There shall be no references to references.
4908 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
4909 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
4910 if (const IdentifierInfo *II = D.getIdentifier())
4911 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
4914 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
4917 // Once we've complained about the reference-to-reference, we
4918 // can go ahead and build the (technically ill-formed)
4919 // declarator: reference collapsing will take care of it.
4923 // Remember that we parsed a reference type.
4924 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
4931 // When correcting from misplaced brackets before the identifier, the location
4932 // is saved inside the declarator so that other diagnostic messages can use
4933 // them. This extracts and returns that location, or returns the provided
4934 // location if a stored location does not exist.
4935 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
4936 SourceLocation Loc) {
4937 if (D.getName().StartLocation.isInvalid() &&
4938 D.getName().EndLocation.isValid())
4939 return D.getName().EndLocation;
4944 /// ParseDirectDeclarator
4945 /// direct-declarator: [C99 6.7.5]
4946 /// [C99] identifier
4947 /// '(' declarator ')'
4948 /// [GNU] '(' attributes declarator ')'
4949 /// [C90] direct-declarator '[' constant-expression[opt] ']'
4950 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
4951 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
4952 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
4953 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
4954 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
4955 /// attribute-specifier-seq[opt]
4956 /// direct-declarator '(' parameter-type-list ')'
4957 /// direct-declarator '(' identifier-list[opt] ')'
4958 /// [GNU] direct-declarator '(' parameter-forward-declarations
4959 /// parameter-type-list[opt] ')'
4960 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
4961 /// cv-qualifier-seq[opt] exception-specification[opt]
4962 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
4963 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
4964 /// ref-qualifier[opt] exception-specification[opt]
4965 /// [C++] declarator-id
4966 /// [C++11] declarator-id attribute-specifier-seq[opt]
4968 /// declarator-id: [C++ 8]
4969 /// '...'[opt] id-expression
4970 /// '::'[opt] nested-name-specifier[opt] type-name
4972 /// id-expression: [C++ 5.1]
4976 /// unqualified-id: [C++ 5.1]
4978 /// operator-function-id
4979 /// conversion-function-id
4983 /// Note, any additional constructs added here may need corresponding changes
4984 /// in isConstructorDeclarator.
4985 void Parser::ParseDirectDeclarator(Declarator &D) {
4986 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
4988 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
4989 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
4990 // this context it is a bitfield. Also in range-based for statement colon
4991 // may delimit for-range-declaration.
4992 ColonProtectionRAIIObject X(*this,
4993 D.getContext() == Declarator::MemberContext ||
4994 (D.getContext() == Declarator::ForContext &&
4995 getLangOpts().CPlusPlus11));
4997 // ParseDeclaratorInternal might already have parsed the scope.
4998 if (D.getCXXScopeSpec().isEmpty()) {
4999 bool EnteringContext = D.getContext() == Declarator::FileContext ||
5000 D.getContext() == Declarator::MemberContext;
5001 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(),
5005 if (D.getCXXScopeSpec().isValid()) {
5006 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5007 D.getCXXScopeSpec()))
5008 // Change the declaration context for name lookup, until this function
5009 // is exited (and the declarator has been parsed).
5010 DeclScopeObj.EnterDeclaratorScope();
5013 // C++0x [dcl.fct]p14:
5014 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5015 // parameter-declaration-clause without a preceding comma. In this case,
5016 // the ellipsis is parsed as part of the abstract-declarator if the type
5017 // of the parameter either names a template parameter pack that has not
5018 // been expanded or contains auto; otherwise, it is parsed as part of the
5019 // parameter-declaration-clause.
5020 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
5021 !((D.getContext() == Declarator::PrototypeContext ||
5022 D.getContext() == Declarator::LambdaExprParameterContext ||
5023 D.getContext() == Declarator::BlockLiteralContext) &&
5024 NextToken().is(tok::r_paren) &&
5025 !D.hasGroupingParens() &&
5026 !Actions.containsUnexpandedParameterPacks(D) &&
5027 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
5028 SourceLocation EllipsisLoc = ConsumeToken();
5029 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
5030 // The ellipsis was put in the wrong place. Recover, and explain to
5031 // the user what they should have done.
5033 if (EllipsisLoc.isValid())
5034 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5037 D.setEllipsisLoc(EllipsisLoc);
5039 // The ellipsis can't be followed by a parenthesized declarator. We
5040 // check for that in ParseParenDeclarator, after we have disambiguated
5041 // the l_paren token.
5044 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
5045 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
5046 // We found something that indicates the start of an unqualified-id.
5047 // Parse that unqualified-id.
5048 bool AllowConstructorName;
5049 if (D.getDeclSpec().hasTypeSpecifier())
5050 AllowConstructorName = false;
5051 else if (D.getCXXScopeSpec().isSet())
5052 AllowConstructorName =
5053 (D.getContext() == Declarator::FileContext ||
5054 D.getContext() == Declarator::MemberContext);
5056 AllowConstructorName = (D.getContext() == Declarator::MemberContext);
5058 SourceLocation TemplateKWLoc;
5059 bool HadScope = D.getCXXScopeSpec().isValid();
5060 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5061 /*EnteringContext=*/true,
5062 /*AllowDestructorName=*/true,
5063 AllowConstructorName,
5067 // Once we're past the identifier, if the scope was bad, mark the
5068 // whole declarator bad.
5069 D.getCXXScopeSpec().isInvalid()) {
5070 D.SetIdentifier(nullptr, Tok.getLocation());
5071 D.setInvalidType(true);
5073 // ParseUnqualifiedId might have parsed a scope specifier during error
5074 // recovery. If it did so, enter that scope.
5075 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5076 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5077 D.getCXXScopeSpec()))
5078 DeclScopeObj.EnterDeclaratorScope();
5080 // Parsed the unqualified-id; update range information and move along.
5081 if (D.getSourceRange().getBegin().isInvalid())
5082 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5083 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
5085 goto PastIdentifier;
5087 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
5088 assert(!getLangOpts().CPlusPlus &&
5089 "There's a C++-specific check for tok::identifier above");
5090 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5091 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5092 D.SetRangeEnd(Tok.getLocation());
5094 goto PastIdentifier;
5095 } else if (Tok.is(tok::identifier) && D.diagnoseIdentifier()) {
5096 // A virt-specifier isn't treated as an identifier if it appears after a
5097 // trailing-return-type.
5098 if (D.getContext() != Declarator::TrailingReturnContext ||
5099 !isCXX11VirtSpecifier(Tok)) {
5100 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5101 << FixItHint::CreateRemoval(Tok.getLocation());
5102 D.SetIdentifier(nullptr, Tok.getLocation());
5104 goto PastIdentifier;
5108 if (Tok.is(tok::l_paren)) {
5109 // direct-declarator: '(' declarator ')'
5110 // direct-declarator: '(' attributes declarator ')'
5111 // Example: 'char (*X)' or 'int (*XX)(void)'
5112 ParseParenDeclarator(D);
5114 // If the declarator was parenthesized, we entered the declarator
5115 // scope when parsing the parenthesized declarator, then exited
5116 // the scope already. Re-enter the scope, if we need to.
5117 if (D.getCXXScopeSpec().isSet()) {
5118 // If there was an error parsing parenthesized declarator, declarator
5119 // scope may have been entered before. Don't do it again.
5120 if (!D.isInvalidType() &&
5121 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5122 D.getCXXScopeSpec()))
5123 // Change the declaration context for name lookup, until this function
5124 // is exited (and the declarator has been parsed).
5125 DeclScopeObj.EnterDeclaratorScope();
5127 } else if (D.mayOmitIdentifier()) {
5128 // This could be something simple like "int" (in which case the declarator
5129 // portion is empty), if an abstract-declarator is allowed.
5130 D.SetIdentifier(nullptr, Tok.getLocation());
5132 // The grammar for abstract-pack-declarator does not allow grouping parens.
5133 // FIXME: Revisit this once core issue 1488 is resolved.
5134 if (D.hasEllipsis() && D.hasGroupingParens())
5135 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5136 diag::ext_abstract_pack_declarator_parens);
5138 if (Tok.getKind() == tok::annot_pragma_parser_crash)
5140 if (Tok.is(tok::l_square))
5141 return ParseMisplacedBracketDeclarator(D);
5142 if (D.getContext() == Declarator::MemberContext) {
5143 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5144 diag::err_expected_member_name_or_semi)
5145 << (D.getDeclSpec().isEmpty() ? SourceRange()
5146 : D.getDeclSpec().getSourceRange());
5147 } else if (getLangOpts().CPlusPlus) {
5148 if (Tok.is(tok::period) || Tok.is(tok::arrow))
5149 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
5151 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5152 if (Tok.isAtStartOfLine() && Loc.isValid())
5153 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5154 << getLangOpts().CPlusPlus;
5156 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5157 diag::err_expected_unqualified_id)
5158 << getLangOpts().CPlusPlus;
5161 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5162 diag::err_expected_either)
5163 << tok::identifier << tok::l_paren;
5165 D.SetIdentifier(nullptr, Tok.getLocation());
5166 D.setInvalidType(true);
5170 assert(D.isPastIdentifier() &&
5171 "Haven't past the location of the identifier yet?");
5173 // Don't parse attributes unless we have parsed an unparenthesized name.
5174 if (D.hasName() && !D.getNumTypeObjects())
5175 MaybeParseCXX11Attributes(D);
5178 if (Tok.is(tok::l_paren)) {
5179 // Enter function-declaration scope, limiting any declarators to the
5180 // function prototype scope, including parameter declarators.
5181 ParseScope PrototypeScope(this,
5182 Scope::FunctionPrototypeScope|Scope::DeclScope|
5183 (D.isFunctionDeclaratorAFunctionDeclaration()
5184 ? Scope::FunctionDeclarationScope : 0));
5186 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5187 // In such a case, check if we actually have a function declarator; if it
5188 // is not, the declarator has been fully parsed.
5189 bool IsAmbiguous = false;
5190 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5191 // The name of the declarator, if any, is tentatively declared within
5192 // a possible direct initializer.
5193 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5194 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5195 TentativelyDeclaredIdentifiers.pop_back();
5196 if (!IsFunctionDecl)
5199 ParsedAttributes attrs(AttrFactory);
5200 BalancedDelimiterTracker T(*this, tok::l_paren);
5202 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
5203 PrototypeScope.Exit();
5204 } else if (Tok.is(tok::l_square)) {
5205 ParseBracketDeclarator(D);
5212 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
5213 /// only called before the identifier, so these are most likely just grouping
5214 /// parens for precedence. If we find that these are actually function
5215 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5217 /// direct-declarator:
5218 /// '(' declarator ')'
5219 /// [GNU] '(' attributes declarator ')'
5220 /// direct-declarator '(' parameter-type-list ')'
5221 /// direct-declarator '(' identifier-list[opt] ')'
5222 /// [GNU] direct-declarator '(' parameter-forward-declarations
5223 /// parameter-type-list[opt] ')'
5225 void Parser::ParseParenDeclarator(Declarator &D) {
5226 BalancedDelimiterTracker T(*this, tok::l_paren);
5229 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
5231 // Eat any attributes before we look at whether this is a grouping or function
5232 // declarator paren. If this is a grouping paren, the attribute applies to
5233 // the type being built up, for example:
5234 // int (__attribute__(()) *x)(long y)
5235 // If this ends up not being a grouping paren, the attribute applies to the
5236 // first argument, for example:
5237 // int (__attribute__(()) int x)
5238 // In either case, we need to eat any attributes to be able to determine what
5239 // sort of paren this is.
5241 ParsedAttributes attrs(AttrFactory);
5242 bool RequiresArg = false;
5243 if (Tok.is(tok::kw___attribute)) {
5244 ParseGNUAttributes(attrs);
5246 // We require that the argument list (if this is a non-grouping paren) be
5247 // present even if the attribute list was empty.
5251 // Eat any Microsoft extensions.
5252 ParseMicrosoftTypeAttributes(attrs);
5254 // Eat any Borland extensions.
5255 if (Tok.is(tok::kw___pascal))
5256 ParseBorlandTypeAttributes(attrs);
5258 // If we haven't past the identifier yet (or where the identifier would be
5259 // stored, if this is an abstract declarator), then this is probably just
5260 // grouping parens. However, if this could be an abstract-declarator, then
5261 // this could also be the start of function arguments (consider 'void()').
5264 if (!D.mayOmitIdentifier()) {
5265 // If this can't be an abstract-declarator, this *must* be a grouping
5266 // paren, because we haven't seen the identifier yet.
5268 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
5269 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
5270 NextToken().is(tok::r_paren)) || // C++ int(...)
5271 isDeclarationSpecifier() || // 'int(int)' is a function.
5272 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
5273 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
5274 // considered to be a type, not a K&R identifier-list.
5277 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
5281 // If this is a grouping paren, handle:
5282 // direct-declarator: '(' declarator ')'
5283 // direct-declarator: '(' attributes declarator ')'
5285 SourceLocation EllipsisLoc = D.getEllipsisLoc();
5286 D.setEllipsisLoc(SourceLocation());
5288 bool hadGroupingParens = D.hasGroupingParens();
5289 D.setGroupingParens(true);
5290 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5293 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
5294 T.getCloseLocation()),
5295 attrs, T.getCloseLocation());
5297 D.setGroupingParens(hadGroupingParens);
5299 // An ellipsis cannot be placed outside parentheses.
5300 if (EllipsisLoc.isValid())
5301 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5306 // Okay, if this wasn't a grouping paren, it must be the start of a function
5307 // argument list. Recognize that this declarator will never have an
5308 // identifier (and remember where it would have been), then call into
5309 // ParseFunctionDeclarator to handle of argument list.
5310 D.SetIdentifier(nullptr, Tok.getLocation());
5312 // Enter function-declaration scope, limiting any declarators to the
5313 // function prototype scope, including parameter declarators.
5314 ParseScope PrototypeScope(this,
5315 Scope::FunctionPrototypeScope | Scope::DeclScope |
5316 (D.isFunctionDeclaratorAFunctionDeclaration()
5317 ? Scope::FunctionDeclarationScope : 0));
5318 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
5319 PrototypeScope.Exit();
5322 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
5323 /// declarator D up to a paren, which indicates that we are parsing function
5326 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
5327 /// immediately after the open paren - they should be considered to be the
5328 /// first argument of a parameter.
5330 /// If RequiresArg is true, then the first argument of the function is required
5331 /// to be present and required to not be an identifier list.
5333 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
5334 /// (C++11) ref-qualifier[opt], exception-specification[opt],
5335 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
5337 /// [C++11] exception-specification:
5338 /// dynamic-exception-specification
5339 /// noexcept-specification
5341 void Parser::ParseFunctionDeclarator(Declarator &D,
5342 ParsedAttributes &FirstArgAttrs,
5343 BalancedDelimiterTracker &Tracker,
5346 assert(getCurScope()->isFunctionPrototypeScope() &&
5347 "Should call from a Function scope");
5348 // lparen is already consumed!
5349 assert(D.isPastIdentifier() && "Should not call before identifier!");
5351 // This should be true when the function has typed arguments.
5352 // Otherwise, it is treated as a K&R-style function.
5353 bool HasProto = false;
5354 // Build up an array of information about the parsed arguments.
5355 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
5356 // Remember where we see an ellipsis, if any.
5357 SourceLocation EllipsisLoc;
5359 DeclSpec DS(AttrFactory);
5360 bool RefQualifierIsLValueRef = true;
5361 SourceLocation RefQualifierLoc;
5362 SourceLocation ConstQualifierLoc;
5363 SourceLocation VolatileQualifierLoc;
5364 SourceLocation RestrictQualifierLoc;
5365 ExceptionSpecificationType ESpecType = EST_None;
5366 SourceRange ESpecRange;
5367 SmallVector<ParsedType, 2> DynamicExceptions;
5368 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5369 ExprResult NoexceptExpr;
5370 CachedTokens *ExceptionSpecTokens = 0;
5371 ParsedAttributes FnAttrs(AttrFactory);
5372 TypeResult TrailingReturnType;
5374 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
5375 EndLoc is the end location for the function declarator.
5376 They differ for trailing return types. */
5377 SourceLocation StartLoc, LocalEndLoc, EndLoc;
5378 SourceLocation LParenLoc, RParenLoc;
5379 LParenLoc = Tracker.getOpenLocation();
5380 StartLoc = LParenLoc;
5382 if (isFunctionDeclaratorIdentifierList()) {
5384 Diag(Tok, diag::err_argument_required_after_attribute);
5386 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
5388 Tracker.consumeClose();
5389 RParenLoc = Tracker.getCloseLocation();
5390 LocalEndLoc = RParenLoc;
5393 if (Tok.isNot(tok::r_paren))
5394 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
5396 else if (RequiresArg)
5397 Diag(Tok, diag::err_argument_required_after_attribute);
5399 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
5401 // If we have the closing ')', eat it.
5402 Tracker.consumeClose();
5403 RParenLoc = Tracker.getCloseLocation();
5404 LocalEndLoc = RParenLoc;
5407 if (getLangOpts().CPlusPlus) {
5408 // FIXME: Accept these components in any order, and produce fixits to
5409 // correct the order if the user gets it wrong. Ideally we should deal
5410 // with the pure-specifier in the same way.
5412 // Parse cv-qualifier-seq[opt].
5413 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
5414 /*AtomicAllowed*/ false);
5415 if (!DS.getSourceRange().getEnd().isInvalid()) {
5416 EndLoc = DS.getSourceRange().getEnd();
5417 ConstQualifierLoc = DS.getConstSpecLoc();
5418 VolatileQualifierLoc = DS.getVolatileSpecLoc();
5419 RestrictQualifierLoc = DS.getRestrictSpecLoc();
5422 // Parse ref-qualifier[opt].
5423 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
5424 EndLoc = RefQualifierLoc;
5426 // C++11 [expr.prim.general]p3:
5427 // If a declaration declares a member function or member function
5428 // template of a class X, the expression this is a prvalue of type
5429 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5430 // and the end of the function-definition, member-declarator, or
5432 // FIXME: currently, "static" case isn't handled correctly.
5433 bool IsCXX11MemberFunction =
5434 getLangOpts().CPlusPlus11 &&
5435 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5436 (D.getContext() == Declarator::MemberContext
5437 ? !D.getDeclSpec().isFriendSpecified()
5438 : D.getContext() == Declarator::FileContext &&
5439 D.getCXXScopeSpec().isValid() &&
5440 Actions.CurContext->isRecord());
5441 Sema::CXXThisScopeRAII ThisScope(Actions,
5442 dyn_cast<CXXRecordDecl>(Actions.CurContext),
5443 DS.getTypeQualifiers() |
5444 (D.getDeclSpec().isConstexprSpecified() &&
5445 !getLangOpts().CPlusPlus14
5446 ? Qualifiers::Const : 0),
5447 IsCXX11MemberFunction);
5449 // Parse exception-specification[opt].
5450 bool Delayed = D.isFirstDeclarationOfMember() &&
5451 D.isFunctionDeclaratorAFunctionDeclaration();
5452 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
5453 GetLookAheadToken(0).is(tok::kw_noexcept) &&
5454 GetLookAheadToken(1).is(tok::l_paren) &&
5455 GetLookAheadToken(2).is(tok::kw_noexcept) &&
5456 GetLookAheadToken(3).is(tok::l_paren) &&
5457 GetLookAheadToken(4).is(tok::identifier) &&
5458 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
5459 // HACK: We've got an exception-specification
5460 // noexcept(noexcept(swap(...)))
5462 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
5463 // on a 'swap' member function. This is a libstdc++ bug; the lookup
5464 // for 'swap' will only find the function we're currently declaring,
5465 // whereas it expects to find a non-member swap through ADL. Turn off
5466 // delayed parsing to give it a chance to find what it expects.
5469 ESpecType = tryParseExceptionSpecification(Delayed,
5472 DynamicExceptionRanges,
5474 ExceptionSpecTokens);
5475 if (ESpecType != EST_None)
5476 EndLoc = ESpecRange.getEnd();
5478 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
5479 // after the exception-specification.
5480 MaybeParseCXX11Attributes(FnAttrs);
5482 // Parse trailing-return-type[opt].
5483 LocalEndLoc = EndLoc;
5484 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
5485 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
5486 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
5487 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5488 LocalEndLoc = Tok.getLocation();
5490 TrailingReturnType = ParseTrailingReturnType(Range);
5491 EndLoc = Range.getEnd();
5496 // Remember that we parsed a function type, and remember the attributes.
5497 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
5500 ParamInfo.data(), ParamInfo.size(),
5501 EllipsisLoc, RParenLoc,
5502 DS.getTypeQualifiers(),
5503 RefQualifierIsLValueRef,
5504 RefQualifierLoc, ConstQualifierLoc,
5505 VolatileQualifierLoc,
5506 RestrictQualifierLoc,
5507 /*MutableLoc=*/SourceLocation(),
5508 ESpecType, ESpecRange.getBegin(),
5509 DynamicExceptions.data(),
5510 DynamicExceptionRanges.data(),
5511 DynamicExceptions.size(),
5512 NoexceptExpr.isUsable() ?
5513 NoexceptExpr.get() : nullptr,
5514 ExceptionSpecTokens,
5515 StartLoc, LocalEndLoc, D,
5516 TrailingReturnType),
5520 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
5521 /// true if a ref-qualifier is found.
5522 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
5523 SourceLocation &RefQualifierLoc) {
5524 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
5525 Diag(Tok, getLangOpts().CPlusPlus11 ?
5526 diag::warn_cxx98_compat_ref_qualifier :
5527 diag::ext_ref_qualifier);
5529 RefQualifierIsLValueRef = Tok.is(tok::amp);
5530 RefQualifierLoc = ConsumeToken();
5536 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
5537 /// identifier list form for a K&R-style function: void foo(a,b,c)
5539 /// Note that identifier-lists are only allowed for normal declarators, not for
5540 /// abstract-declarators.
5541 bool Parser::isFunctionDeclaratorIdentifierList() {
5542 return !getLangOpts().CPlusPlus
5543 && Tok.is(tok::identifier)
5544 && !TryAltiVecVectorToken()
5545 // K&R identifier lists can't have typedefs as identifiers, per C99
5547 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
5548 // Identifier lists follow a really simple grammar: the identifiers can
5549 // be followed *only* by a ", identifier" or ")". However, K&R
5550 // identifier lists are really rare in the brave new modern world, and
5551 // it is very common for someone to typo a type in a non-K&R style
5552 // list. If we are presented with something like: "void foo(intptr x,
5553 // float y)", we don't want to start parsing the function declarator as
5554 // though it is a K&R style declarator just because intptr is an
5557 // To handle this, we check to see if the token after the first
5558 // identifier is a "," or ")". Only then do we parse it as an
5560 && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren));
5563 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
5564 /// we found a K&R-style identifier list instead of a typed parameter list.
5566 /// After returning, ParamInfo will hold the parsed parameters.
5568 /// identifier-list: [C99 6.7.5]
5570 /// identifier-list ',' identifier
5572 void Parser::ParseFunctionDeclaratorIdentifierList(
5574 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
5575 // If there was no identifier specified for the declarator, either we are in
5576 // an abstract-declarator, or we are in a parameter declarator which was found
5577 // to be abstract. In abstract-declarators, identifier lists are not valid:
5579 if (!D.getIdentifier())
5580 Diag(Tok, diag::ext_ident_list_in_param);
5582 // Maintain an efficient lookup of params we have seen so far.
5583 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
5586 // If this isn't an identifier, report the error and skip until ')'.
5587 if (Tok.isNot(tok::identifier)) {
5588 Diag(Tok, diag::err_expected) << tok::identifier;
5589 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
5590 // Forget we parsed anything.
5595 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
5597 // Reject 'typedef int y; int test(x, y)', but continue parsing.
5598 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
5599 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
5601 // Verify that the argument identifier has not already been mentioned.
5602 if (!ParamsSoFar.insert(ParmII).second) {
5603 Diag(Tok, diag::err_param_redefinition) << ParmII;
5605 // Remember this identifier in ParamInfo.
5606 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
5611 // Eat the identifier.
5613 // The list continues if we see a comma.
5614 } while (TryConsumeToken(tok::comma));
5617 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
5618 /// after the opening parenthesis. This function will not parse a K&R-style
5619 /// identifier list.
5621 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
5622 /// caller parsed those arguments immediately after the open paren - they should
5623 /// be considered to be part of the first parameter.
5625 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
5626 /// be the location of the ellipsis, if any was parsed.
5628 /// parameter-type-list: [C99 6.7.5]
5630 /// parameter-list ',' '...'
5631 /// [C++] parameter-list '...'
5633 /// parameter-list: [C99 6.7.5]
5634 /// parameter-declaration
5635 /// parameter-list ',' parameter-declaration
5637 /// parameter-declaration: [C99 6.7.5]
5638 /// declaration-specifiers declarator
5639 /// [C++] declaration-specifiers declarator '=' assignment-expression
5640 /// [C++11] initializer-clause
5641 /// [GNU] declaration-specifiers declarator attributes
5642 /// declaration-specifiers abstract-declarator[opt]
5643 /// [C++] declaration-specifiers abstract-declarator[opt]
5644 /// '=' assignment-expression
5645 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
5646 /// [C++11] attribute-specifier-seq parameter-declaration
5648 void Parser::ParseParameterDeclarationClause(
5650 ParsedAttributes &FirstArgAttrs,
5651 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
5652 SourceLocation &EllipsisLoc) {
5654 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
5655 // before deciding this was a parameter-declaration-clause.
5656 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
5659 // Parse the declaration-specifiers.
5660 // Just use the ParsingDeclaration "scope" of the declarator.
5661 DeclSpec DS(AttrFactory);
5663 // Parse any C++11 attributes.
5664 MaybeParseCXX11Attributes(DS.getAttributes());
5666 // Skip any Microsoft attributes before a param.
5667 MaybeParseMicrosoftAttributes(DS.getAttributes());
5669 SourceLocation DSStart = Tok.getLocation();
5671 // If the caller parsed attributes for the first argument, add them now.
5672 // Take them so that we only apply the attributes to the first parameter.
5673 // FIXME: If we can leave the attributes in the token stream somehow, we can
5674 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
5676 DS.takeAttributesFrom(FirstArgAttrs);
5678 ParseDeclarationSpecifiers(DS);
5681 // Parse the declarator. This is "PrototypeContext" or
5682 // "LambdaExprParameterContext", because we must accept either
5683 // 'declarator' or 'abstract-declarator' here.
5684 Declarator ParmDeclarator(DS,
5685 D.getContext() == Declarator::LambdaExprContext ?
5686 Declarator::LambdaExprParameterContext :
5687 Declarator::PrototypeContext);
5688 ParseDeclarator(ParmDeclarator);
5690 // Parse GNU attributes, if present.
5691 MaybeParseGNUAttributes(ParmDeclarator);
5693 // Remember this parsed parameter in ParamInfo.
5694 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
5696 // DefArgToks is used when the parsing of default arguments needs
5698 CachedTokens *DefArgToks = nullptr;
5700 // If no parameter was specified, verify that *something* was specified,
5701 // otherwise we have a missing type and identifier.
5702 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
5703 ParmDeclarator.getNumTypeObjects() == 0) {
5704 // Completely missing, emit error.
5705 Diag(DSStart, diag::err_missing_param);
5707 // Otherwise, we have something. Add it and let semantic analysis try
5708 // to grok it and add the result to the ParamInfo we are building.
5710 // Last chance to recover from a misplaced ellipsis in an attempted
5711 // parameter pack declaration.
5712 if (Tok.is(tok::ellipsis) &&
5713 (NextToken().isNot(tok::r_paren) ||
5714 (!ParmDeclarator.getEllipsisLoc().isValid() &&
5715 !Actions.isUnexpandedParameterPackPermitted())) &&
5716 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
5717 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
5719 // Inform the actions module about the parameter declarator, so it gets
5720 // added to the current scope.
5721 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
5722 // Parse the default argument, if any. We parse the default
5723 // arguments in all dialects; the semantic analysis in
5724 // ActOnParamDefaultArgument will reject the default argument in
5726 if (Tok.is(tok::equal)) {
5727 SourceLocation EqualLoc = Tok.getLocation();
5729 // Parse the default argument
5730 if (D.getContext() == Declarator::MemberContext) {
5731 // If we're inside a class definition, cache the tokens
5732 // corresponding to the default argument. We'll actually parse
5733 // them when we see the end of the class definition.
5734 // FIXME: Can we use a smart pointer for Toks?
5735 DefArgToks = new CachedTokens;
5737 SourceLocation ArgStartLoc = NextToken().getLocation();
5738 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
5740 DefArgToks = nullptr;
5741 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
5743 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
5750 // The argument isn't actually potentially evaluated unless it is
5752 EnterExpressionEvaluationContext Eval(Actions,
5753 Sema::PotentiallyEvaluatedIfUsed,
5756 ExprResult DefArgResult;
5757 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
5758 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
5759 DefArgResult = ParseBraceInitializer();
5761 DefArgResult = ParseAssignmentExpression();
5762 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
5763 if (DefArgResult.isInvalid()) {
5764 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
5765 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
5767 // Inform the actions module about the default argument
5768 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
5769 DefArgResult.get());
5774 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
5775 ParmDeclarator.getIdentifierLoc(),
5776 Param, DefArgToks));
5779 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
5780 if (!getLangOpts().CPlusPlus) {
5781 // We have ellipsis without a preceding ',', which is ill-formed
5782 // in C. Complain and provide the fix.
5783 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
5784 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
5785 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
5786 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
5787 // It looks like this was supposed to be a parameter pack. Warn and
5788 // point out where the ellipsis should have gone.
5789 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
5790 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
5791 << ParmEllipsis.isValid() << ParmEllipsis;
5792 if (ParmEllipsis.isValid()) {
5794 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
5796 Diag(ParmDeclarator.getIdentifierLoc(),
5797 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
5798 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
5800 << !ParmDeclarator.hasName();
5802 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
5803 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
5806 // We can't have any more parameters after an ellipsis.
5810 // If the next token is a comma, consume it and keep reading arguments.
5811 } while (TryConsumeToken(tok::comma));
5814 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5815 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5816 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5817 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5818 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5819 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5820 /// attribute-specifier-seq[opt]
5821 void Parser::ParseBracketDeclarator(Declarator &D) {
5822 if (CheckProhibitedCXX11Attribute())
5825 BalancedDelimiterTracker T(*this, tok::l_square);
5828 // C array syntax has many features, but by-far the most common is [] and [4].
5829 // This code does a fast path to handle some of the most obvious cases.
5830 if (Tok.getKind() == tok::r_square) {
5832 ParsedAttributes attrs(AttrFactory);
5833 MaybeParseCXX11Attributes(attrs);
5835 // Remember that we parsed the empty array type.
5836 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
5837 T.getOpenLocation(),
5838 T.getCloseLocation()),
5839 attrs, T.getCloseLocation());
5841 } else if (Tok.getKind() == tok::numeric_constant &&
5842 GetLookAheadToken(1).is(tok::r_square)) {
5843 // [4] is very common. Parse the numeric constant expression.
5844 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
5848 ParsedAttributes attrs(AttrFactory);
5849 MaybeParseCXX11Attributes(attrs);
5851 // Remember that we parsed a array type, and remember its features.
5852 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false,
5854 T.getOpenLocation(),
5855 T.getCloseLocation()),
5856 attrs, T.getCloseLocation());
5860 // If valid, this location is the position where we read the 'static' keyword.
5861 SourceLocation StaticLoc;
5862 TryConsumeToken(tok::kw_static, StaticLoc);
5864 // If there is a type-qualifier-list, read it now.
5865 // Type qualifiers in an array subscript are a C99 feature.
5866 DeclSpec DS(AttrFactory);
5867 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
5869 // If we haven't already read 'static', check to see if there is one after the
5870 // type-qualifier-list.
5871 if (!StaticLoc.isValid())
5872 TryConsumeToken(tok::kw_static, StaticLoc);
5874 // Handle "direct-declarator [ type-qual-list[opt] * ]".
5875 bool isStar = false;
5876 ExprResult NumElements;
5878 // Handle the case where we have '[*]' as the array size. However, a leading
5879 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
5880 // the token after the star is a ']'. Since stars in arrays are
5881 // infrequent, use of lookahead is not costly here.
5882 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
5883 ConsumeToken(); // Eat the '*'.
5885 if (StaticLoc.isValid()) {
5886 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
5887 StaticLoc = SourceLocation(); // Drop the static.
5890 } else if (Tok.isNot(tok::r_square)) {
5891 // Note, in C89, this production uses the constant-expr production instead
5892 // of assignment-expr. The only difference is that assignment-expr allows
5893 // things like '=' and '*='. Sema rejects these in C89 mode because they
5894 // are not i-c-e's, so we don't need to distinguish between the two here.
5896 // Parse the constant-expression or assignment-expression now (depending
5898 if (getLangOpts().CPlusPlus) {
5899 NumElements = ParseConstantExpression();
5901 EnterExpressionEvaluationContext Unevaluated(Actions,
5902 Sema::ConstantEvaluated);
5904 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
5907 if (StaticLoc.isValid()) {
5908 Diag(StaticLoc, diag::err_unspecified_size_with_static);
5909 StaticLoc = SourceLocation(); // Drop the static.
5913 // If there was an error parsing the assignment-expression, recover.
5914 if (NumElements.isInvalid()) {
5915 D.setInvalidType(true);
5916 // If the expression was invalid, skip it.
5917 SkipUntil(tok::r_square, StopAtSemi);
5923 ParsedAttributes attrs(AttrFactory);
5924 MaybeParseCXX11Attributes(attrs);
5926 // Remember that we parsed a array type, and remember its features.
5927 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
5928 StaticLoc.isValid(), isStar,
5930 T.getOpenLocation(),
5931 T.getCloseLocation()),
5932 attrs, T.getCloseLocation());
5935 /// Diagnose brackets before an identifier.
5936 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
5937 assert(Tok.is(tok::l_square) && "Missing opening bracket");
5938 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
5940 SourceLocation StartBracketLoc = Tok.getLocation();
5941 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
5943 while (Tok.is(tok::l_square)) {
5944 ParseBracketDeclarator(TempDeclarator);
5947 // Stuff the location of the start of the brackets into the Declarator.
5948 // The diagnostics from ParseDirectDeclarator will make more sense if
5949 // they use this location instead.
5950 if (Tok.is(tok::semi))
5951 D.getName().EndLocation = StartBracketLoc;
5953 SourceLocation SuggestParenLoc = Tok.getLocation();
5955 // Now that the brackets are removed, try parsing the declarator again.
5956 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5958 // Something went wrong parsing the brackets, in which case,
5959 // ParseBracketDeclarator has emitted an error, and we don't need to emit
5961 if (TempDeclarator.getNumTypeObjects() == 0)
5964 // Determine if parens will need to be suggested in the diagnostic.
5965 bool NeedParens = false;
5966 if (D.getNumTypeObjects() != 0) {
5967 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
5968 case DeclaratorChunk::Pointer:
5969 case DeclaratorChunk::Reference:
5970 case DeclaratorChunk::BlockPointer:
5971 case DeclaratorChunk::MemberPointer:
5974 case DeclaratorChunk::Array:
5975 case DeclaratorChunk::Function:
5976 case DeclaratorChunk::Paren:
5982 // Create a DeclaratorChunk for the inserted parens.
5983 ParsedAttributes attrs(AttrFactory);
5984 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
5985 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), attrs,
5989 // Adding back the bracket info to the end of the Declarator.
5990 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
5991 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
5992 ParsedAttributes attrs(AttrFactory);
5993 attrs.set(Chunk.Common.AttrList);
5994 D.AddTypeInfo(Chunk, attrs, SourceLocation());
5997 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
5998 // If parentheses are required, always suggest them.
5999 if (!D.getIdentifier() && !NeedParens)
6002 SourceLocation EndBracketLoc = TempDeclarator.getLocEnd();
6004 // Generate the move bracket error message.
6005 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
6006 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6009 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6010 << getLangOpts().CPlusPlus
6011 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6012 << FixItHint::CreateInsertion(EndLoc, ")")
6013 << FixItHint::CreateInsertionFromRange(
6014 EndLoc, CharSourceRange(BracketRange, true))
6015 << FixItHint::CreateRemoval(BracketRange);
6017 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6018 << getLangOpts().CPlusPlus
6019 << FixItHint::CreateInsertionFromRange(
6020 EndLoc, CharSourceRange(BracketRange, true))
6021 << FixItHint::CreateRemoval(BracketRange);
6025 /// [GNU] typeof-specifier:
6026 /// typeof ( expressions )
6027 /// typeof ( type-name )
6028 /// [GNU/C++] typeof unary-expression
6030 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
6031 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
6033 SourceLocation StartLoc = ConsumeToken();
6035 const bool hasParens = Tok.is(tok::l_paren);
6037 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
6038 Sema::ReuseLambdaContextDecl);
6042 SourceRange CastRange;
6043 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6044 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
6046 DS.setTypeofParensRange(CastRange);
6048 if (CastRange.getEnd().isInvalid())
6049 // FIXME: Not accurate, the range gets one token more than it should.
6050 DS.SetRangeEnd(Tok.getLocation());
6052 DS.SetRangeEnd(CastRange.getEnd());
6056 DS.SetTypeSpecError();
6060 const char *PrevSpec = nullptr;
6062 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6063 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
6065 Actions.getASTContext().getPrintingPolicy()))
6066 Diag(StartLoc, DiagID) << PrevSpec;
6070 // If we get here, the operand to the typeof was an expresion.
6071 if (Operand.isInvalid()) {
6072 DS.SetTypeSpecError();
6076 // We might need to transform the operand if it is potentially evaluated.
6077 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6078 if (Operand.isInvalid()) {
6079 DS.SetTypeSpecError();
6083 const char *PrevSpec = nullptr;
6085 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6086 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
6087 DiagID, Operand.get(),
6088 Actions.getASTContext().getPrintingPolicy()))
6089 Diag(StartLoc, DiagID) << PrevSpec;
6092 /// [C11] atomic-specifier:
6093 /// _Atomic ( type-name )
6095 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
6096 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6097 "Not an atomic specifier");
6099 SourceLocation StartLoc = ConsumeToken();
6100 BalancedDelimiterTracker T(*this, tok::l_paren);
6101 if (T.consumeOpen())
6104 TypeResult Result = ParseTypeName();
6105 if (Result.isInvalid()) {
6106 SkipUntil(tok::r_paren, StopAtSemi);
6113 if (T.getCloseLocation().isInvalid())
6116 DS.setTypeofParensRange(T.getRange());
6117 DS.SetRangeEnd(T.getCloseLocation());
6119 const char *PrevSpec = nullptr;
6121 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
6122 DiagID, Result.get(),
6123 Actions.getASTContext().getPrintingPolicy()))
6124 Diag(StartLoc, DiagID) << PrevSpec;
6128 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6129 /// from TryAltiVecVectorToken.
6130 bool Parser::TryAltiVecVectorTokenOutOfLine() {
6131 Token Next = NextToken();
6132 switch (Next.getKind()) {
6133 default: return false;
6136 case tok::kw_signed:
6137 case tok::kw_unsigned:
6142 case tok::kw_double:
6144 case tok::kw___bool:
6145 case tok::kw___pixel:
6146 Tok.setKind(tok::kw___vector);
6148 case tok::identifier:
6149 if (Next.getIdentifierInfo() == Ident_pixel) {
6150 Tok.setKind(tok::kw___vector);
6153 if (Next.getIdentifierInfo() == Ident_bool) {
6154 Tok.setKind(tok::kw___vector);
6161 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6162 const char *&PrevSpec, unsigned &DiagID,
6164 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
6165 if (Tok.getIdentifierInfo() == Ident_vector) {
6166 Token Next = NextToken();
6167 switch (Next.getKind()) {
6170 case tok::kw_signed:
6171 case tok::kw_unsigned:
6176 case tok::kw_double:
6178 case tok::kw___bool:
6179 case tok::kw___pixel:
6180 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
6182 case tok::identifier:
6183 if (Next.getIdentifierInfo() == Ident_pixel) {
6184 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6187 if (Next.getIdentifierInfo() == Ident_bool) {
6188 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6195 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
6196 DS.isTypeAltiVecVector()) {
6197 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
6199 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
6200 DS.isTypeAltiVecVector()) {
6201 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);