1 //===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Declaration portions of the Parser interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "clang/Parse/RAIIObjectsForParser.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/Basic/AddressSpaces.h"
19 #include "clang/Basic/Attributes.h"
20 #include "clang/Basic/CharInfo.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Parse/ParseDiagnostic.h"
23 #include "clang/Sema/Lookup.h"
24 #include "clang/Sema/ParsedTemplate.h"
25 #include "clang/Sema/PrettyDeclStackTrace.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/SemaDiagnostic.h"
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/Support/ScopedPrinter.h"
34 using namespace clang;
36 //===----------------------------------------------------------------------===//
37 // C99 6.7: Declarations.
38 //===----------------------------------------------------------------------===//
41 /// type-name: [C99 6.7.6]
42 /// specifier-qualifier-list abstract-declarator[opt]
44 /// Called type-id in C++.
45 TypeResult Parser::ParseTypeName(SourceRange *Range,
46 Declarator::TheContext Context,
49 ParsedAttributes *Attrs) {
50 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
51 if (DSC == DSC_normal)
52 DSC = DSC_type_specifier;
54 // Parse the common declaration-specifiers piece.
55 DeclSpec DS(AttrFactory);
57 DS.addAttributes(Attrs->getList());
58 ParseSpecifierQualifierList(DS, AS, DSC);
60 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
62 // Parse the abstract-declarator, if present.
63 Declarator DeclaratorInfo(DS, Context);
64 ParseDeclarator(DeclaratorInfo);
66 *Range = DeclaratorInfo.getSourceRange();
68 if (DeclaratorInfo.isInvalidType())
71 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
74 /// isAttributeLateParsed - Return true if the attribute has arguments that
75 /// require late parsing.
76 static bool isAttributeLateParsed(const IdentifierInfo &II) {
77 #define CLANG_ATTR_LATE_PARSED_LIST
78 return llvm::StringSwitch<bool>(II.getName())
79 #include "clang/Parse/AttrParserStringSwitches.inc"
81 #undef CLANG_ATTR_LATE_PARSED_LIST
84 /// ParseGNUAttributes - Parse a non-empty attributes list.
88 /// attributes attribute
91 /// '__attribute__' '(' '(' attribute-list ')' ')'
93 /// [GNU] attribute-list:
95 /// attribute_list ',' attrib
100 /// attrib-name '(' identifier ')'
101 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
102 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
104 /// [GNU] attrib-name:
110 /// Whether an attribute takes an 'identifier' is determined by the
111 /// attrib-name. GCC's behavior here is not worth imitating:
113 /// * In C mode, if the attribute argument list starts with an identifier
114 /// followed by a ',' or an ')', and the identifier doesn't resolve to
115 /// a type, it is parsed as an identifier. If the attribute actually
116 /// wanted an expression, it's out of luck (but it turns out that no
117 /// attributes work that way, because C constant expressions are very
119 /// * In C++ mode, if the attribute argument list starts with an identifier,
120 /// and the attribute *wants* an identifier, it is parsed as an identifier.
121 /// At block scope, any additional tokens between the identifier and the
122 /// ',' or ')' are ignored, otherwise they produce a parse error.
124 /// We follow the C++ model, but don't allow junk after the identifier.
125 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
126 SourceLocation *endLoc,
127 LateParsedAttrList *LateAttrs,
129 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
131 while (Tok.is(tok::kw___attribute)) {
133 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
135 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
138 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
139 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
142 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
144 // Allow empty/non-empty attributes. ((__vector_size__(16),,,,))
145 if (TryConsumeToken(tok::comma))
148 // Expect an identifier or declaration specifier (const, int, etc.)
149 if (Tok.isAnnotation())
151 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
155 SourceLocation AttrNameLoc = ConsumeToken();
157 if (Tok.isNot(tok::l_paren)) {
158 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
159 AttributeList::AS_GNU);
163 // Handle "parameterized" attributes
164 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
165 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
166 SourceLocation(), AttributeList::AS_GNU, D);
170 // Handle attributes with arguments that require late parsing.
171 LateParsedAttribute *LA =
172 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
173 LateAttrs->push_back(LA);
175 // Attributes in a class are parsed at the end of the class, along
176 // with other late-parsed declarations.
177 if (!ClassStack.empty() && !LateAttrs->parseSoon())
178 getCurrentClass().LateParsedDeclarations.push_back(LA);
180 // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
181 // recursively consumes balanced parens.
182 LA->Toks.push_back(Tok);
184 // Consume everything up to and including the matching right parens.
185 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
189 Eof.setLocation(Tok.getLocation());
190 LA->Toks.push_back(Eof);
193 if (ExpectAndConsume(tok::r_paren))
194 SkipUntil(tok::r_paren, StopAtSemi);
195 SourceLocation Loc = Tok.getLocation();
196 if (ExpectAndConsume(tok::r_paren))
197 SkipUntil(tok::r_paren, StopAtSemi);
203 /// \brief Normalizes an attribute name by dropping prefixed and suffixed __.
204 static StringRef normalizeAttrName(StringRef Name) {
205 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
206 Name = Name.drop_front(2).drop_back(2);
210 /// \brief Determine whether the given attribute has an identifier argument.
211 static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
212 #define CLANG_ATTR_IDENTIFIER_ARG_LIST
213 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
214 #include "clang/Parse/AttrParserStringSwitches.inc"
216 #undef CLANG_ATTR_IDENTIFIER_ARG_LIST
219 /// \brief Determine whether the given attribute parses a type argument.
220 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
221 #define CLANG_ATTR_TYPE_ARG_LIST
222 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
223 #include "clang/Parse/AttrParserStringSwitches.inc"
225 #undef CLANG_ATTR_TYPE_ARG_LIST
228 /// \brief Determine whether the given attribute requires parsing its arguments
229 /// in an unevaluated context or not.
230 static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
231 #define CLANG_ATTR_ARG_CONTEXT_LIST
232 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
233 #include "clang/Parse/AttrParserStringSwitches.inc"
235 #undef CLANG_ATTR_ARG_CONTEXT_LIST
238 IdentifierLoc *Parser::ParseIdentifierLoc() {
239 assert(Tok.is(tok::identifier) && "expected an identifier");
240 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
242 Tok.getIdentifierInfo());
247 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
248 SourceLocation AttrNameLoc,
249 ParsedAttributes &Attrs,
250 SourceLocation *EndLoc,
251 IdentifierInfo *ScopeName,
252 SourceLocation ScopeLoc,
253 AttributeList::Syntax Syntax) {
254 BalancedDelimiterTracker Parens(*this, tok::l_paren);
255 Parens.consumeOpen();
258 if (Tok.isNot(tok::r_paren))
261 if (Parens.consumeClose())
268 Attrs.addNewTypeAttr(&AttrName,
269 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
270 ScopeName, ScopeLoc, T.get(), Syntax);
272 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
273 ScopeName, ScopeLoc, nullptr, 0, Syntax);
276 unsigned Parser::ParseAttributeArgsCommon(
277 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
278 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
279 SourceLocation ScopeLoc, AttributeList::Syntax Syntax) {
280 // Ignore the left paren location for now.
284 if (Tok.is(tok::identifier)) {
285 // If this attribute wants an 'identifier' argument, make it so.
286 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName);
287 AttributeList::Kind AttrKind =
288 AttributeList::getKind(AttrName, ScopeName, Syntax);
290 // If we don't know how to parse this attribute, but this is the only
291 // token in this argument, assume it's meant to be an identifier.
292 if (AttrKind == AttributeList::UnknownAttribute ||
293 AttrKind == AttributeList::IgnoredAttribute) {
294 const Token &Next = NextToken();
295 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
299 ArgExprs.push_back(ParseIdentifierLoc());
302 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
304 if (!ArgExprs.empty())
307 // Parse the non-empty comma-separated list of expressions.
309 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
310 EnterExpressionEvaluationContext Unevaluated(
312 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
313 : Sema::ExpressionEvaluationContext::ConstantEvaluated,
314 /*LambdaContextDecl=*/nullptr,
315 /*IsDecltype=*/false);
318 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
319 if (ArgExpr.isInvalid()) {
320 SkipUntil(tok::r_paren, StopAtSemi);
323 ArgExprs.push_back(ArgExpr.get());
324 // Eat the comma, move to the next argument
325 } while (TryConsumeToken(tok::comma));
328 SourceLocation RParen = Tok.getLocation();
329 if (!ExpectAndConsume(tok::r_paren)) {
330 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
331 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
332 ArgExprs.data(), ArgExprs.size(), Syntax);
338 return static_cast<unsigned>(ArgExprs.size());
341 /// Parse the arguments to a parameterized GNU attribute or
342 /// a C++11 attribute in "gnu" namespace.
343 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
344 SourceLocation AttrNameLoc,
345 ParsedAttributes &Attrs,
346 SourceLocation *EndLoc,
347 IdentifierInfo *ScopeName,
348 SourceLocation ScopeLoc,
349 AttributeList::Syntax Syntax,
352 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
354 AttributeList::Kind AttrKind =
355 AttributeList::getKind(AttrName, ScopeName, Syntax);
357 if (AttrKind == AttributeList::AT_Availability) {
358 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
361 } else if (AttrKind == AttributeList::AT_ExternalSourceSymbol) {
362 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
363 ScopeName, ScopeLoc, Syntax);
365 } else if (AttrKind == AttributeList::AT_ObjCBridgeRelated) {
366 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
367 ScopeName, ScopeLoc, Syntax);
369 } else if (AttrKind == AttributeList::AT_TypeTagForDatatype) {
370 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
371 ScopeName, ScopeLoc, Syntax);
373 } else if (attributeIsTypeArgAttr(*AttrName)) {
374 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
379 // These may refer to the function arguments, but need to be parsed early to
380 // participate in determining whether it's a redeclaration.
381 llvm::Optional<ParseScope> PrototypeScope;
382 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
383 D && D->isFunctionDeclarator()) {
384 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
385 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
386 Scope::FunctionDeclarationScope |
388 for (unsigned i = 0; i != FTI.NumParams; ++i) {
389 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
390 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
394 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
398 unsigned Parser::ParseClangAttributeArgs(
399 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
400 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
401 SourceLocation ScopeLoc, AttributeList::Syntax Syntax) {
402 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
404 AttributeList::Kind AttrKind =
405 AttributeList::getKind(AttrName, ScopeName, Syntax);
407 if (AttrKind == AttributeList::AT_ExternalSourceSymbol) {
408 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
409 ScopeName, ScopeLoc, Syntax);
410 return Attrs.getList() ? Attrs.getList()->getNumArgs() : 0;
413 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
414 ScopeName, ScopeLoc, Syntax);
417 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
418 SourceLocation AttrNameLoc,
419 ParsedAttributes &Attrs) {
420 // If the attribute isn't known, we will not attempt to parse any
422 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
423 getTargetInfo(), getLangOpts())) {
424 // Eat the left paren, then skip to the ending right paren.
426 SkipUntil(tok::r_paren);
430 SourceLocation OpenParenLoc = Tok.getLocation();
432 if (AttrName->getName() == "property") {
433 // The property declspec is more complex in that it can take one or two
434 // assignment expressions as a parameter, but the lhs of the assignment
435 // must be named get or put.
437 BalancedDelimiterTracker T(*this, tok::l_paren);
438 T.expectAndConsume(diag::err_expected_lparen_after,
439 AttrName->getNameStart(), tok::r_paren);
444 AK_Get = 1 // indices into AccessorNames
446 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
447 bool HasInvalidAccessor = false;
449 // Parse the accessor specifications.
451 // Stop if this doesn't look like an accessor spec.
452 if (!Tok.is(tok::identifier)) {
453 // If the user wrote a completely empty list, use a special diagnostic.
454 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
455 AccessorNames[AK_Put] == nullptr &&
456 AccessorNames[AK_Get] == nullptr) {
457 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
461 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
466 SourceLocation KindLoc = Tok.getLocation();
467 StringRef KindStr = Tok.getIdentifierInfo()->getName();
468 if (KindStr == "get") {
470 } else if (KindStr == "put") {
473 // Recover from the common mistake of using 'set' instead of 'put'.
474 } else if (KindStr == "set") {
475 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
476 << FixItHint::CreateReplacement(KindLoc, "put");
479 // Handle the mistake of forgetting the accessor kind by skipping
481 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
482 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
484 HasInvalidAccessor = true;
485 goto next_property_accessor;
487 // Otherwise, complain about the unknown accessor kind.
489 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
490 HasInvalidAccessor = true;
493 // Try to keep parsing unless it doesn't look like an accessor spec.
494 if (!NextToken().is(tok::equal))
498 // Consume the identifier.
502 if (!TryConsumeToken(tok::equal)) {
503 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
508 // Expect the method name.
509 if (!Tok.is(tok::identifier)) {
510 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
514 if (Kind == AK_Invalid) {
515 // Just drop invalid accessors.
516 } else if (AccessorNames[Kind] != nullptr) {
517 // Complain about the repeated accessor, ignore it, and keep parsing.
518 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
520 AccessorNames[Kind] = Tok.getIdentifierInfo();
524 next_property_accessor:
525 // Keep processing accessors until we run out.
526 if (TryConsumeToken(tok::comma))
529 // If we run into the ')', stop without consuming it.
530 if (Tok.is(tok::r_paren))
533 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
537 // Only add the property attribute if it was well-formed.
538 if (!HasInvalidAccessor)
539 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
540 AccessorNames[AK_Get], AccessorNames[AK_Put],
541 AttributeList::AS_Declspec);
543 return !HasInvalidAccessor;
547 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
548 SourceLocation(), AttributeList::AS_Declspec);
550 // If this attribute's args were parsed, and it was expected to have
551 // arguments but none were provided, emit a diagnostic.
552 const AttributeList *Attr = Attrs.getList();
553 if (Attr && Attr->getMaxArgs() && !NumArgs) {
554 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
560 /// [MS] decl-specifier:
561 /// __declspec ( extended-decl-modifier-seq )
563 /// [MS] extended-decl-modifier-seq:
564 /// extended-decl-modifier[opt]
565 /// extended-decl-modifier extended-decl-modifier-seq
566 void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
567 SourceLocation *End) {
568 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
569 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
571 while (Tok.is(tok::kw___declspec)) {
573 BalancedDelimiterTracker T(*this, tok::l_paren);
574 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
578 // An empty declspec is perfectly legal and should not warn. Additionally,
579 // you can specify multiple attributes per declspec.
580 while (Tok.isNot(tok::r_paren)) {
581 // Attribute not present.
582 if (TryConsumeToken(tok::comma))
585 // We expect either a well-known identifier or a generic string. Anything
586 // else is a malformed declspec.
587 bool IsString = Tok.getKind() == tok::string_literal;
588 if (!IsString && Tok.getKind() != tok::identifier &&
589 Tok.getKind() != tok::kw_restrict) {
590 Diag(Tok, diag::err_ms_declspec_type);
595 IdentifierInfo *AttrName;
596 SourceLocation AttrNameLoc;
598 SmallString<8> StrBuffer;
599 bool Invalid = false;
600 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
605 AttrName = PP.getIdentifierInfo(Str);
606 AttrNameLoc = ConsumeStringToken();
608 AttrName = Tok.getIdentifierInfo();
609 AttrNameLoc = ConsumeToken();
612 bool AttrHandled = false;
614 // Parse attribute arguments.
615 if (Tok.is(tok::l_paren))
616 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
617 else if (AttrName->getName() == "property")
618 // The property attribute must have an argument list.
619 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
620 << AttrName->getName();
623 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
624 AttributeList::AS_Declspec);
628 *End = T.getCloseLocation();
632 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
633 // Treat these like attributes
635 switch (Tok.getKind()) {
636 case tok::kw___fastcall:
637 case tok::kw___stdcall:
638 case tok::kw___thiscall:
639 case tok::kw___regcall:
640 case tok::kw___cdecl:
641 case tok::kw___vectorcall:
642 case tok::kw___ptr64:
644 case tok::kw___ptr32:
646 case tok::kw___uptr: {
647 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
648 SourceLocation AttrNameLoc = ConsumeToken();
649 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
650 AttributeList::AS_Keyword);
659 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
660 SourceLocation StartLoc = Tok.getLocation();
661 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
663 if (EndLoc.isValid()) {
664 SourceRange Range(StartLoc, EndLoc);
665 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
669 SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
670 SourceLocation EndLoc;
673 switch (Tok.getKind()) {
675 case tok::kw_volatile:
676 case tok::kw___fastcall:
677 case tok::kw___stdcall:
678 case tok::kw___thiscall:
679 case tok::kw___cdecl:
680 case tok::kw___vectorcall:
681 case tok::kw___ptr32:
682 case tok::kw___ptr64:
684 case tok::kw___unaligned:
687 EndLoc = ConsumeToken();
695 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
696 // Treat these like attributes
697 while (Tok.is(tok::kw___pascal)) {
698 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
699 SourceLocation AttrNameLoc = ConsumeToken();
700 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
701 AttributeList::AS_Keyword);
705 void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
706 // Treat these like attributes
707 while (Tok.is(tok::kw___kernel)) {
708 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
709 SourceLocation AttrNameLoc = ConsumeToken();
710 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
711 AttributeList::AS_Keyword);
715 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
716 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
717 SourceLocation AttrNameLoc = Tok.getLocation();
718 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
719 AttributeList::AS_Keyword);
722 void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
723 // Treat these like attributes, even though they're type specifiers.
725 switch (Tok.getKind()) {
726 case tok::kw__Nonnull:
727 case tok::kw__Nullable:
728 case tok::kw__Null_unspecified: {
729 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
730 SourceLocation AttrNameLoc = ConsumeToken();
731 if (!getLangOpts().ObjC1)
732 Diag(AttrNameLoc, diag::ext_nullability)
734 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
735 AttributeList::AS_Keyword);
744 static bool VersionNumberSeparator(const char Separator) {
745 return (Separator == '.' || Separator == '_');
748 /// \brief Parse a version number.
752 /// simple-integer ',' simple-integer
753 /// simple-integer ',' simple-integer ',' simple-integer
754 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
755 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
757 if (!Tok.is(tok::numeric_constant)) {
758 Diag(Tok, diag::err_expected_version);
759 SkipUntil(tok::comma, tok::r_paren,
760 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
761 return VersionTuple();
764 // Parse the major (and possibly minor and subminor) versions, which
765 // are stored in the numeric constant. We utilize a quirk of the
766 // lexer, which is that it handles something like 1.2.3 as a single
767 // numeric constant, rather than two separate tokens.
768 SmallString<512> Buffer;
769 Buffer.resize(Tok.getLength()+1);
770 const char *ThisTokBegin = &Buffer[0];
772 // Get the spelling of the token, which eliminates trigraphs, etc.
773 bool Invalid = false;
774 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
776 return VersionTuple();
778 // Parse the major version.
779 unsigned AfterMajor = 0;
781 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
782 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
786 if (AfterMajor == 0) {
787 Diag(Tok, diag::err_expected_version);
788 SkipUntil(tok::comma, tok::r_paren,
789 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
790 return VersionTuple();
793 if (AfterMajor == ActualLength) {
796 // We only had a single version component.
798 Diag(Tok, diag::err_zero_version);
799 return VersionTuple();
802 return VersionTuple(Major);
805 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
806 if (!VersionNumberSeparator(AfterMajorSeparator)
807 || (AfterMajor + 1 == ActualLength)) {
808 Diag(Tok, diag::err_expected_version);
809 SkipUntil(tok::comma, tok::r_paren,
810 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
811 return VersionTuple();
814 // Parse the minor version.
815 unsigned AfterMinor = AfterMajor + 1;
817 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
818 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
822 if (AfterMinor == ActualLength) {
825 // We had major.minor.
826 if (Major == 0 && Minor == 0) {
827 Diag(Tok, diag::err_zero_version);
828 return VersionTuple();
831 return VersionTuple(Major, Minor, (AfterMajorSeparator == '_'));
834 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
835 // If what follows is not a '.' or '_', we have a problem.
836 if (!VersionNumberSeparator(AfterMinorSeparator)) {
837 Diag(Tok, diag::err_expected_version);
838 SkipUntil(tok::comma, tok::r_paren,
839 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
840 return VersionTuple();
843 // Warn if separators, be it '.' or '_', do not match.
844 if (AfterMajorSeparator != AfterMinorSeparator)
845 Diag(Tok, diag::warn_expected_consistent_version_separator);
847 // Parse the subminor version.
848 unsigned AfterSubminor = AfterMinor + 1;
849 unsigned Subminor = 0;
850 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
851 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
855 if (AfterSubminor != ActualLength) {
856 Diag(Tok, diag::err_expected_version);
857 SkipUntil(tok::comma, tok::r_paren,
858 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
859 return VersionTuple();
862 return VersionTuple(Major, Minor, Subminor, (AfterMajorSeparator == '_'));
865 /// \brief Parse the contents of the "availability" attribute.
867 /// availability-attribute:
868 /// 'availability' '(' platform ',' opt-strict version-arg-list,
869 /// opt-replacement, opt-message')'
877 /// version-arg-list:
879 /// version-arg ',' version-arg-list
882 /// 'introduced' '=' version
883 /// 'deprecated' '=' version
884 /// 'obsoleted' = version
887 /// 'replacement' '=' <string>
889 /// 'message' '=' <string>
890 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
891 SourceLocation AvailabilityLoc,
892 ParsedAttributes &attrs,
893 SourceLocation *endLoc,
894 IdentifierInfo *ScopeName,
895 SourceLocation ScopeLoc,
896 AttributeList::Syntax Syntax) {
897 enum { Introduced, Deprecated, Obsoleted, Unknown };
898 AvailabilityChange Changes[Unknown];
899 ExprResult MessageExpr, ReplacementExpr;
902 BalancedDelimiterTracker T(*this, tok::l_paren);
903 if (T.consumeOpen()) {
904 Diag(Tok, diag::err_expected) << tok::l_paren;
908 // Parse the platform name.
909 if (Tok.isNot(tok::identifier)) {
910 Diag(Tok, diag::err_availability_expected_platform);
911 SkipUntil(tok::r_paren, StopAtSemi);
914 IdentifierLoc *Platform = ParseIdentifierLoc();
915 // Canonicalize platform name from "macosx" to "macos".
916 if (Platform->Ident && Platform->Ident->getName() == "macosx")
917 Platform->Ident = PP.getIdentifierInfo("macos");
918 // Canonicalize platform name from "macosx_app_extension" to
919 // "macos_app_extension".
920 if (Platform->Ident && Platform->Ident->getName() == "macosx_app_extension")
921 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
923 // Parse the ',' following the platform name.
924 if (ExpectAndConsume(tok::comma)) {
925 SkipUntil(tok::r_paren, StopAtSemi);
929 // If we haven't grabbed the pointers for the identifiers
930 // "introduced", "deprecated", and "obsoleted", do so now.
931 if (!Ident_introduced) {
932 Ident_introduced = PP.getIdentifierInfo("introduced");
933 Ident_deprecated = PP.getIdentifierInfo("deprecated");
934 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
935 Ident_unavailable = PP.getIdentifierInfo("unavailable");
936 Ident_message = PP.getIdentifierInfo("message");
937 Ident_strict = PP.getIdentifierInfo("strict");
938 Ident_replacement = PP.getIdentifierInfo("replacement");
941 // Parse the optional "strict", the optional "replacement" and the set of
942 // introductions/deprecations/removals.
943 SourceLocation UnavailableLoc, StrictLoc;
945 if (Tok.isNot(tok::identifier)) {
946 Diag(Tok, diag::err_availability_expected_change);
947 SkipUntil(tok::r_paren, StopAtSemi);
950 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
951 SourceLocation KeywordLoc = ConsumeToken();
953 if (Keyword == Ident_strict) {
954 if (StrictLoc.isValid()) {
955 Diag(KeywordLoc, diag::err_availability_redundant)
956 << Keyword << SourceRange(StrictLoc);
958 StrictLoc = KeywordLoc;
962 if (Keyword == Ident_unavailable) {
963 if (UnavailableLoc.isValid()) {
964 Diag(KeywordLoc, diag::err_availability_redundant)
965 << Keyword << SourceRange(UnavailableLoc);
967 UnavailableLoc = KeywordLoc;
971 if (Tok.isNot(tok::equal)) {
972 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
973 SkipUntil(tok::r_paren, StopAtSemi);
977 if (Keyword == Ident_message || Keyword == Ident_replacement) {
978 if (Tok.isNot(tok::string_literal)) {
979 Diag(Tok, diag::err_expected_string_literal)
980 << /*Source='availability attribute'*/2;
981 SkipUntil(tok::r_paren, StopAtSemi);
984 if (Keyword == Ident_message)
985 MessageExpr = ParseStringLiteralExpression();
987 ReplacementExpr = ParseStringLiteralExpression();
988 // Also reject wide string literals.
989 if (StringLiteral *MessageStringLiteral =
990 cast_or_null<StringLiteral>(MessageExpr.get())) {
991 if (MessageStringLiteral->getCharByteWidth() != 1) {
992 Diag(MessageStringLiteral->getSourceRange().getBegin(),
993 diag::err_expected_string_literal)
994 << /*Source='availability attribute'*/ 2;
995 SkipUntil(tok::r_paren, StopAtSemi);
999 if (Keyword == Ident_message)
1005 // Special handling of 'NA' only when applied to introduced or
1007 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1008 Tok.is(tok::identifier)) {
1009 IdentifierInfo *NA = Tok.getIdentifierInfo();
1010 if (NA->getName() == "NA") {
1012 if (Keyword == Ident_introduced)
1013 UnavailableLoc = KeywordLoc;
1018 SourceRange VersionRange;
1019 VersionTuple Version = ParseVersionTuple(VersionRange);
1021 if (Version.empty()) {
1022 SkipUntil(tok::r_paren, StopAtSemi);
1027 if (Keyword == Ident_introduced)
1029 else if (Keyword == Ident_deprecated)
1031 else if (Keyword == Ident_obsoleted)
1036 if (Index < Unknown) {
1037 if (!Changes[Index].KeywordLoc.isInvalid()) {
1038 Diag(KeywordLoc, diag::err_availability_redundant)
1040 << SourceRange(Changes[Index].KeywordLoc,
1041 Changes[Index].VersionRange.getEnd());
1044 Changes[Index].KeywordLoc = KeywordLoc;
1045 Changes[Index].Version = Version;
1046 Changes[Index].VersionRange = VersionRange;
1048 Diag(KeywordLoc, diag::err_availability_unknown_change)
1049 << Keyword << VersionRange;
1052 } while (TryConsumeToken(tok::comma));
1055 if (T.consumeClose())
1059 *endLoc = T.getCloseLocation();
1061 // The 'unavailable' availability cannot be combined with any other
1062 // availability changes. Make sure that hasn't happened.
1063 if (UnavailableLoc.isValid()) {
1064 bool Complained = false;
1065 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1066 if (Changes[Index].KeywordLoc.isValid()) {
1068 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1069 << SourceRange(Changes[Index].KeywordLoc,
1070 Changes[Index].VersionRange.getEnd());
1074 // Clear out the availability.
1075 Changes[Index] = AvailabilityChange();
1080 // Record this attribute
1081 attrs.addNew(&Availability,
1082 SourceRange(AvailabilityLoc, T.getCloseLocation()),
1083 ScopeName, ScopeLoc,
1085 Changes[Introduced],
1086 Changes[Deprecated],
1088 UnavailableLoc, MessageExpr.get(),
1089 Syntax, StrictLoc, ReplacementExpr.get());
1092 /// \brief Parse the contents of the "external_source_symbol" attribute.
1094 /// external-source-symbol-attribute:
1095 /// 'external_source_symbol' '(' keyword-arg-list ')'
1097 /// keyword-arg-list:
1099 /// keyword-arg ',' keyword-arg-list
1102 /// 'language' '=' <string>
1103 /// 'defined_in' '=' <string>
1104 /// 'generated_declaration'
1105 void Parser::ParseExternalSourceSymbolAttribute(
1106 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1107 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1108 SourceLocation ScopeLoc, AttributeList::Syntax Syntax) {
1110 BalancedDelimiterTracker T(*this, tok::l_paren);
1111 if (T.expectAndConsume())
1114 // Initialize the pointers for the keyword identifiers when required.
1115 if (!Ident_language) {
1116 Ident_language = PP.getIdentifierInfo("language");
1117 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1118 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1121 ExprResult Language;
1122 bool HasLanguage = false;
1123 ExprResult DefinedInExpr;
1124 bool HasDefinedIn = false;
1125 IdentifierLoc *GeneratedDeclaration = nullptr;
1127 // Parse the language/defined_in/generated_declaration keywords
1129 if (Tok.isNot(tok::identifier)) {
1130 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1131 SkipUntil(tok::r_paren, StopAtSemi);
1135 SourceLocation KeywordLoc = Tok.getLocation();
1136 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1137 if (Keyword == Ident_generated_declaration) {
1138 if (GeneratedDeclaration) {
1139 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1140 SkipUntil(tok::r_paren, StopAtSemi);
1143 GeneratedDeclaration = ParseIdentifierLoc();
1147 if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1148 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1149 SkipUntil(tok::r_paren, StopAtSemi);
1154 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1155 Keyword->getName())) {
1156 SkipUntil(tok::r_paren, StopAtSemi);
1160 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1161 if (Keyword == Ident_language)
1164 HasDefinedIn = true;
1166 if (Tok.isNot(tok::string_literal)) {
1167 Diag(Tok, diag::err_expected_string_literal)
1168 << /*Source='external_source_symbol attribute'*/ 3
1169 << /*language | source container*/ (Keyword != Ident_language);
1170 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1173 if (Keyword == Ident_language) {
1175 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1177 ParseStringLiteralExpression();
1180 Language = ParseStringLiteralExpression();
1182 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1184 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1186 ParseStringLiteralExpression();
1189 DefinedInExpr = ParseStringLiteralExpression();
1191 } while (TryConsumeToken(tok::comma));
1194 if (T.consumeClose())
1197 *EndLoc = T.getCloseLocation();
1199 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1200 GeneratedDeclaration};
1201 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1202 ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1205 /// \brief Parse the contents of the "objc_bridge_related" attribute.
1206 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1210 /// opt-class_method:
1211 /// Identifier: | <empty>
1213 /// opt-instance_method:
1214 /// Identifier | <empty>
1216 void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1217 SourceLocation ObjCBridgeRelatedLoc,
1218 ParsedAttributes &attrs,
1219 SourceLocation *endLoc,
1220 IdentifierInfo *ScopeName,
1221 SourceLocation ScopeLoc,
1222 AttributeList::Syntax Syntax) {
1224 BalancedDelimiterTracker T(*this, tok::l_paren);
1225 if (T.consumeOpen()) {
1226 Diag(Tok, diag::err_expected) << tok::l_paren;
1230 // Parse the related class name.
1231 if (Tok.isNot(tok::identifier)) {
1232 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1233 SkipUntil(tok::r_paren, StopAtSemi);
1236 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1237 if (ExpectAndConsume(tok::comma)) {
1238 SkipUntil(tok::r_paren, StopAtSemi);
1242 // Parse optional class method name.
1243 IdentifierLoc *ClassMethod = nullptr;
1244 if (Tok.is(tok::identifier)) {
1245 ClassMethod = ParseIdentifierLoc();
1246 if (!TryConsumeToken(tok::colon)) {
1247 Diag(Tok, diag::err_objcbridge_related_selector_name);
1248 SkipUntil(tok::r_paren, StopAtSemi);
1252 if (!TryConsumeToken(tok::comma)) {
1253 if (Tok.is(tok::colon))
1254 Diag(Tok, diag::err_objcbridge_related_selector_name);
1256 Diag(Tok, diag::err_expected) << tok::comma;
1257 SkipUntil(tok::r_paren, StopAtSemi);
1261 // Parse optional instance method name.
1262 IdentifierLoc *InstanceMethod = nullptr;
1263 if (Tok.is(tok::identifier))
1264 InstanceMethod = ParseIdentifierLoc();
1265 else if (Tok.isNot(tok::r_paren)) {
1266 Diag(Tok, diag::err_expected) << tok::r_paren;
1267 SkipUntil(tok::r_paren, StopAtSemi);
1272 if (T.consumeClose())
1276 *endLoc = T.getCloseLocation();
1278 // Record this attribute
1279 attrs.addNew(&ObjCBridgeRelated,
1280 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1281 ScopeName, ScopeLoc,
1288 // Late Parsed Attributes:
1289 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1291 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1293 void Parser::LateParsedClass::ParseLexedAttributes() {
1294 Self->ParseLexedAttributes(*Class);
1297 void Parser::LateParsedAttribute::ParseLexedAttributes() {
1298 Self->ParseLexedAttribute(*this, true, false);
1301 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1302 /// scope appropriately.
1303 void Parser::ParseLexedAttributes(ParsingClass &Class) {
1304 // Deal with templates
1305 // FIXME: Test cases to make sure this does the right thing for templates.
1306 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1307 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1309 if (HasTemplateScope)
1310 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1312 // Set or update the scope flags.
1313 bool AlreadyHasClassScope = Class.TopLevelClass;
1314 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
1315 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1316 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1318 // Enter the scope of nested classes
1319 if (!AlreadyHasClassScope)
1320 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1321 Class.TagOrTemplate);
1322 if (!Class.LateParsedDeclarations.empty()) {
1323 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1324 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1328 if (!AlreadyHasClassScope)
1329 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1330 Class.TagOrTemplate);
1333 /// \brief Parse all attributes in LAs, and attach them to Decl D.
1334 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1335 bool EnterScope, bool OnDefinition) {
1336 assert(LAs.parseSoon() &&
1337 "Attribute list should be marked for immediate parsing.");
1338 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1341 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1347 /// \brief Finish parsing an attribute for which parsing was delayed.
1348 /// This will be called at the end of parsing a class declaration
1349 /// for each LateParsedAttribute. We consume the saved tokens and
1350 /// create an attribute with the arguments filled in. We add this
1351 /// to the Attribute list for the decl.
1352 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1353 bool EnterScope, bool OnDefinition) {
1354 // Create a fake EOF so that attribute parsing won't go off the end of the
1357 AttrEnd.startToken();
1358 AttrEnd.setKind(tok::eof);
1359 AttrEnd.setLocation(Tok.getLocation());
1360 AttrEnd.setEofData(LA.Toks.data());
1361 LA.Toks.push_back(AttrEnd);
1363 // Append the current token at the end of the new token stream so that it
1364 // doesn't get lost.
1365 LA.Toks.push_back(Tok);
1366 PP.EnterTokenStream(LA.Toks, true);
1367 // Consume the previously pushed token.
1368 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1370 ParsedAttributes Attrs(AttrFactory);
1371 SourceLocation endLoc;
1373 if (LA.Decls.size() > 0) {
1374 Decl *D = LA.Decls[0];
1375 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1376 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1378 // Allow 'this' within late-parsed attributes.
1379 Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0,
1380 ND && ND->isCXXInstanceMember());
1382 if (LA.Decls.size() == 1) {
1383 // If the Decl is templatized, add template parameters to scope.
1384 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1385 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1386 if (HasTemplateScope)
1387 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1389 // If the Decl is on a function, add function parameters to the scope.
1390 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1391 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunScope);
1393 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1395 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1396 nullptr, SourceLocation(), AttributeList::AS_GNU,
1400 Actions.ActOnExitFunctionContext();
1401 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1403 if (HasTemplateScope) {
1407 // If there are multiple decls, then the decl cannot be within the
1409 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1410 nullptr, SourceLocation(), AttributeList::AS_GNU,
1414 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1417 const AttributeList *AL = Attrs.getList();
1418 if (OnDefinition && AL && !AL->isCXX11Attribute() &&
1420 Diag(Tok, diag::warn_attribute_on_function_definition)
1423 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
1424 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1426 // Due to a parsing error, we either went over the cached tokens or
1427 // there are still cached tokens left, so we skip the leftover tokens.
1428 while (Tok.isNot(tok::eof))
1431 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1435 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1436 SourceLocation AttrNameLoc,
1437 ParsedAttributes &Attrs,
1438 SourceLocation *EndLoc,
1439 IdentifierInfo *ScopeName,
1440 SourceLocation ScopeLoc,
1441 AttributeList::Syntax Syntax) {
1442 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1444 BalancedDelimiterTracker T(*this, tok::l_paren);
1447 if (Tok.isNot(tok::identifier)) {
1448 Diag(Tok, diag::err_expected) << tok::identifier;
1452 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1454 if (ExpectAndConsume(tok::comma)) {
1459 SourceRange MatchingCTypeRange;
1460 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1461 if (MatchingCType.isInvalid()) {
1466 bool LayoutCompatible = false;
1467 bool MustBeNull = false;
1468 while (TryConsumeToken(tok::comma)) {
1469 if (Tok.isNot(tok::identifier)) {
1470 Diag(Tok, diag::err_expected) << tok::identifier;
1474 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1475 if (Flag->isStr("layout_compatible"))
1476 LayoutCompatible = true;
1477 else if (Flag->isStr("must_be_null"))
1480 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1484 ConsumeToken(); // consume flag
1487 if (!T.consumeClose()) {
1488 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1489 ArgumentKind, MatchingCType.get(),
1490 LayoutCompatible, MustBeNull, Syntax);
1494 *EndLoc = T.getCloseLocation();
1497 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1498 /// of a C++11 attribute-specifier in a location where an attribute is not
1499 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1502 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1503 /// this doesn't appear to actually be an attribute-specifier, and the caller
1504 /// should try to parse it.
1505 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1506 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1508 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1509 case CAK_NotAttributeSpecifier:
1510 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1513 case CAK_InvalidAttributeSpecifier:
1514 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1517 case CAK_AttributeSpecifier:
1518 // Parse and discard the attributes.
1519 SourceLocation BeginLoc = ConsumeBracket();
1521 SkipUntil(tok::r_square);
1522 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1523 SourceLocation EndLoc = ConsumeBracket();
1524 Diag(BeginLoc, diag::err_attributes_not_allowed)
1525 << SourceRange(BeginLoc, EndLoc);
1528 llvm_unreachable("All cases handled above.");
1531 /// \brief We have found the opening square brackets of a C++11
1532 /// attribute-specifier in a location where an attribute is not permitted, but
1533 /// we know where the attributes ought to be written. Parse them anyway, and
1534 /// provide a fixit moving them to the right place.
1535 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1536 SourceLocation CorrectLocation) {
1537 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1538 Tok.is(tok::kw_alignas));
1540 // Consume the attributes.
1541 SourceLocation Loc = Tok.getLocation();
1542 ParseCXX11Attributes(Attrs);
1543 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1545 Diag(Loc, diag::err_attributes_not_allowed)
1546 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1547 << FixItHint::CreateRemoval(AttrRange);
1550 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
1551 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
1555 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1557 for (AttributeList *Attr = Attrs.getList(); Attr; Attr = Attr->getNext()) {
1558 if (!Attr->isCXX11Attribute())
1560 if (Attr->getKind() == AttributeList::UnknownAttribute)
1561 Diag(Attr->getLoc(), diag::warn_unknown_attribute_ignored)
1564 Diag(Attr->getLoc(), DiagID)
1571 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1572 // applies to var, not the type Foo.
1573 // As an exception to the rule, __declspec(align(...)) before the
1574 // class-key affects the type instead of the variable.
1575 // Also, Microsoft-style [attributes] seem to affect the type instead of the
1577 // This function moves attributes that should apply to the type off DS to Attrs.
1578 void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1580 Sema::TagUseKind TUK) {
1581 if (TUK == Sema::TUK_Reference)
1584 ParsedAttributes &PA = DS.getAttributes();
1585 AttributeList *AL = PA.getList();
1586 AttributeList *Prev = nullptr;
1587 AttributeList *TypeAttrHead = nullptr;
1588 AttributeList *TypeAttrTail = nullptr;
1590 AttributeList *Next = AL->getNext();
1592 if ((AL->getKind() == AttributeList::AT_Aligned &&
1593 AL->isDeclspecAttribute()) ||
1594 AL->isMicrosoftAttribute()) {
1595 // Stitch the attribute into the tag's attribute list.
1597 TypeAttrTail->setNext(AL);
1601 TypeAttrTail->setNext(nullptr);
1603 // Remove the attribute from the variable's attribute list.
1605 // Set the last variable attribute's next attribute to be the attribute
1606 // after the current one.
1607 Prev->setNext(Next);
1609 // Removing the head of the list requires us to reset the head to the
1620 // Find end of type attributes Attrs and add NewTypeAttributes in the same
1621 // order they were in originally. (Remember, in AttributeList things earlier
1622 // in source order are later in the list, since new attributes are added to
1623 // the front of the list.)
1624 Attrs.addAllAtEnd(TypeAttrHead);
1627 /// ParseDeclaration - Parse a full 'declaration', which consists of
1628 /// declaration-specifiers, some number of declarators, and a semicolon.
1629 /// 'Context' should be a Declarator::TheContext value. This returns the
1630 /// location of the semicolon in DeclEnd.
1632 /// declaration: [C99 6.7]
1633 /// block-declaration ->
1634 /// simple-declaration
1636 /// [C++] template-declaration
1637 /// [C++] namespace-definition
1638 /// [C++] using-directive
1639 /// [C++] using-declaration
1640 /// [C++11/C11] static_assert-declaration
1641 /// others... [FIXME]
1643 Parser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context,
1644 SourceLocation &DeclEnd,
1645 ParsedAttributesWithRange &attrs) {
1646 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1647 // Must temporarily exit the objective-c container scope for
1648 // parsing c none objective-c decls.
1649 ObjCDeclContextSwitch ObjCDC(*this);
1651 Decl *SingleDecl = nullptr;
1652 switch (Tok.getKind()) {
1653 case tok::kw_template:
1654 case tok::kw_export:
1655 ProhibitAttributes(attrs);
1656 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
1658 case tok::kw_inline:
1659 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1660 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1661 ProhibitAttributes(attrs);
1662 SourceLocation InlineLoc = ConsumeToken();
1663 return ParseNamespace(Context, DeclEnd, InlineLoc);
1665 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
1667 case tok::kw_namespace:
1668 ProhibitAttributes(attrs);
1669 return ParseNamespace(Context, DeclEnd);
1671 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1673 case tok::kw_static_assert:
1674 case tok::kw__Static_assert:
1675 ProhibitAttributes(attrs);
1676 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1679 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
1682 // This routine returns a DeclGroup, if the thing we parsed only contains a
1683 // single decl, convert it now.
1684 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1687 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1688 /// declaration-specifiers init-declarator-list[opt] ';'
1689 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1690 /// init-declarator-list ';'
1691 ///[C90/C++]init-declarator-list ';' [TODO]
1692 /// [OMP] threadprivate-directive [TODO]
1694 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1695 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1697 /// If RequireSemi is false, this does not check for a ';' at the end of the
1698 /// declaration. If it is true, it checks for and eats it.
1700 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1701 /// of a simple-declaration. If we find that we are, we also parse the
1702 /// for-range-initializer, and place it here.
1703 Parser::DeclGroupPtrTy
1704 Parser::ParseSimpleDeclaration(unsigned Context,
1705 SourceLocation &DeclEnd,
1706 ParsedAttributesWithRange &Attrs,
1707 bool RequireSemi, ForRangeInit *FRI) {
1708 // Parse the common declaration-specifiers piece.
1709 ParsingDeclSpec DS(*this);
1711 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1712 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1714 // If we had a free-standing type definition with a missing semicolon, we
1715 // may get this far before the problem becomes obvious.
1716 if (DS.hasTagDefinition() &&
1717 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1720 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1721 // declaration-specifiers init-declarator-list[opt] ';'
1722 if (Tok.is(tok::semi)) {
1723 ProhibitAttributes(Attrs);
1724 DeclEnd = Tok.getLocation();
1725 if (RequireSemi) ConsumeToken();
1726 RecordDecl *AnonRecord = nullptr;
1727 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1729 DS.complete(TheDecl);
1731 Decl* decls[] = {AnonRecord, TheDecl};
1732 return Actions.BuildDeclaratorGroup(decls);
1734 return Actions.ConvertDeclToDeclGroup(TheDecl);
1737 DS.takeAttributesFrom(Attrs);
1738 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1741 /// Returns true if this might be the start of a declarator, or a common typo
1742 /// for a declarator.
1743 bool Parser::MightBeDeclarator(unsigned Context) {
1744 switch (Tok.getKind()) {
1745 case tok::annot_cxxscope:
1746 case tok::annot_template_id:
1748 case tok::code_completion:
1749 case tok::coloncolon:
1751 case tok::kw___attribute:
1752 case tok::kw_operator:
1759 return getLangOpts().CPlusPlus;
1761 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1762 return Context == Declarator::MemberContext && getLangOpts().CPlusPlus11 &&
1763 NextToken().is(tok::l_square);
1765 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1766 return Context == Declarator::MemberContext || getLangOpts().CPlusPlus;
1768 case tok::identifier:
1769 switch (NextToken().getKind()) {
1770 case tok::code_completion:
1771 case tok::coloncolon:
1774 case tok::equalequal: // Might be a typo for '='.
1775 case tok::kw_alignas:
1777 case tok::kw___attribute:
1789 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1790 // and in block scope it's probably a label. Inside a class definition,
1791 // this is a bit-field.
1792 return Context == Declarator::MemberContext ||
1793 (getLangOpts().CPlusPlus && Context == Declarator::FileContext);
1795 case tok::identifier: // Possible virt-specifier.
1796 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1807 /// Skip until we reach something which seems like a sensible place to pick
1808 /// up parsing after a malformed declaration. This will sometimes stop sooner
1809 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1810 void Parser::SkipMalformedDecl() {
1812 switch (Tok.getKind()) {
1814 // Skip until matching }, then stop. We've probably skipped over
1815 // a malformed class or function definition or similar.
1817 SkipUntil(tok::r_brace);
1818 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1819 // This declaration isn't over yet. Keep skipping.
1822 TryConsumeToken(tok::semi);
1827 SkipUntil(tok::r_square);
1832 SkipUntil(tok::r_paren);
1842 case tok::kw_inline:
1843 // 'inline namespace' at the start of a line is almost certainly
1844 // a good place to pick back up parsing, except in an Objective-C
1845 // @interface context.
1846 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1847 (!ParsingInObjCContainer || CurParsedObjCImpl))
1851 case tok::kw_namespace:
1852 // 'namespace' at the start of a line is almost certainly a good
1853 // place to pick back up parsing, except in an Objective-C
1854 // @interface context.
1855 if (Tok.isAtStartOfLine() &&
1856 (!ParsingInObjCContainer || CurParsedObjCImpl))
1861 // @end is very much like } in Objective-C contexts.
1862 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1863 ParsingInObjCContainer)
1869 // - and + probably start new method declarations in Objective-C contexts.
1870 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1875 case tok::annot_module_begin:
1876 case tok::annot_module_end:
1877 case tok::annot_module_include:
1888 /// ParseDeclGroup - Having concluded that this is either a function
1889 /// definition or a group of object declarations, actually parse the
1891 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1893 SourceLocation *DeclEnd,
1894 ForRangeInit *FRI) {
1895 // Parse the first declarator.
1896 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
1899 // Bail out if the first declarator didn't seem well-formed.
1900 if (!D.hasName() && !D.mayOmitIdentifier()) {
1901 SkipMalformedDecl();
1905 // Save late-parsed attributes for now; they need to be parsed in the
1906 // appropriate function scope after the function Decl has been constructed.
1907 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1908 LateParsedAttrList LateParsedAttrs(true);
1909 if (D.isFunctionDeclarator()) {
1910 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1912 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1913 // attribute. If we find the keyword here, tell the user to put it
1914 // at the start instead.
1915 if (Tok.is(tok::kw__Noreturn)) {
1916 SourceLocation Loc = ConsumeToken();
1917 const char *PrevSpec;
1920 // We can offer a fixit if it's valid to mark this function as _Noreturn
1921 // and we don't have any other declarators in this declaration.
1922 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1923 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1924 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
1926 Diag(Loc, diag::err_c11_noreturn_misplaced)
1927 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
1928 << (Fixit ? FixItHint::CreateInsertion(D.getLocStart(), "_Noreturn ")
1933 // Check to see if we have a function *definition* which must have a body.
1934 if (D.isFunctionDeclarator() &&
1935 // Look at the next token to make sure that this isn't a function
1936 // declaration. We have to check this because __attribute__ might be the
1937 // start of a function definition in GCC-extended K&R C.
1938 !isDeclarationAfterDeclarator()) {
1940 // Function definitions are only allowed at file scope and in C++ classes.
1941 // The C++ inline method definition case is handled elsewhere, so we only
1942 // need to handle the file scope definition case.
1943 if (Context == Declarator::FileContext) {
1944 if (isStartOfFunctionDefinition(D)) {
1945 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1946 Diag(Tok, diag::err_function_declared_typedef);
1948 // Recover by treating the 'typedef' as spurious.
1949 DS.ClearStorageClassSpecs();
1953 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1954 return Actions.ConvertDeclToDeclGroup(TheDecl);
1957 if (isDeclarationSpecifier()) {
1958 // If there is an invalid declaration specifier right after the
1959 // function prototype, then we must be in a missing semicolon case
1960 // where this isn't actually a body. Just fall through into the code
1961 // that handles it as a prototype, and let the top-level code handle
1962 // the erroneous declspec where it would otherwise expect a comma or
1965 Diag(Tok, diag::err_expected_fn_body);
1966 SkipUntil(tok::semi);
1970 if (Tok.is(tok::l_brace)) {
1971 Diag(Tok, diag::err_function_definition_not_allowed);
1972 SkipMalformedDecl();
1978 if (ParseAsmAttributesAfterDeclarator(D))
1981 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1982 // must parse and analyze the for-range-initializer before the declaration is
1985 // Handle the Objective-C for-in loop variable similarly, although we
1986 // don't need to parse the container in advance.
1987 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
1988 bool IsForRangeLoop = false;
1989 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
1990 IsForRangeLoop = true;
1991 if (Tok.is(tok::l_brace))
1992 FRI->RangeExpr = ParseBraceInitializer();
1994 FRI->RangeExpr = ParseExpression();
1997 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1999 Actions.ActOnCXXForRangeDecl(ThisDecl);
2000 Actions.FinalizeDeclaration(ThisDecl);
2001 D.complete(ThisDecl);
2002 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2005 SmallVector<Decl *, 8> DeclsInGroup;
2006 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2007 D, ParsedTemplateInfo(), FRI);
2008 if (LateParsedAttrs.size() > 0)
2009 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2010 D.complete(FirstDecl);
2012 DeclsInGroup.push_back(FirstDecl);
2014 bool ExpectSemi = Context != Declarator::ForContext;
2016 // If we don't have a comma, it is either the end of the list (a ';') or an
2018 SourceLocation CommaLoc;
2019 while (TryConsumeToken(tok::comma, CommaLoc)) {
2020 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2021 // This comma was followed by a line-break and something which can't be
2022 // the start of a declarator. The comma was probably a typo for a
2024 Diag(CommaLoc, diag::err_expected_semi_declaration)
2025 << FixItHint::CreateReplacement(CommaLoc, ";");
2030 // Parse the next declarator.
2032 D.setCommaLoc(CommaLoc);
2034 // Accept attributes in an init-declarator. In the first declarator in a
2035 // declaration, these would be part of the declspec. In subsequent
2036 // declarators, they become part of the declarator itself, so that they
2037 // don't apply to declarators after *this* one. Examples:
2038 // short __attribute__((common)) var; -> declspec
2039 // short var __attribute__((common)); -> declarator
2040 // short x, __attribute__((common)) var; -> declarator
2041 MaybeParseGNUAttributes(D);
2043 // MSVC parses but ignores qualifiers after the comma as an extension.
2044 if (getLangOpts().MicrosoftExt)
2045 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2048 if (!D.isInvalidType()) {
2049 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2050 D.complete(ThisDecl);
2052 DeclsInGroup.push_back(ThisDecl);
2057 *DeclEnd = Tok.getLocation();
2060 ExpectAndConsumeSemi(Context == Declarator::FileContext
2061 ? diag::err_invalid_token_after_toplevel_declarator
2062 : diag::err_expected_semi_declaration)) {
2063 // Okay, there was no semicolon and one was expected. If we see a
2064 // declaration specifier, just assume it was missing and continue parsing.
2065 // Otherwise things are very confused and we skip to recover.
2066 if (!isDeclarationSpecifier()) {
2067 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2068 TryConsumeToken(tok::semi);
2072 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2075 /// Parse an optional simple-asm-expr and attributes, and attach them to a
2076 /// declarator. Returns true on an error.
2077 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2078 // If a simple-asm-expr is present, parse it.
2079 if (Tok.is(tok::kw_asm)) {
2081 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2082 if (AsmLabel.isInvalid()) {
2083 SkipUntil(tok::semi, StopBeforeMatch);
2087 D.setAsmLabel(AsmLabel.get());
2091 MaybeParseGNUAttributes(D);
2095 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
2096 /// declarator'. This method parses the remainder of the declaration
2097 /// (including any attributes or initializer, among other things) and
2098 /// finalizes the declaration.
2100 /// init-declarator: [C99 6.7]
2102 /// declarator '=' initializer
2103 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2104 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2105 /// [C++] declarator initializer[opt]
2107 /// [C++] initializer:
2108 /// [C++] '=' initializer-clause
2109 /// [C++] '(' expression-list ')'
2110 /// [C++0x] '=' 'default' [TODO]
2111 /// [C++0x] '=' 'delete'
2112 /// [C++0x] braced-init-list
2114 /// According to the standard grammar, =default and =delete are function
2115 /// definitions, but that definitely doesn't fit with the parser here.
2117 Decl *Parser::ParseDeclarationAfterDeclarator(
2118 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2119 if (ParseAsmAttributesAfterDeclarator(D))
2122 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2125 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2126 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2127 // Inform the current actions module that we just parsed this declarator.
2128 Decl *ThisDecl = nullptr;
2129 switch (TemplateInfo.Kind) {
2130 case ParsedTemplateInfo::NonTemplate:
2131 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2134 case ParsedTemplateInfo::Template:
2135 case ParsedTemplateInfo::ExplicitSpecialization: {
2136 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2137 *TemplateInfo.TemplateParams,
2139 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
2140 // Re-direct this decl to refer to the templated decl so that we can
2142 ThisDecl = VT->getTemplatedDecl();
2145 case ParsedTemplateInfo::ExplicitInstantiation: {
2146 if (Tok.is(tok::semi)) {
2147 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2148 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2149 if (ThisRes.isInvalid()) {
2150 SkipUntil(tok::semi, StopBeforeMatch);
2153 ThisDecl = ThisRes.get();
2155 // FIXME: This check should be for a variable template instantiation only.
2157 // Check that this is a valid instantiation
2158 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
2159 // If the declarator-id is not a template-id, issue a diagnostic and
2160 // recover by ignoring the 'template' keyword.
2161 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2162 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2163 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2165 SourceLocation LAngleLoc =
2166 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2167 Diag(D.getIdentifierLoc(),
2168 diag::err_explicit_instantiation_with_definition)
2169 << SourceRange(TemplateInfo.TemplateLoc)
2170 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2172 // Recover as if it were an explicit specialization.
2173 TemplateParameterLists FakedParamLists;
2174 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2175 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
2176 LAngleLoc, nullptr));
2179 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2186 // Parse declarator '=' initializer.
2187 // If a '==' or '+=' is found, suggest a fixit to '='.
2188 if (isTokenEqualOrEqualTypo()) {
2189 SourceLocation EqualLoc = ConsumeToken();
2191 if (Tok.is(tok::kw_delete)) {
2192 if (D.isFunctionDeclarator())
2193 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2196 Diag(ConsumeToken(), diag::err_deleted_non_function);
2197 } else if (Tok.is(tok::kw_default)) {
2198 if (D.isFunctionDeclarator())
2199 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2202 Diag(ConsumeToken(), diag::err_default_special_members);
2204 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2206 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
2209 if (Tok.is(tok::code_completion)) {
2210 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2211 Actions.FinalizeDeclaration(ThisDecl);
2216 ExprResult Init(ParseInitializer());
2218 // If this is the only decl in (possibly) range based for statement,
2219 // our best guess is that the user meant ':' instead of '='.
2220 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2221 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2222 << FixItHint::CreateReplacement(EqualLoc, ":");
2223 // We are trying to stop parser from looking for ';' in this for
2224 // statement, therefore preventing spurious errors to be issued.
2225 FRI->ColonLoc = EqualLoc;
2227 FRI->RangeExpr = Init;
2230 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2231 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2235 if (Init.isInvalid()) {
2236 SmallVector<tok::TokenKind, 2> StopTokens;
2237 StopTokens.push_back(tok::comma);
2238 if (D.getContext() == Declarator::ForContext ||
2239 D.getContext() == Declarator::InitStmtContext)
2240 StopTokens.push_back(tok::r_paren);
2241 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2242 Actions.ActOnInitializerError(ThisDecl);
2244 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2245 /*DirectInit=*/false);
2247 } else if (Tok.is(tok::l_paren)) {
2248 // Parse C++ direct initializer: '(' expression-list ')'
2249 BalancedDelimiterTracker T(*this, tok::l_paren);
2253 CommaLocsTy CommaLocs;
2255 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2257 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
2260 if (ParseExpressionList(Exprs, CommaLocs, [&] {
2261 Actions.CodeCompleteConstructor(getCurScope(),
2262 cast<VarDecl>(ThisDecl)->getType()->getCanonicalTypeInternal(),
2263 ThisDecl->getLocation(), Exprs);
2265 Actions.ActOnInitializerError(ThisDecl);
2266 SkipUntil(tok::r_paren, StopAtSemi);
2268 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2269 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2276 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2277 "Unexpected number of commas!");
2279 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2280 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2284 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2285 T.getCloseLocation(),
2287 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2288 /*DirectInit=*/true);
2290 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2291 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
2292 // Parse C++0x braced-init-list.
2293 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2295 if (D.getCXXScopeSpec().isSet()) {
2297 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
2300 ExprResult Init(ParseBraceInitializer());
2302 if (D.getCXXScopeSpec().isSet()) {
2303 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2307 if (Init.isInvalid()) {
2308 Actions.ActOnInitializerError(ThisDecl);
2310 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2313 Actions.ActOnUninitializedDecl(ThisDecl);
2316 Actions.FinalizeDeclaration(ThisDecl);
2321 /// ParseSpecifierQualifierList
2322 /// specifier-qualifier-list:
2323 /// type-specifier specifier-qualifier-list[opt]
2324 /// type-qualifier specifier-qualifier-list[opt]
2325 /// [GNU] attributes specifier-qualifier-list[opt]
2327 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2328 DeclSpecContext DSC) {
2329 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2330 /// parse declaration-specifiers and complain about extra stuff.
2331 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2332 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2334 // Validate declspec for type-name.
2335 unsigned Specs = DS.getParsedSpecifiers();
2336 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2337 Diag(Tok, diag::err_expected_type);
2338 DS.SetTypeSpecError();
2339 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2340 Diag(Tok, diag::err_typename_requires_specqual);
2341 if (!DS.hasTypeSpecifier())
2342 DS.SetTypeSpecError();
2345 // Issue diagnostic and remove storage class if present.
2346 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2347 if (DS.getStorageClassSpecLoc().isValid())
2348 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2350 Diag(DS.getThreadStorageClassSpecLoc(),
2351 diag::err_typename_invalid_storageclass);
2352 DS.ClearStorageClassSpecs();
2355 // Issue diagnostic and remove function specifier if present.
2356 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2357 if (DS.isInlineSpecified())
2358 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2359 if (DS.isVirtualSpecified())
2360 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2361 if (DS.isExplicitSpecified())
2362 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2363 DS.ClearFunctionSpecs();
2366 // Issue diagnostic and remove constexpr specfier if present.
2367 if (DS.isConstexprSpecified() && DSC != DSC_condition) {
2368 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2369 DS.ClearConstexprSpec();
2373 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2374 /// specified token is valid after the identifier in a declarator which
2375 /// immediately follows the declspec. For example, these things are valid:
2377 /// int x [ 4]; // direct-declarator
2378 /// int x ( int y); // direct-declarator
2379 /// int(int x ) // direct-declarator
2380 /// int x ; // simple-declaration
2381 /// int x = 17; // init-declarator-list
2382 /// int x , y; // init-declarator-list
2383 /// int x __asm__ ("foo"); // init-declarator-list
2384 /// int x : 4; // struct-declarator
2385 /// int x { 5}; // C++'0x unified initializers
2387 /// This is not, because 'x' does not immediately follow the declspec (though
2388 /// ')' happens to be valid anyway).
2391 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2392 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2393 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2397 /// ParseImplicitInt - This method is called when we have an non-typename
2398 /// identifier in a declspec (which normally terminates the decl spec) when
2399 /// the declspec has no type specifier. In this case, the declspec is either
2400 /// malformed or is "implicit int" (in K&R and C89).
2402 /// This method handles diagnosing this prettily and returns false if the
2403 /// declspec is done being processed. If it recovers and thinks there may be
2404 /// other pieces of declspec after it, it returns true.
2406 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2407 const ParsedTemplateInfo &TemplateInfo,
2408 AccessSpecifier AS, DeclSpecContext DSC,
2409 ParsedAttributesWithRange &Attrs) {
2410 assert(Tok.is(tok::identifier) && "should have identifier");
2412 SourceLocation Loc = Tok.getLocation();
2413 // If we see an identifier that is not a type name, we normally would
2414 // parse it as the identifer being declared. However, when a typename
2415 // is typo'd or the definition is not included, this will incorrectly
2416 // parse the typename as the identifier name and fall over misparsing
2417 // later parts of the diagnostic.
2419 // As such, we try to do some look-ahead in cases where this would
2420 // otherwise be an "implicit-int" case to see if this is invalid. For
2421 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2422 // an identifier with implicit int, we'd get a parse error because the
2423 // next token is obviously invalid for a type. Parse these as a case
2424 // with an invalid type specifier.
2425 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2427 // Since we know that this either implicit int (which is rare) or an
2428 // error, do lookahead to try to do better recovery. This never applies
2429 // within a type specifier. Outside of C++, we allow this even if the
2430 // language doesn't "officially" support implicit int -- we support
2431 // implicit int as an extension in C99 and C11.
2432 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2433 isValidAfterIdentifierInDeclarator(NextToken())) {
2434 // If this token is valid for implicit int, e.g. "static x = 4", then
2435 // we just avoid eating the identifier, so it will be parsed as the
2436 // identifier in the declarator.
2440 if (getLangOpts().CPlusPlus &&
2441 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2442 // Don't require a type specifier if we have the 'auto' storage class
2443 // specifier in C++98 -- we'll promote it to a type specifier.
2445 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2449 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2450 getLangOpts().MSVCCompat) {
2451 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2452 // Give Sema a chance to recover if we are in a template with dependent base
2454 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2455 *Tok.getIdentifierInfo(), Tok.getLocation(),
2456 DSC == DSC_template_type_arg)) {
2457 const char *PrevSpec;
2459 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2460 Actions.getASTContext().getPrintingPolicy());
2461 DS.SetRangeEnd(Tok.getLocation());
2467 // Otherwise, if we don't consume this token, we are going to emit an
2468 // error anyway. Try to recover from various common problems. Check
2469 // to see if this was a reference to a tag name without a tag specified.
2470 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2472 // C++ doesn't need this, and isTagName doesn't take SS.
2473 if (SS == nullptr) {
2474 const char *TagName = nullptr, *FixitTagName = nullptr;
2475 tok::TokenKind TagKind = tok::unknown;
2477 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2479 case DeclSpec::TST_enum:
2480 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2481 case DeclSpec::TST_union:
2482 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2483 case DeclSpec::TST_struct:
2484 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2485 case DeclSpec::TST_interface:
2486 TagName="__interface"; FixitTagName = "__interface ";
2487 TagKind=tok::kw___interface;break;
2488 case DeclSpec::TST_class:
2489 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2493 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2494 LookupResult R(Actions, TokenName, SourceLocation(),
2495 Sema::LookupOrdinaryName);
2497 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2498 << TokenName << TagName << getLangOpts().CPlusPlus
2499 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2501 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2502 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2504 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2505 << TokenName << TagName;
2508 // Parse this as a tag as if the missing tag were present.
2509 if (TagKind == tok::kw_enum)
2510 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
2512 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2513 /*EnteringContext*/ false, DSC_normal, Attrs);
2518 // Determine whether this identifier could plausibly be the name of something
2519 // being declared (with a missing type).
2520 if (!isTypeSpecifier(DSC) &&
2521 (!SS || DSC == DSC_top_level || DSC == DSC_class)) {
2522 // Look ahead to the next token to try to figure out what this declaration
2523 // was supposed to be.
2524 switch (NextToken().getKind()) {
2525 case tok::l_paren: {
2526 // static x(4); // 'x' is not a type
2527 // x(int n); // 'x' is not a type
2528 // x (*p)[]; // 'x' is a type
2530 // Since we're in an error case, we can afford to perform a tentative
2531 // parse to determine which case we're in.
2532 TentativeParsingAction PA(*this);
2534 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2537 if (TPR != TPResult::False) {
2538 // The identifier is followed by a parenthesized declarator.
2539 // It's supposed to be a type.
2543 // If we're in a context where we could be declaring a constructor,
2544 // check whether this is a constructor declaration with a bogus name.
2545 if (DSC == DSC_class || (DSC == DSC_top_level && SS)) {
2546 IdentifierInfo *II = Tok.getIdentifierInfo();
2547 if (Actions.isCurrentClassNameTypo(II, SS)) {
2548 Diag(Loc, diag::err_constructor_bad_name)
2549 << Tok.getIdentifierInfo() << II
2550 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2551 Tok.setIdentifierInfo(II);
2562 // This looks like a variable or function declaration. The type is
2563 // probably missing. We're done parsing decl-specifiers.
2565 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2569 // This is probably supposed to be a type. This includes cases like:
2571 // struct S { unsinged : 4; };
2576 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2577 // and attempt to recover.
2579 IdentifierInfo *II = Tok.getIdentifierInfo();
2580 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2581 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2584 // The action has suggested that the type T could be used. Set that as
2585 // the type in the declaration specifiers, consume the would-be type
2586 // name token, and we're done.
2587 const char *PrevSpec;
2589 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2590 Actions.getASTContext().getPrintingPolicy());
2591 DS.SetRangeEnd(Tok.getLocation());
2593 // There may be other declaration specifiers after this.
2595 } else if (II != Tok.getIdentifierInfo()) {
2596 // If no type was suggested, the correction is to a keyword
2597 Tok.setKind(II->getTokenID());
2598 // There may be other declaration specifiers after this.
2602 // Otherwise, the action had no suggestion for us. Mark this as an error.
2603 DS.SetTypeSpecError();
2604 DS.SetRangeEnd(Tok.getLocation());
2607 // Eat any following template arguments.
2608 if (IsTemplateName) {
2609 SourceLocation LAngle, RAngle;
2610 TemplateArgList Args;
2611 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2614 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2615 // avoid rippling error messages on subsequent uses of the same type,
2616 // could be useful if #include was forgotten.
2620 /// \brief Determine the declaration specifier context from the declarator
2623 /// \param Context the declarator context, which is one of the
2624 /// Declarator::TheContext enumerator values.
2625 Parser::DeclSpecContext
2626 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
2627 if (Context == Declarator::MemberContext)
2629 if (Context == Declarator::FileContext)
2630 return DSC_top_level;
2631 if (Context == Declarator::TemplateTypeArgContext)
2632 return DSC_template_type_arg;
2633 if (Context == Declarator::TrailingReturnContext)
2634 return DSC_trailing;
2635 if (Context == Declarator::AliasDeclContext ||
2636 Context == Declarator::AliasTemplateContext)
2637 return DSC_alias_declaration;
2641 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2643 /// FIXME: Simply returns an alignof() expression if the argument is a
2644 /// type. Ideally, the type should be propagated directly into Sema.
2647 /// [C11] constant-expression
2648 /// [C++0x] type-id ...[opt]
2649 /// [C++0x] assignment-expression ...[opt]
2650 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2651 SourceLocation &EllipsisLoc) {
2653 if (isTypeIdInParens()) {
2654 SourceLocation TypeLoc = Tok.getLocation();
2655 ParsedType Ty = ParseTypeName().get();
2656 SourceRange TypeRange(Start, Tok.getLocation());
2657 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2658 Ty.getAsOpaquePtr(), TypeRange);
2660 ER = ParseConstantExpression();
2662 if (getLangOpts().CPlusPlus11)
2663 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2668 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2669 /// attribute to Attrs.
2671 /// alignment-specifier:
2672 /// [C11] '_Alignas' '(' type-id ')'
2673 /// [C11] '_Alignas' '(' constant-expression ')'
2674 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2675 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2676 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2677 SourceLocation *EndLoc) {
2678 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2679 "Not an alignment-specifier!");
2681 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2682 SourceLocation KWLoc = ConsumeToken();
2684 BalancedDelimiterTracker T(*this, tok::l_paren);
2685 if (T.expectAndConsume())
2688 SourceLocation EllipsisLoc;
2689 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2690 if (ArgExpr.isInvalid()) {
2697 *EndLoc = T.getCloseLocation();
2699 ArgsVector ArgExprs;
2700 ArgExprs.push_back(ArgExpr.get());
2701 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2702 AttributeList::AS_Keyword, EllipsisLoc);
2705 /// Determine whether we're looking at something that might be a declarator
2706 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2707 /// diagnose a missing semicolon after a prior tag definition in the decl
2710 /// \return \c true if an error occurred and this can't be any kind of
2713 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2714 DeclSpecContext DSContext,
2715 LateParsedAttrList *LateAttrs) {
2716 assert(DS.hasTagDefinition() && "shouldn't call this");
2718 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2720 if (getLangOpts().CPlusPlus &&
2721 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2722 tok::annot_template_id) &&
2723 TryAnnotateCXXScopeToken(EnteringContext)) {
2724 SkipMalformedDecl();
2728 bool HasScope = Tok.is(tok::annot_cxxscope);
2729 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2730 Token AfterScope = HasScope ? NextToken() : Tok;
2732 // Determine whether the following tokens could possibly be a
2734 bool MightBeDeclarator = true;
2735 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2736 // A declarator-id can't start with 'typename'.
2737 MightBeDeclarator = false;
2738 } else if (AfterScope.is(tok::annot_template_id)) {
2739 // If we have a type expressed as a template-id, this cannot be a
2740 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2741 TemplateIdAnnotation *Annot =
2742 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2743 if (Annot->Kind == TNK_Type_template)
2744 MightBeDeclarator = false;
2745 } else if (AfterScope.is(tok::identifier)) {
2746 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2748 // These tokens cannot come after the declarator-id in a
2749 // simple-declaration, and are likely to come after a type-specifier.
2750 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2751 tok::annot_cxxscope, tok::coloncolon)) {
2752 // Missing a semicolon.
2753 MightBeDeclarator = false;
2754 } else if (HasScope) {
2755 // If the declarator-id has a scope specifier, it must redeclare a
2756 // previously-declared entity. If that's a type (and this is not a
2757 // typedef), that's an error.
2759 Actions.RestoreNestedNameSpecifierAnnotation(
2760 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2761 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2762 Sema::NameClassification Classification = Actions.ClassifyName(
2763 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2764 /*IsAddressOfOperand*/false);
2765 switch (Classification.getKind()) {
2766 case Sema::NC_Error:
2767 SkipMalformedDecl();
2770 case Sema::NC_Keyword:
2771 case Sema::NC_NestedNameSpecifier:
2772 llvm_unreachable("typo correction and nested name specifiers not "
2776 case Sema::NC_TypeTemplate:
2777 // Not a previously-declared non-type entity.
2778 MightBeDeclarator = false;
2781 case Sema::NC_Unknown:
2782 case Sema::NC_Expression:
2783 case Sema::NC_VarTemplate:
2784 case Sema::NC_FunctionTemplate:
2785 // Might be a redeclaration of a prior entity.
2791 if (MightBeDeclarator)
2794 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2795 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()),
2796 diag::err_expected_after)
2797 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2799 // Try to recover from the typo, by dropping the tag definition and parsing
2800 // the problematic tokens as a type.
2802 // FIXME: Split the DeclSpec into pieces for the standalone
2803 // declaration and pieces for the following declaration, instead
2804 // of assuming that all the other pieces attach to new declaration,
2805 // and call ParsedFreeStandingDeclSpec as appropriate.
2806 DS.ClearTypeSpecType();
2807 ParsedTemplateInfo NotATemplate;
2808 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2812 /// ParseDeclarationSpecifiers
2813 /// declaration-specifiers: [C99 6.7]
2814 /// storage-class-specifier declaration-specifiers[opt]
2815 /// type-specifier declaration-specifiers[opt]
2816 /// [C99] function-specifier declaration-specifiers[opt]
2817 /// [C11] alignment-specifier declaration-specifiers[opt]
2818 /// [GNU] attributes declaration-specifiers[opt]
2819 /// [Clang] '__module_private__' declaration-specifiers[opt]
2820 /// [ObjC1] '__kindof' declaration-specifiers[opt]
2822 /// storage-class-specifier: [C99 6.7.1]
2829 /// [C++11] 'thread_local'
2830 /// [C11] '_Thread_local'
2831 /// [GNU] '__thread'
2832 /// function-specifier: [C99 6.7.4]
2835 /// [C++] 'explicit'
2836 /// [OpenCL] '__kernel'
2837 /// 'friend': [C++ dcl.friend]
2838 /// 'constexpr': [C++0x dcl.constexpr]
2839 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2840 const ParsedTemplateInfo &TemplateInfo,
2842 DeclSpecContext DSContext,
2843 LateParsedAttrList *LateAttrs) {
2844 if (DS.getSourceRange().isInvalid()) {
2845 // Start the range at the current token but make the end of the range
2846 // invalid. This will make the entire range invalid unless we successfully
2848 DS.SetRangeStart(Tok.getLocation());
2849 DS.SetRangeEnd(SourceLocation());
2852 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2853 bool AttrsLastTime = false;
2854 ParsedAttributesWithRange attrs(AttrFactory);
2855 // We use Sema's policy to get bool macros right.
2856 PrintingPolicy Policy = Actions.getPrintingPolicy();
2858 bool isInvalid = false;
2859 bool isStorageClass = false;
2860 const char *PrevSpec = nullptr;
2861 unsigned DiagID = 0;
2863 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2864 // implementation for VS2013 uses _Atomic as an identifier for one of the
2865 // classes in <atomic>.
2867 // A typedef declaration containing _Atomic<...> is among the places where
2868 // the class is used. If we are currently parsing such a declaration, treat
2869 // the token as an identifier.
2870 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2871 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
2872 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
2873 Tok.setKind(tok::identifier);
2875 SourceLocation Loc = Tok.getLocation();
2877 switch (Tok.getKind()) {
2881 ProhibitAttributes(attrs);
2883 // Reject C++11 attributes that appertain to decl specifiers as
2884 // we don't support any C++11 attributes that appertain to decl
2885 // specifiers. This also conforms to what g++ 4.8 is doing.
2886 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
2888 DS.takeAttributesFrom(attrs);
2891 // If this is not a declaration specifier token, we're done reading decl
2892 // specifiers. First verify that DeclSpec's are consistent.
2893 DS.Finish(Actions, Policy);
2897 case tok::kw_alignas:
2898 if (!getLangOpts().CPlusPlus11 || !isCXX11AttributeSpecifier())
2899 goto DoneWithDeclSpec;
2901 ProhibitAttributes(attrs);
2902 // FIXME: It would be good to recover by accepting the attributes,
2903 // but attempting to do that now would cause serious
2904 // madness in terms of diagnostics.
2906 attrs.Range = SourceRange();
2908 ParseCXX11Attributes(attrs);
2909 AttrsLastTime = true;
2912 case tok::code_completion: {
2913 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2914 if (DS.hasTypeSpecifier()) {
2915 bool AllowNonIdentifiers
2916 = (getCurScope()->getFlags() & (Scope::ControlScope |
2918 Scope::TemplateParamScope |
2919 Scope::FunctionPrototypeScope |
2920 Scope::AtCatchScope)) == 0;
2921 bool AllowNestedNameSpecifiers
2922 = DSContext == DSC_top_level ||
2923 (DSContext == DSC_class && DS.isFriendSpecified());
2925 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
2926 AllowNonIdentifiers,
2927 AllowNestedNameSpecifiers);
2928 return cutOffParsing();
2931 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
2932 CCC = Sema::PCC_LocalDeclarationSpecifiers;
2933 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
2934 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
2935 : Sema::PCC_Template;
2936 else if (DSContext == DSC_class)
2937 CCC = Sema::PCC_Class;
2938 else if (CurParsedObjCImpl)
2939 CCC = Sema::PCC_ObjCImplementation;
2941 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
2942 return cutOffParsing();
2945 case tok::coloncolon: // ::foo::bar
2946 // C++ scope specifier. Annotate and loop, or bail out on error.
2947 if (TryAnnotateCXXScopeToken(EnteringContext)) {
2948 if (!DS.hasTypeSpecifier())
2949 DS.SetTypeSpecError();
2950 goto DoneWithDeclSpec;
2952 if (Tok.is(tok::coloncolon)) // ::new or ::delete
2953 goto DoneWithDeclSpec;
2956 case tok::annot_cxxscope: {
2957 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
2958 goto DoneWithDeclSpec;
2961 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2962 Tok.getAnnotationRange(),
2965 // We are looking for a qualified typename.
2966 Token Next = NextToken();
2967 if (Next.is(tok::annot_template_id) &&
2968 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
2969 ->Kind == TNK_Type_template) {
2970 // We have a qualified template-id, e.g., N::A<int>
2972 // If this would be a valid constructor declaration with template
2973 // arguments, we will reject the attempt to form an invalid type-id
2974 // referring to the injected-class-name when we annotate the token,
2975 // per C++ [class.qual]p2.
2977 // To improve diagnostics for this case, parse the declaration as a
2978 // constructor (and reject the extra template arguments later).
2979 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
2980 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2982 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
2983 isConstructorDeclarator(/*Unqualified*/false)) {
2984 // The user meant this to be an out-of-line constructor
2985 // definition, but template arguments are not allowed
2986 // there. Just allow this as a constructor; we'll
2987 // complain about it later.
2988 goto DoneWithDeclSpec;
2991 DS.getTypeSpecScope() = SS;
2992 ConsumeToken(); // The C++ scope.
2993 assert(Tok.is(tok::annot_template_id) &&
2994 "ParseOptionalCXXScopeSpecifier not working");
2995 AnnotateTemplateIdTokenAsType();
2999 if (Next.is(tok::annot_typename)) {
3000 DS.getTypeSpecScope() = SS;
3001 ConsumeToken(); // The C++ scope.
3002 if (Tok.getAnnotationValue()) {
3003 ParsedType T = getTypeAnnotation(Tok);
3004 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3005 Tok.getAnnotationEndLoc(),
3006 PrevSpec, DiagID, T, Policy);
3011 DS.SetTypeSpecError();
3012 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3013 ConsumeToken(); // The typename
3016 if (Next.isNot(tok::identifier))
3017 goto DoneWithDeclSpec;
3019 // Check whether this is a constructor declaration. If we're in a
3020 // context where the identifier could be a class name, and it has the
3021 // shape of a constructor declaration, process it as one.
3022 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
3023 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3025 isConstructorDeclarator(/*Unqualified*/ false))
3026 goto DoneWithDeclSpec;
3028 ParsedType TypeRep =
3029 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3030 getCurScope(), &SS, false, false, nullptr,
3031 /*IsCtorOrDtorName=*/false,
3032 /*WantNonTrivialSourceInfo=*/true,
3033 isClassTemplateDeductionContext(DSContext));
3035 // If the referenced identifier is not a type, then this declspec is
3036 // erroneous: We already checked about that it has no type specifier, and
3037 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3040 ConsumeToken(); // Eat the scope spec so the identifier is current.
3041 ParsedAttributesWithRange Attrs(AttrFactory);
3042 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3043 if (!Attrs.empty()) {
3044 AttrsLastTime = true;
3045 attrs.takeAllFrom(Attrs);
3049 goto DoneWithDeclSpec;
3052 DS.getTypeSpecScope() = SS;
3053 ConsumeToken(); // The C++ scope.
3055 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3056 DiagID, TypeRep, Policy);
3060 DS.SetRangeEnd(Tok.getLocation());
3061 ConsumeToken(); // The typename.
3066 case tok::annot_typename: {
3067 // If we've previously seen a tag definition, we were almost surely
3068 // missing a semicolon after it.
3069 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3070 goto DoneWithDeclSpec;
3072 if (Tok.getAnnotationValue()) {
3073 ParsedType T = getTypeAnnotation(Tok);
3074 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3077 DS.SetTypeSpecError();
3082 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3083 ConsumeToken(); // The typename
3088 case tok::kw___is_signed:
3089 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3090 // typically treats it as a trait. If we see __is_signed as it appears
3091 // in libstdc++, e.g.,
3093 // static const bool __is_signed;
3095 // then treat __is_signed as an identifier rather than as a keyword.
3096 if (DS.getTypeSpecType() == TST_bool &&
3097 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3098 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3099 TryKeywordIdentFallback(true);
3101 // We're done with the declaration-specifiers.
3102 goto DoneWithDeclSpec;
3105 case tok::kw___super:
3106 case tok::kw_decltype:
3107 case tok::identifier: {
3108 // This identifier can only be a typedef name if we haven't already seen
3109 // a type-specifier. Without this check we misparse:
3110 // typedef int X; struct Y { short X; }; as 'short int'.
3111 if (DS.hasTypeSpecifier())
3112 goto DoneWithDeclSpec;
3114 // If the token is an identifier named "__declspec" and Microsoft
3115 // extensions are not enabled, it is likely that there will be cascading
3116 // parse errors if this really is a __declspec attribute. Attempt to
3117 // recognize that scenario and recover gracefully.
3118 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3119 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3120 Diag(Loc, diag::err_ms_attributes_not_enabled);
3122 // The next token should be an open paren. If it is, eat the entire
3123 // attribute declaration and continue.
3124 if (NextToken().is(tok::l_paren)) {
3125 // Consume the __declspec identifier.
3128 // Eat the parens and everything between them.
3129 BalancedDelimiterTracker T(*this, tok::l_paren);
3130 if (T.consumeOpen()) {
3131 assert(false && "Not a left paren?");
3139 // In C++, check to see if this is a scope specifier like foo::bar::, if
3140 // so handle it as such. This is important for ctor parsing.
3141 if (getLangOpts().CPlusPlus) {
3142 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3143 DS.SetTypeSpecError();
3144 goto DoneWithDeclSpec;
3146 if (!Tok.is(tok::identifier))
3150 // Check for need to substitute AltiVec keyword tokens.
3151 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3154 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3155 // allow the use of a typedef name as a type specifier.
3156 if (DS.isTypeAltiVecVector())
3157 goto DoneWithDeclSpec;
3159 if (DSContext == DSC_objc_method_result && isObjCInstancetype()) {
3160 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3162 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3163 DiagID, TypeRep, Policy);
3167 DS.SetRangeEnd(Loc);
3172 ParsedType TypeRep = Actions.getTypeName(
3173 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3174 false, false, nullptr, false, false,
3175 isClassTemplateDeductionContext(DSContext));
3177 // If this is not a typedef name, don't parse it as part of the declspec,
3178 // it must be an implicit int or an error.
3180 ParsedAttributesWithRange Attrs(AttrFactory);
3181 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3182 if (!Attrs.empty()) {
3183 AttrsLastTime = true;
3184 attrs.takeAllFrom(Attrs);
3188 goto DoneWithDeclSpec;
3191 // If we're in a context where the identifier could be a class name,
3192 // check whether this is a constructor declaration.
3193 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
3194 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3195 isConstructorDeclarator(/*Unqualified*/true))
3196 goto DoneWithDeclSpec;
3198 // Likewise, if this is a context where the identifier could be a template
3199 // name, check whether this is a deduction guide declaration.
3200 if (getLangOpts().CPlusPlus1z &&
3201 (DSContext == DSC_class || DSContext == DSC_top_level) &&
3202 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3203 Tok.getLocation()) &&
3204 isConstructorDeclarator(/*Unqualified*/ true,
3205 /*DeductionGuide*/ true))
3206 goto DoneWithDeclSpec;
3208 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3209 DiagID, TypeRep, Policy);
3213 DS.SetRangeEnd(Tok.getLocation());
3214 ConsumeToken(); // The identifier
3216 // Objective-C supports type arguments and protocol references
3217 // following an Objective-C object or object pointer
3218 // type. Handle either one of them.
3219 if (Tok.is(tok::less) && getLangOpts().ObjC1) {
3220 SourceLocation NewEndLoc;
3221 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3222 Loc, TypeRep, /*consumeLastToken=*/true,
3224 if (NewTypeRep.isUsable()) {
3225 DS.UpdateTypeRep(NewTypeRep.get());
3226 DS.SetRangeEnd(NewEndLoc);
3230 // Need to support trailing type qualifiers (e.g. "id<p> const").
3231 // If a type specifier follows, it will be diagnosed elsewhere.
3236 case tok::annot_template_id: {
3237 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3238 if (TemplateId->Kind != TNK_Type_template) {
3239 // This template-id does not refer to a type name, so we're
3240 // done with the type-specifiers.
3241 goto DoneWithDeclSpec;
3244 // If we're in a context where the template-id could be a
3245 // constructor name or specialization, check whether this is a
3246 // constructor declaration.
3247 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
3248 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3249 isConstructorDeclarator(TemplateId->SS.isEmpty()))
3250 goto DoneWithDeclSpec;
3252 // Turn the template-id annotation token into a type annotation
3253 // token, then try again to parse it as a type-specifier.
3254 AnnotateTemplateIdTokenAsType();
3258 // GNU attributes support.
3259 case tok::kw___attribute:
3260 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3263 // Microsoft declspec support.
3264 case tok::kw___declspec:
3265 ParseMicrosoftDeclSpecs(DS.getAttributes());
3268 // Microsoft single token adornments.
3269 case tok::kw___forceinline: {
3270 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3271 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3272 SourceLocation AttrNameLoc = Tok.getLocation();
3273 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3274 nullptr, 0, AttributeList::AS_Keyword);
3278 case tok::kw___unaligned:
3279 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3283 case tok::kw___sptr:
3284 case tok::kw___uptr:
3285 case tok::kw___ptr64:
3286 case tok::kw___ptr32:
3288 case tok::kw___cdecl:
3289 case tok::kw___stdcall:
3290 case tok::kw___fastcall:
3291 case tok::kw___thiscall:
3292 case tok::kw___regcall:
3293 case tok::kw___vectorcall:
3294 ParseMicrosoftTypeAttributes(DS.getAttributes());
3297 // Borland single token adornments.
3298 case tok::kw___pascal:
3299 ParseBorlandTypeAttributes(DS.getAttributes());
3302 // OpenCL single token adornments.
3303 case tok::kw___kernel:
3304 ParseOpenCLKernelAttributes(DS.getAttributes());
3307 // Nullability type specifiers.
3308 case tok::kw__Nonnull:
3309 case tok::kw__Nullable:
3310 case tok::kw__Null_unspecified:
3311 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3314 // Objective-C 'kindof' types.
3315 case tok::kw___kindof:
3316 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3317 nullptr, 0, AttributeList::AS_Keyword);
3318 (void)ConsumeToken();
3321 // storage-class-specifier
3322 case tok::kw_typedef:
3323 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3324 PrevSpec, DiagID, Policy);
3325 isStorageClass = true;
3327 case tok::kw_extern:
3328 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3329 Diag(Tok, diag::ext_thread_before) << "extern";
3330 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3331 PrevSpec, DiagID, Policy);
3332 isStorageClass = true;
3334 case tok::kw___private_extern__:
3335 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3336 Loc, PrevSpec, DiagID, Policy);
3337 isStorageClass = true;
3339 case tok::kw_static:
3340 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3341 Diag(Tok, diag::ext_thread_before) << "static";
3342 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3343 PrevSpec, DiagID, Policy);
3344 isStorageClass = true;
3347 if (getLangOpts().CPlusPlus11) {
3348 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3349 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3350 PrevSpec, DiagID, Policy);
3352 Diag(Tok, diag::ext_auto_storage_class)
3353 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3355 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3358 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3359 PrevSpec, DiagID, Policy);
3360 isStorageClass = true;
3362 case tok::kw___auto_type:
3363 Diag(Tok, diag::ext_auto_type);
3364 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3367 case tok::kw_register:
3368 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3369 PrevSpec, DiagID, Policy);
3370 isStorageClass = true;
3372 case tok::kw_mutable:
3373 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3374 PrevSpec, DiagID, Policy);
3375 isStorageClass = true;
3377 case tok::kw___thread:
3378 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3380 isStorageClass = true;
3382 case tok::kw_thread_local:
3383 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3386 case tok::kw__Thread_local:
3387 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3388 Loc, PrevSpec, DiagID);
3389 isStorageClass = true;
3392 // function-specifier
3393 case tok::kw_inline:
3394 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3396 case tok::kw_virtual:
3397 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3399 case tok::kw_explicit:
3400 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
3402 case tok::kw__Noreturn:
3403 if (!getLangOpts().C11)
3404 Diag(Loc, diag::ext_c11_noreturn);
3405 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3408 // alignment-specifier
3409 case tok::kw__Alignas:
3410 if (!getLangOpts().C11)
3411 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
3412 ParseAlignmentSpecifier(DS.getAttributes());
3416 case tok::kw_friend:
3417 if (DSContext == DSC_class)
3418 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3420 PrevSpec = ""; // not actually used by the diagnostic
3421 DiagID = diag::err_friend_invalid_in_context;
3427 case tok::kw___module_private__:
3428 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3432 case tok::kw_constexpr:
3433 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3437 case tok::kw_concept:
3438 isInvalid = DS.SetConceptSpec(Loc, PrevSpec, DiagID);
3443 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3447 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
3448 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3451 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3454 case tok::kw___int64:
3455 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3458 case tok::kw_signed:
3459 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3462 case tok::kw_unsigned:
3463 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3466 case tok::kw__Complex:
3467 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3470 case tok::kw__Imaginary:
3471 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3475 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3479 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3483 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3486 case tok::kw___int128:
3487 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3491 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3495 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3498 case tok::kw_double:
3499 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3502 case tok::kw___float128:
3503 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3506 case tok::kw_wchar_t:
3507 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3510 case tok::kw_char16_t:
3511 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3514 case tok::kw_char32_t:
3515 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3520 if (Tok.is(tok::kw_bool) &&
3521 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3522 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3523 PrevSpec = ""; // Not used by the diagnostic.
3524 DiagID = diag::err_bool_redeclaration;
3525 // For better error recovery.
3526 Tok.setKind(tok::identifier);
3529 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3533 case tok::kw__Decimal32:
3534 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3537 case tok::kw__Decimal64:
3538 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3541 case tok::kw__Decimal128:
3542 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3545 case tok::kw___vector:
3546 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3548 case tok::kw___pixel:
3549 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3551 case tok::kw___bool:
3552 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3555 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3556 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3557 // support the "pipe" word as identifier.
3558 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3559 goto DoneWithDeclSpec;
3561 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3563 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
3564 case tok::kw_##ImgType##_t: \
3565 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3568 #include "clang/Basic/OpenCLImageTypes.def"
3569 case tok::kw___unknown_anytype:
3570 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3571 PrevSpec, DiagID, Policy);
3576 case tok::kw_struct:
3577 case tok::kw___interface:
3578 case tok::kw_union: {
3579 tok::TokenKind Kind = Tok.getKind();
3582 // These are attributes following class specifiers.
3583 // To produce better diagnostic, we parse them when
3584 // parsing class specifier.
3585 ParsedAttributesWithRange Attributes(AttrFactory);
3586 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3587 EnteringContext, DSContext, Attributes);
3589 // If there are attributes following class specifier,
3590 // take them over and handle them here.
3591 if (!Attributes.empty()) {
3592 AttrsLastTime = true;
3593 attrs.takeAllFrom(Attributes);
3601 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3606 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3609 case tok::kw_volatile:
3610 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3613 case tok::kw_restrict:
3614 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3618 // C++ typename-specifier:
3619 case tok::kw_typename:
3620 if (TryAnnotateTypeOrScopeToken()) {
3621 DS.SetTypeSpecError();
3622 goto DoneWithDeclSpec;
3624 if (!Tok.is(tok::kw_typename))
3628 // GNU typeof support.
3629 case tok::kw_typeof:
3630 ParseTypeofSpecifier(DS);
3633 case tok::annot_decltype:
3634 ParseDecltypeSpecifier(DS);
3637 case tok::annot_pragma_pack:
3641 case tok::annot_pragma_ms_pragma:
3642 HandlePragmaMSPragma();
3645 case tok::annot_pragma_ms_vtordisp:
3646 HandlePragmaMSVtorDisp();
3649 case tok::annot_pragma_ms_pointers_to_members:
3650 HandlePragmaMSPointersToMembers();
3653 case tok::kw___underlying_type:
3654 ParseUnderlyingTypeSpecifier(DS);
3657 case tok::kw__Atomic:
3659 // If the _Atomic keyword is immediately followed by a left parenthesis,
3660 // it is interpreted as a type specifier (with a type name), not as a
3662 if (NextToken().is(tok::l_paren)) {
3663 ParseAtomicSpecifier(DS);
3666 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3670 // OpenCL qualifiers:
3671 case tok::kw___generic:
3672 // generic address space is introduced only in OpenCL v2.0
3673 // see OpenCL C Spec v2.0 s6.5.5
3674 if (Actions.getLangOpts().OpenCLVersion < 200) {
3675 DiagID = diag::err_opencl_unknown_type_specifier;
3676 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3680 case tok::kw___private:
3681 case tok::kw___global:
3682 case tok::kw___local:
3683 case tok::kw___constant:
3684 case tok::kw___read_only:
3685 case tok::kw___write_only:
3686 case tok::kw___read_write:
3687 ParseOpenCLQualifiers(DS.getAttributes());
3691 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3692 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3693 // but we support it.
3694 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
3695 goto DoneWithDeclSpec;
3697 SourceLocation StartLoc = Tok.getLocation();
3698 SourceLocation EndLoc;
3699 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3700 if (Type.isUsable()) {
3701 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3702 PrevSpec, DiagID, Type.get(),
3703 Actions.getASTContext().getPrintingPolicy()))
3704 Diag(StartLoc, DiagID) << PrevSpec;
3706 DS.SetRangeEnd(EndLoc);
3708 DS.SetTypeSpecError();
3711 // Need to support trailing type qualifiers (e.g. "id<p> const").
3712 // If a type specifier follows, it will be diagnosed elsewhere.
3715 // If the specifier wasn't legal, issue a diagnostic.
3717 assert(PrevSpec && "Method did not return previous specifier!");
3720 if (DiagID == diag::ext_duplicate_declspec)
3722 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
3723 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
3724 const int OpenCLVer = getLangOpts().OpenCLVersion;
3725 std::string VerSpec = llvm::to_string(OpenCLVer / 100) +
3727 llvm::to_string((OpenCLVer % 100) / 10);
3728 Diag(Tok, DiagID) << VerSpec << PrevSpec << isStorageClass;
3730 Diag(Tok, DiagID) << PrevSpec;
3733 DS.SetRangeEnd(Tok.getLocation());
3734 if (DiagID != diag::err_bool_redeclaration)
3737 AttrsLastTime = false;
3741 /// ParseStructDeclaration - Parse a struct declaration without the terminating
3744 /// struct-declaration:
3745 /// specifier-qualifier-list struct-declarator-list
3746 /// [GNU] __extension__ struct-declaration
3747 /// [GNU] specifier-qualifier-list
3748 /// struct-declarator-list:
3749 /// struct-declarator
3750 /// struct-declarator-list ',' struct-declarator
3751 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3752 /// struct-declarator:
3754 /// [GNU] declarator attributes[opt]
3755 /// declarator[opt] ':' constant-expression
3756 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3758 void Parser::ParseStructDeclaration(
3759 ParsingDeclSpec &DS,
3760 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
3762 if (Tok.is(tok::kw___extension__)) {
3763 // __extension__ silences extension warnings in the subexpression.
3764 ExtensionRAIIObject O(Diags); // Use RAII to do this.
3766 return ParseStructDeclaration(DS, FieldsCallback);
3769 // Parse the common specifier-qualifiers-list piece.
3770 ParseSpecifierQualifierList(DS);
3772 // If there are no declarators, this is a free-standing declaration
3773 // specifier. Let the actions module cope with it.
3774 if (Tok.is(tok::semi)) {
3775 RecordDecl *AnonRecord = nullptr;
3776 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
3778 assert(!AnonRecord && "Did not expect anonymous struct or union here");
3779 DS.complete(TheDecl);
3783 // Read struct-declarators until we find the semicolon.
3784 bool FirstDeclarator = true;
3785 SourceLocation CommaLoc;
3787 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
3788 DeclaratorInfo.D.setCommaLoc(CommaLoc);
3790 // Attributes are only allowed here on successive declarators.
3791 if (!FirstDeclarator)
3792 MaybeParseGNUAttributes(DeclaratorInfo.D);
3794 /// struct-declarator: declarator
3795 /// struct-declarator: declarator[opt] ':' constant-expression
3796 if (Tok.isNot(tok::colon)) {
3797 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3798 ColonProtectionRAIIObject X(*this);
3799 ParseDeclarator(DeclaratorInfo.D);
3801 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
3803 if (TryConsumeToken(tok::colon)) {
3804 ExprResult Res(ParseConstantExpression());
3805 if (Res.isInvalid())
3806 SkipUntil(tok::semi, StopBeforeMatch);
3808 DeclaratorInfo.BitfieldSize = Res.get();
3811 // If attributes exist after the declarator, parse them.
3812 MaybeParseGNUAttributes(DeclaratorInfo.D);
3814 // We're done with this declarator; invoke the callback.
3815 FieldsCallback(DeclaratorInfo);
3817 // If we don't have a comma, it is either the end of the list (a ';')
3818 // or an error, bail out.
3819 if (!TryConsumeToken(tok::comma, CommaLoc))
3822 FirstDeclarator = false;
3826 /// ParseStructUnionBody
3827 /// struct-contents:
3828 /// struct-declaration-list
3830 /// [GNU] "struct-declaration-list" without terminatoring ';'
3831 /// struct-declaration-list:
3832 /// struct-declaration
3833 /// struct-declaration-list struct-declaration
3834 /// [OBC] '@' 'defs' '(' class-name ')'
3836 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
3837 unsigned TagType, Decl *TagDecl) {
3838 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3839 "parsing struct/union body");
3840 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
3842 BalancedDelimiterTracker T(*this, tok::l_brace);
3843 if (T.consumeOpen())
3846 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
3847 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3849 SmallVector<Decl *, 32> FieldDecls;
3851 // While we still have something to read, read the declarations in the struct.
3852 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3853 Tok.isNot(tok::eof)) {
3854 // Each iteration of this loop reads one struct-declaration.
3856 // Check for extraneous top-level semicolon.
3857 if (Tok.is(tok::semi)) {
3858 ConsumeExtraSemi(InsideStruct, TagType);
3862 // Parse _Static_assert declaration.
3863 if (Tok.is(tok::kw__Static_assert)) {
3864 SourceLocation DeclEnd;
3865 ParseStaticAssertDeclaration(DeclEnd);
3869 if (Tok.is(tok::annot_pragma_pack)) {
3874 if (Tok.is(tok::annot_pragma_align)) {
3875 HandlePragmaAlign();
3879 if (Tok.is(tok::annot_pragma_openmp)) {
3880 // Result can be ignored, because it must be always empty.
3881 AccessSpecifier AS = AS_none;
3882 ParsedAttributesWithRange Attrs(AttrFactory);
3883 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
3887 if (!Tok.is(tok::at)) {
3888 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
3889 // Install the declarator into the current TagDecl.
3891 Actions.ActOnField(getCurScope(), TagDecl,
3892 FD.D.getDeclSpec().getSourceRange().getBegin(),
3893 FD.D, FD.BitfieldSize);
3894 FieldDecls.push_back(Field);
3898 // Parse all the comma separated declarators.
3899 ParsingDeclSpec DS(*this);
3900 ParseStructDeclaration(DS, CFieldCallback);
3901 } else { // Handle @defs
3903 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
3904 Diag(Tok, diag::err_unexpected_at);
3905 SkipUntil(tok::semi);
3909 ExpectAndConsume(tok::l_paren);
3910 if (!Tok.is(tok::identifier)) {
3911 Diag(Tok, diag::err_expected) << tok::identifier;
3912 SkipUntil(tok::semi);
3915 SmallVector<Decl *, 16> Fields;
3916 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
3917 Tok.getIdentifierInfo(), Fields);
3918 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
3920 ExpectAndConsume(tok::r_paren);
3923 if (TryConsumeToken(tok::semi))
3926 if (Tok.is(tok::r_brace)) {
3927 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
3931 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
3932 // Skip to end of block or statement to avoid ext-warning on extra ';'.
3933 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
3934 // If we stopped at a ';', eat it.
3935 TryConsumeToken(tok::semi);
3940 ParsedAttributes attrs(AttrFactory);
3941 // If attributes exist after struct contents, parse them.
3942 MaybeParseGNUAttributes(attrs);
3944 Actions.ActOnFields(getCurScope(),
3945 RecordLoc, TagDecl, FieldDecls,
3946 T.getOpenLocation(), T.getCloseLocation(),
3949 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
3952 /// ParseEnumSpecifier
3953 /// enum-specifier: [C99 6.7.2.2]
3954 /// 'enum' identifier[opt] '{' enumerator-list '}'
3955 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
3956 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
3957 /// '}' attributes[opt]
3958 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
3960 /// 'enum' identifier
3961 /// [GNU] 'enum' attributes[opt] identifier
3963 /// [C++11] enum-head '{' enumerator-list[opt] '}'
3964 /// [C++11] enum-head '{' enumerator-list ',' '}'
3966 /// enum-head: [C++11]
3967 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
3968 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
3969 /// identifier enum-base[opt]
3971 /// enum-key: [C++11]
3976 /// enum-base: [C++11]
3977 /// ':' type-specifier-seq
3979 /// [C++] elaborated-type-specifier:
3980 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
3982 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
3983 const ParsedTemplateInfo &TemplateInfo,
3984 AccessSpecifier AS, DeclSpecContext DSC) {
3985 // Parse the tag portion of this.
3986 if (Tok.is(tok::code_completion)) {
3987 // Code completion for an enum name.
3988 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
3989 return cutOffParsing();
3992 // If attributes exist after tag, parse them.
3993 ParsedAttributesWithRange attrs(AttrFactory);
3994 MaybeParseGNUAttributes(attrs);
3995 MaybeParseCXX11Attributes(attrs);
3996 MaybeParseMicrosoftDeclSpecs(attrs);
3998 SourceLocation ScopedEnumKWLoc;
3999 bool IsScopedUsingClassTag = false;
4001 // In C++11, recognize 'enum class' and 'enum struct'.
4002 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4003 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4004 : diag::ext_scoped_enum);
4005 IsScopedUsingClassTag = Tok.is(tok::kw_class);
4006 ScopedEnumKWLoc = ConsumeToken();
4008 // Attributes are not allowed between these keywords. Diagnose,
4009 // but then just treat them like they appeared in the right place.
4010 ProhibitAttributes(attrs);
4012 // They are allowed afterwards, though.
4013 MaybeParseGNUAttributes(attrs);
4014 MaybeParseCXX11Attributes(attrs);
4015 MaybeParseMicrosoftDeclSpecs(attrs);
4018 // C++11 [temp.explicit]p12:
4019 // The usual access controls do not apply to names used to specify
4020 // explicit instantiations.
4021 // We extend this to also cover explicit specializations. Note that
4022 // we don't suppress if this turns out to be an elaborated type
4024 bool shouldDelayDiagsInTag =
4025 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4026 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4027 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4029 // Enum definitions should not be parsed in a trailing-return-type.
4030 bool AllowDeclaration = DSC != DSC_trailing;
4032 bool AllowFixedUnderlyingType = AllowDeclaration &&
4033 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
4034 getLangOpts().ObjC2);
4036 CXXScopeSpec &SS = DS.getTypeSpecScope();
4037 if (getLangOpts().CPlusPlus) {
4038 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4039 // if a fixed underlying type is allowed.
4040 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
4043 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
4044 /*EnteringContext=*/true))
4047 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4048 Diag(Tok, diag::err_expected) << tok::identifier;
4049 if (Tok.isNot(tok::l_brace)) {
4050 // Has no name and is not a definition.
4051 // Skip the rest of this declarator, up until the comma or semicolon.
4052 SkipUntil(tok::comma, StopAtSemi);
4060 // Must have either 'enum name' or 'enum {...}'.
4061 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4062 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
4063 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4065 // Skip the rest of this declarator, up until the comma or semicolon.
4066 SkipUntil(tok::comma, StopAtSemi);
4070 // If an identifier is present, consume and remember it.
4071 IdentifierInfo *Name = nullptr;
4072 SourceLocation NameLoc;
4073 if (Tok.is(tok::identifier)) {
4074 Name = Tok.getIdentifierInfo();
4075 NameLoc = ConsumeToken();
4078 if (!Name && ScopedEnumKWLoc.isValid()) {
4079 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4080 // declaration of a scoped enumeration.
4081 Diag(Tok, diag::err_scoped_enum_missing_identifier);
4082 ScopedEnumKWLoc = SourceLocation();
4083 IsScopedUsingClassTag = false;
4086 // Okay, end the suppression area. We'll decide whether to emit the
4087 // diagnostics in a second.
4088 if (shouldDelayDiagsInTag)
4089 diagsFromTag.done();
4091 TypeResult BaseType;
4093 // Parse the fixed underlying type.
4094 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4095 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
4096 bool PossibleBitfield = false;
4097 if (CanBeBitfield) {
4098 // If we're in class scope, this can either be an enum declaration with
4099 // an underlying type, or a declaration of a bitfield member. We try to
4100 // use a simple disambiguation scheme first to catch the common cases
4101 // (integer literal, sizeof); if it's still ambiguous, we then consider
4102 // anything that's a simple-type-specifier followed by '(' as an
4103 // expression. This suffices because function types are not valid
4104 // underlying types anyway.
4105 EnterExpressionEvaluationContext Unevaluated(
4106 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4107 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
4108 // If the next token starts an expression, we know we're parsing a
4109 // bit-field. This is the common case.
4110 if (TPR == TPResult::True)
4111 PossibleBitfield = true;
4112 // If the next token starts a type-specifier-seq, it may be either a
4113 // a fixed underlying type or the start of a function-style cast in C++;
4114 // lookahead one more token to see if it's obvious that we have a
4115 // fixed underlying type.
4116 else if (TPR == TPResult::False &&
4117 GetLookAheadToken(2).getKind() == tok::semi) {
4121 // We have the start of a type-specifier-seq, so we have to perform
4122 // tentative parsing to determine whether we have an expression or a
4124 TentativeParsingAction TPA(*this);
4129 // If we see a type specifier followed by an open-brace, we have an
4130 // ambiguity between an underlying type and a C++11 braced
4131 // function-style cast. Resolve this by always treating it as an
4133 // FIXME: The standard is not entirely clear on how to disambiguate in
4135 if ((getLangOpts().CPlusPlus &&
4136 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
4137 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
4138 // We'll parse this as a bitfield later.
4139 PossibleBitfield = true;
4142 // We have a type-specifier-seq.
4151 if (!PossibleBitfield) {
4153 BaseType = ParseTypeName(&Range);
4155 if (getLangOpts().CPlusPlus11) {
4156 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4157 } else if (!getLangOpts().ObjC2) {
4158 if (getLangOpts().CPlusPlus)
4159 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
4161 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
4166 // There are four options here. If we have 'friend enum foo;' then this is a
4167 // friend declaration, and cannot have an accompanying definition. If we have
4168 // 'enum foo;', then this is a forward declaration. If we have
4169 // 'enum foo {...' then this is a definition. Otherwise we have something
4170 // like 'enum foo xyz', a reference.
4172 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4173 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4174 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4176 Sema::TagUseKind TUK;
4177 if (!AllowDeclaration) {
4178 TUK = Sema::TUK_Reference;
4179 } else if (Tok.is(tok::l_brace)) {
4180 if (DS.isFriendSpecified()) {
4181 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4182 << SourceRange(DS.getFriendSpecLoc());
4184 SkipUntil(tok::r_brace, StopAtSemi);
4185 TUK = Sema::TUK_Friend;
4187 TUK = Sema::TUK_Definition;
4189 } else if (!isTypeSpecifier(DSC) &&
4190 (Tok.is(tok::semi) ||
4191 (Tok.isAtStartOfLine() &&
4192 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4193 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4194 if (Tok.isNot(tok::semi)) {
4195 // A semicolon was missing after this declaration. Diagnose and recover.
4196 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4198 Tok.setKind(tok::semi);
4201 TUK = Sema::TUK_Reference;
4204 // If this is an elaborated type specifier, and we delayed
4205 // diagnostics before, just merge them into the current pool.
4206 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4207 diagsFromTag.redelay();
4210 MultiTemplateParamsArg TParams;
4211 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4212 TUK != Sema::TUK_Reference) {
4213 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4214 // Skip the rest of this declarator, up until the comma or semicolon.
4215 Diag(Tok, diag::err_enum_template);
4216 SkipUntil(tok::comma, StopAtSemi);
4220 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4221 // Enumerations can't be explicitly instantiated.
4222 DS.SetTypeSpecError();
4223 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4227 assert(TemplateInfo.TemplateParams && "no template parameters");
4228 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4229 TemplateInfo.TemplateParams->size());
4232 if (TUK == Sema::TUK_Reference)
4233 ProhibitAttributes(attrs);
4235 if (!Name && TUK != Sema::TUK_Definition) {
4236 Diag(Tok, diag::err_enumerator_unnamed_no_def);
4238 // Skip the rest of this declarator, up until the comma or semicolon.
4239 SkipUntil(tok::comma, StopAtSemi);
4243 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4245 Sema::SkipBodyInfo SkipBody;
4246 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4247 NextToken().is(tok::identifier))
4248 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4249 NextToken().getIdentifierInfo(),
4250 NextToken().getLocation());
4253 bool IsDependent = false;
4254 const char *PrevSpec = nullptr;
4256 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
4257 StartLoc, SS, Name, NameLoc, attrs.getList(),
4258 AS, DS.getModulePrivateSpecLoc(), TParams,
4259 Owned, IsDependent, ScopedEnumKWLoc,
4260 IsScopedUsingClassTag, BaseType,
4261 DSC == DSC_type_specifier, &SkipBody);
4263 if (SkipBody.ShouldSkip) {
4264 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4266 BalancedDelimiterTracker T(*this, tok::l_brace);
4270 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4271 NameLoc.isValid() ? NameLoc : StartLoc,
4272 PrevSpec, DiagID, TagDecl, Owned,
4273 Actions.getASTContext().getPrintingPolicy()))
4274 Diag(StartLoc, DiagID) << PrevSpec;
4279 // This enum has a dependent nested-name-specifier. Handle it as a
4282 DS.SetTypeSpecError();
4283 Diag(Tok, diag::err_expected_type_name_after_typename);
4287 TypeResult Type = Actions.ActOnDependentTag(
4288 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4289 if (Type.isInvalid()) {
4290 DS.SetTypeSpecError();
4294 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4295 NameLoc.isValid() ? NameLoc : StartLoc,
4296 PrevSpec, DiagID, Type.get(),
4297 Actions.getASTContext().getPrintingPolicy()))
4298 Diag(StartLoc, DiagID) << PrevSpec;
4304 // The action failed to produce an enumeration tag. If this is a
4305 // definition, consume the entire definition.
4306 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4308 SkipUntil(tok::r_brace, StopAtSemi);
4311 DS.SetTypeSpecError();
4315 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference)
4316 ParseEnumBody(StartLoc, TagDecl);
4318 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4319 NameLoc.isValid() ? NameLoc : StartLoc,
4320 PrevSpec, DiagID, TagDecl, Owned,
4321 Actions.getASTContext().getPrintingPolicy()))
4322 Diag(StartLoc, DiagID) << PrevSpec;
4325 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4326 /// enumerator-list:
4328 /// enumerator-list ',' enumerator
4330 /// enumeration-constant attributes[opt]
4331 /// enumeration-constant attributes[opt] '=' constant-expression
4332 /// enumeration-constant:
4335 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4336 // Enter the scope of the enum body and start the definition.
4337 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4338 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4340 BalancedDelimiterTracker T(*this, tok::l_brace);
4343 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4344 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4345 Diag(Tok, diag::err_empty_enum);
4347 SmallVector<Decl *, 32> EnumConstantDecls;
4348 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4350 Decl *LastEnumConstDecl = nullptr;
4352 // Parse the enumerator-list.
4353 while (Tok.isNot(tok::r_brace)) {
4354 // Parse enumerator. If failed, try skipping till the start of the next
4355 // enumerator definition.
4356 if (Tok.isNot(tok::identifier)) {
4357 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4358 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4359 TryConsumeToken(tok::comma))
4363 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4364 SourceLocation IdentLoc = ConsumeToken();
4366 // If attributes exist after the enumerator, parse them.
4367 ParsedAttributesWithRange attrs(AttrFactory);
4368 MaybeParseGNUAttributes(attrs);
4369 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4370 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
4371 if (!getLangOpts().CPlusPlus1z)
4372 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
4373 << 1 /*enumerator*/;
4374 ParseCXX11Attributes(attrs);
4377 SourceLocation EqualLoc;
4378 ExprResult AssignedVal;
4379 EnumAvailabilityDiags.emplace_back(*this);
4381 if (TryConsumeToken(tok::equal, EqualLoc)) {
4382 AssignedVal = ParseConstantExpression();
4383 if (AssignedVal.isInvalid())
4384 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4387 // Install the enumerator constant into EnumDecl.
4388 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
4391 attrs.getList(), EqualLoc,
4393 EnumAvailabilityDiags.back().done();
4395 EnumConstantDecls.push_back(EnumConstDecl);
4396 LastEnumConstDecl = EnumConstDecl;
4398 if (Tok.is(tok::identifier)) {
4399 // We're missing a comma between enumerators.
4400 SourceLocation Loc = getEndOfPreviousToken();
4401 Diag(Loc, diag::err_enumerator_list_missing_comma)
4402 << FixItHint::CreateInsertion(Loc, ", ");
4406 // Emumerator definition must be finished, only comma or r_brace are
4408 SourceLocation CommaLoc;
4409 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4410 if (EqualLoc.isValid())
4411 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4414 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4415 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4416 if (TryConsumeToken(tok::comma, CommaLoc))
4423 // If comma is followed by r_brace, emit appropriate warning.
4424 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4425 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4426 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4427 diag::ext_enumerator_list_comma_cxx :
4428 diag::ext_enumerator_list_comma_c)
4429 << FixItHint::CreateRemoval(CommaLoc);
4430 else if (getLangOpts().CPlusPlus11)
4431 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4432 << FixItHint::CreateRemoval(CommaLoc);
4440 // If attributes exist after the identifier list, parse them.
4441 ParsedAttributes attrs(AttrFactory);
4442 MaybeParseGNUAttributes(attrs);
4444 Actions.ActOnEnumBody(StartLoc, T.getRange(),
4445 EnumDecl, EnumConstantDecls,
4449 // Now handle enum constant availability diagnostics.
4450 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4451 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4452 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4453 EnumAvailabilityDiags[i].redelay();
4454 PD.complete(EnumConstantDecls[i]);
4458 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4460 // The next token must be valid after an enum definition. If not, a ';'
4461 // was probably forgotten.
4462 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4463 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4464 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4465 // Push this token back into the preprocessor and change our current token
4466 // to ';' so that the rest of the code recovers as though there were an
4467 // ';' after the definition.
4469 Tok.setKind(tok::semi);
4473 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4474 /// is definitely a type-specifier. Return false if it isn't part of a type
4475 /// specifier or if we're not sure.
4476 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4477 switch (Tok.getKind()) {
4478 default: return false;
4482 case tok::kw___int64:
4483 case tok::kw___int128:
4484 case tok::kw_signed:
4485 case tok::kw_unsigned:
4486 case tok::kw__Complex:
4487 case tok::kw__Imaginary:
4490 case tok::kw_wchar_t:
4491 case tok::kw_char16_t:
4492 case tok::kw_char32_t:
4496 case tok::kw_double:
4497 case tok::kw___float128:
4500 case tok::kw__Decimal32:
4501 case tok::kw__Decimal64:
4502 case tok::kw__Decimal128:
4503 case tok::kw___vector:
4504 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4505 #include "clang/Basic/OpenCLImageTypes.def"
4507 // struct-or-union-specifier (C99) or class-specifier (C++)
4509 case tok::kw_struct:
4510 case tok::kw___interface:
4516 case tok::annot_typename:
4521 /// isTypeSpecifierQualifier - Return true if the current token could be the
4522 /// start of a specifier-qualifier-list.
4523 bool Parser::isTypeSpecifierQualifier() {
4524 switch (Tok.getKind()) {
4525 default: return false;
4527 case tok::identifier: // foo::bar
4528 if (TryAltiVecVectorToken())
4531 case tok::kw_typename: // typename T::type
4532 // Annotate typenames and C++ scope specifiers. If we get one, just
4533 // recurse to handle whatever we get.
4534 if (TryAnnotateTypeOrScopeToken())
4536 if (Tok.is(tok::identifier))
4538 return isTypeSpecifierQualifier();
4540 case tok::coloncolon: // ::foo::bar
4541 if (NextToken().is(tok::kw_new) || // ::new
4542 NextToken().is(tok::kw_delete)) // ::delete
4545 if (TryAnnotateTypeOrScopeToken())
4547 return isTypeSpecifierQualifier();
4549 // GNU attributes support.
4550 case tok::kw___attribute:
4551 // GNU typeof support.
4552 case tok::kw_typeof:
4557 case tok::kw___int64:
4558 case tok::kw___int128:
4559 case tok::kw_signed:
4560 case tok::kw_unsigned:
4561 case tok::kw__Complex:
4562 case tok::kw__Imaginary:
4565 case tok::kw_wchar_t:
4566 case tok::kw_char16_t:
4567 case tok::kw_char32_t:
4571 case tok::kw_double:
4572 case tok::kw___float128:
4575 case tok::kw__Decimal32:
4576 case tok::kw__Decimal64:
4577 case tok::kw__Decimal128:
4578 case tok::kw___vector:
4579 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4580 #include "clang/Basic/OpenCLImageTypes.def"
4582 // struct-or-union-specifier (C99) or class-specifier (C++)
4584 case tok::kw_struct:
4585 case tok::kw___interface:
4592 case tok::kw_volatile:
4593 case tok::kw_restrict:
4595 // Debugger support.
4596 case tok::kw___unknown_anytype:
4599 case tok::annot_typename:
4602 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4604 return getLangOpts().ObjC1;
4606 case tok::kw___cdecl:
4607 case tok::kw___stdcall:
4608 case tok::kw___fastcall:
4609 case tok::kw___thiscall:
4610 case tok::kw___regcall:
4611 case tok::kw___vectorcall:
4613 case tok::kw___ptr64:
4614 case tok::kw___ptr32:
4615 case tok::kw___pascal:
4616 case tok::kw___unaligned:
4618 case tok::kw__Nonnull:
4619 case tok::kw__Nullable:
4620 case tok::kw__Null_unspecified:
4622 case tok::kw___kindof:
4624 case tok::kw___private:
4625 case tok::kw___local:
4626 case tok::kw___global:
4627 case tok::kw___constant:
4628 case tok::kw___generic:
4629 case tok::kw___read_only:
4630 case tok::kw___read_write:
4631 case tok::kw___write_only:
4636 case tok::kw__Atomic:
4641 /// isDeclarationSpecifier() - Return true if the current token is part of a
4642 /// declaration specifier.
4644 /// \param DisambiguatingWithExpression True to indicate that the purpose of
4645 /// this check is to disambiguate between an expression and a declaration.
4646 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4647 switch (Tok.getKind()) {
4648 default: return false;
4651 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4653 case tok::identifier: // foo::bar
4654 // Unfortunate hack to support "Class.factoryMethod" notation.
4655 if (getLangOpts().ObjC1 && NextToken().is(tok::period))
4657 if (TryAltiVecVectorToken())
4660 case tok::kw_decltype: // decltype(T())::type
4661 case tok::kw_typename: // typename T::type
4662 // Annotate typenames and C++ scope specifiers. If we get one, just
4663 // recurse to handle whatever we get.
4664 if (TryAnnotateTypeOrScopeToken())
4666 if (Tok.is(tok::identifier))
4669 // If we're in Objective-C and we have an Objective-C class type followed
4670 // by an identifier and then either ':' or ']', in a place where an
4671 // expression is permitted, then this is probably a class message send
4672 // missing the initial '['. In this case, we won't consider this to be
4673 // the start of a declaration.
4674 if (DisambiguatingWithExpression &&
4675 isStartOfObjCClassMessageMissingOpenBracket())
4678 return isDeclarationSpecifier();
4680 case tok::coloncolon: // ::foo::bar
4681 if (NextToken().is(tok::kw_new) || // ::new
4682 NextToken().is(tok::kw_delete)) // ::delete
4685 // Annotate typenames and C++ scope specifiers. If we get one, just
4686 // recurse to handle whatever we get.
4687 if (TryAnnotateTypeOrScopeToken())
4689 return isDeclarationSpecifier();
4691 // storage-class-specifier
4692 case tok::kw_typedef:
4693 case tok::kw_extern:
4694 case tok::kw___private_extern__:
4695 case tok::kw_static:
4697 case tok::kw___auto_type:
4698 case tok::kw_register:
4699 case tok::kw___thread:
4700 case tok::kw_thread_local:
4701 case tok::kw__Thread_local:
4704 case tok::kw___module_private__:
4707 case tok::kw___unknown_anytype:
4712 case tok::kw___int64:
4713 case tok::kw___int128:
4714 case tok::kw_signed:
4715 case tok::kw_unsigned:
4716 case tok::kw__Complex:
4717 case tok::kw__Imaginary:
4720 case tok::kw_wchar_t:
4721 case tok::kw_char16_t:
4722 case tok::kw_char32_t:
4727 case tok::kw_double:
4728 case tok::kw___float128:
4731 case tok::kw__Decimal32:
4732 case tok::kw__Decimal64:
4733 case tok::kw__Decimal128:
4734 case tok::kw___vector:
4736 // struct-or-union-specifier (C99) or class-specifier (C++)
4738 case tok::kw_struct:
4740 case tok::kw___interface:
4746 case tok::kw_volatile:
4747 case tok::kw_restrict:
4749 // function-specifier
4750 case tok::kw_inline:
4751 case tok::kw_virtual:
4752 case tok::kw_explicit:
4753 case tok::kw__Noreturn:
4755 // alignment-specifier
4756 case tok::kw__Alignas:
4759 case tok::kw_friend:
4761 // static_assert-declaration
4762 case tok::kw__Static_assert:
4764 // GNU typeof support.
4765 case tok::kw_typeof:
4768 case tok::kw___attribute:
4770 // C++11 decltype and constexpr.
4771 case tok::annot_decltype:
4772 case tok::kw_constexpr:
4774 // C++ Concepts TS - concept
4775 case tok::kw_concept:
4778 case tok::kw__Atomic:
4781 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4783 return getLangOpts().ObjC1;
4786 case tok::annot_typename:
4787 return !DisambiguatingWithExpression ||
4788 !isStartOfObjCClassMessageMissingOpenBracket();
4790 case tok::kw___declspec:
4791 case tok::kw___cdecl:
4792 case tok::kw___stdcall:
4793 case tok::kw___fastcall:
4794 case tok::kw___thiscall:
4795 case tok::kw___regcall:
4796 case tok::kw___vectorcall:
4798 case tok::kw___sptr:
4799 case tok::kw___uptr:
4800 case tok::kw___ptr64:
4801 case tok::kw___ptr32:
4802 case tok::kw___forceinline:
4803 case tok::kw___pascal:
4804 case tok::kw___unaligned:
4806 case tok::kw__Nonnull:
4807 case tok::kw__Nullable:
4808 case tok::kw__Null_unspecified:
4810 case tok::kw___kindof:
4812 case tok::kw___private:
4813 case tok::kw___local:
4814 case tok::kw___global:
4815 case tok::kw___constant:
4816 case tok::kw___generic:
4817 case tok::kw___read_only:
4818 case tok::kw___read_write:
4819 case tok::kw___write_only:
4820 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4821 #include "clang/Basic/OpenCLImageTypes.def"
4827 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
4828 TentativeParsingAction TPA(*this);
4830 // Parse the C++ scope specifier.
4832 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
4833 /*EnteringContext=*/true)) {
4838 // Parse the constructor name.
4839 if (Tok.isOneOf(tok::identifier, tok::annot_template_id)) {
4840 // We already know that we have a constructor name; just consume
4848 // There may be attributes here, appertaining to the constructor name or type
4849 // we just stepped past.
4850 SkipCXX11Attributes();
4852 // Current class name must be followed by a left parenthesis.
4853 if (Tok.isNot(tok::l_paren)) {
4859 // A right parenthesis, or ellipsis followed by a right parenthesis signals
4860 // that we have a constructor.
4861 if (Tok.is(tok::r_paren) ||
4862 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
4867 // A C++11 attribute here signals that we have a constructor, and is an
4868 // attribute on the first constructor parameter.
4869 if (getLangOpts().CPlusPlus11 &&
4870 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
4871 /*OuterMightBeMessageSend*/ true)) {
4876 // If we need to, enter the specified scope.
4877 DeclaratorScopeObj DeclScopeObj(*this, SS);
4878 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
4879 DeclScopeObj.EnterDeclaratorScope();
4881 // Optionally skip Microsoft attributes.
4882 ParsedAttributes Attrs(AttrFactory);
4883 MaybeParseMicrosoftAttributes(Attrs);
4885 // Check whether the next token(s) are part of a declaration
4886 // specifier, in which case we have the start of a parameter and,
4887 // therefore, we know that this is a constructor.
4888 bool IsConstructor = false;
4889 if (isDeclarationSpecifier())
4890 IsConstructor = true;
4891 else if (Tok.is(tok::identifier) ||
4892 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
4893 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
4894 // This might be a parenthesized member name, but is more likely to
4895 // be a constructor declaration with an invalid argument type. Keep
4897 if (Tok.is(tok::annot_cxxscope))
4901 // If this is not a constructor, we must be parsing a declarator,
4902 // which must have one of the following syntactic forms (see the
4903 // grammar extract at the start of ParseDirectDeclarator):
4904 switch (Tok.getKind()) {
4909 // C(X [ [attribute]]);
4910 case tok::coloncolon:
4913 // Assume this isn't a constructor, rather than assuming it's a
4914 // constructor with an unnamed parameter of an ill-formed type.
4920 // Skip past the right-paren and any following attributes to get to
4921 // the function body or trailing-return-type.
4923 SkipCXX11Attributes();
4925 if (DeductionGuide) {
4926 // C(X) -> ... is a deduction guide.
4927 IsConstructor = Tok.is(tok::arrow);
4930 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
4931 // Assume these were meant to be constructors:
4932 // C(X) : (the name of a bit-field cannot be parenthesized).
4933 // C(X) try (this is otherwise ill-formed).
4934 IsConstructor = true;
4936 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
4937 // If we have a constructor name within the class definition,
4938 // assume these were meant to be constructors:
4941 // ... because otherwise we would be declaring a non-static data
4942 // member that is ill-formed because it's of the same type as its
4943 // surrounding class.
4945 // FIXME: We can actually do this whether or not the name is qualified,
4946 // because if it is qualified in this context it must be being used as
4947 // a constructor name.
4948 // currently, so we're somewhat conservative here.
4949 IsConstructor = IsUnqualified;
4954 IsConstructor = true;
4960 return IsConstructor;
4963 /// ParseTypeQualifierListOpt
4964 /// type-qualifier-list: [C99 6.7.5]
4966 /// [vendor] attributes
4967 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
4968 /// type-qualifier-list type-qualifier
4969 /// [vendor] type-qualifier-list attributes
4970 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
4971 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
4972 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
4973 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
4974 /// AttrRequirements bitmask values.
4975 void Parser::ParseTypeQualifierListOpt(
4976 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
4977 bool IdentifierRequired,
4978 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
4979 if (getLangOpts().CPlusPlus11 && (AttrReqs & AR_CXX11AttributesParsed) &&
4980 isCXX11AttributeSpecifier()) {
4981 ParsedAttributesWithRange attrs(AttrFactory);
4982 ParseCXX11Attributes(attrs);
4983 DS.takeAttributesFrom(attrs);
4986 SourceLocation EndLoc;
4989 bool isInvalid = false;
4990 const char *PrevSpec = nullptr;
4991 unsigned DiagID = 0;
4992 SourceLocation Loc = Tok.getLocation();
4994 switch (Tok.getKind()) {
4995 case tok::code_completion:
4996 if (CodeCompletionHandler)
4997 (*CodeCompletionHandler)();
4999 Actions.CodeCompleteTypeQualifiers(DS);
5000 return cutOffParsing();
5003 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
5006 case tok::kw_volatile:
5007 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5010 case tok::kw_restrict:
5011 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5014 case tok::kw__Atomic:
5016 goto DoneWithTypeQuals;
5017 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5021 // OpenCL qualifiers:
5022 case tok::kw___private:
5023 case tok::kw___global:
5024 case tok::kw___local:
5025 case tok::kw___constant:
5026 case tok::kw___generic:
5027 case tok::kw___read_only:
5028 case tok::kw___write_only:
5029 case tok::kw___read_write:
5030 ParseOpenCLQualifiers(DS.getAttributes());
5033 case tok::kw___unaligned:
5034 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5037 case tok::kw___uptr:
5038 // GNU libc headers in C mode use '__uptr' as an identifer which conflicts
5039 // with the MS modifier keyword.
5040 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
5041 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5042 if (TryKeywordIdentFallback(false))
5045 case tok::kw___sptr:
5047 case tok::kw___ptr64:
5048 case tok::kw___ptr32:
5049 case tok::kw___cdecl:
5050 case tok::kw___stdcall:
5051 case tok::kw___fastcall:
5052 case tok::kw___thiscall:
5053 case tok::kw___regcall:
5054 case tok::kw___vectorcall:
5055 if (AttrReqs & AR_DeclspecAttributesParsed) {
5056 ParseMicrosoftTypeAttributes(DS.getAttributes());
5059 goto DoneWithTypeQuals;
5060 case tok::kw___pascal:
5061 if (AttrReqs & AR_VendorAttributesParsed) {
5062 ParseBorlandTypeAttributes(DS.getAttributes());
5065 goto DoneWithTypeQuals;
5067 // Nullability type specifiers.
5068 case tok::kw__Nonnull:
5069 case tok::kw__Nullable:
5070 case tok::kw__Null_unspecified:
5071 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5074 // Objective-C 'kindof' types.
5075 case tok::kw___kindof:
5076 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
5077 nullptr, 0, AttributeList::AS_Keyword);
5078 (void)ConsumeToken();
5081 case tok::kw___attribute:
5082 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5083 // When GNU attributes are expressly forbidden, diagnose their usage.
5084 Diag(Tok, diag::err_attributes_not_allowed);
5086 // Parse the attributes even if they are rejected to ensure that error
5087 // recovery is graceful.
5088 if (AttrReqs & AR_GNUAttributesParsed ||
5089 AttrReqs & AR_GNUAttributesParsedAndRejected) {
5090 ParseGNUAttributes(DS.getAttributes());
5091 continue; // do *not* consume the next token!
5093 // otherwise, FALL THROUGH!
5096 // If this is not a type-qualifier token, we're done reading type
5097 // qualifiers. First verify that DeclSpec's are consistent.
5098 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
5099 if (EndLoc.isValid())
5100 DS.SetRangeEnd(EndLoc);
5104 // If the specifier combination wasn't legal, issue a diagnostic.
5106 assert(PrevSpec && "Method did not return previous specifier!");
5107 Diag(Tok, DiagID) << PrevSpec;
5109 EndLoc = ConsumeToken();
5113 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
5115 void Parser::ParseDeclarator(Declarator &D) {
5116 /// This implements the 'declarator' production in the C grammar, then checks
5117 /// for well-formedness and issues diagnostics.
5118 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5121 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
5122 unsigned TheContext) {
5123 if (Kind == tok::star || Kind == tok::caret)
5126 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
5129 if (!Lang.CPlusPlus)
5132 if (Kind == tok::amp)
5135 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5136 // But we must not parse them in conversion-type-ids and new-type-ids, since
5137 // those can be legitimately followed by a && operator.
5138 // (The same thing can in theory happen after a trailing-return-type, but
5139 // since those are a C++11 feature, there is no rejects-valid issue there.)
5140 if (Kind == tok::ampamp)
5141 return Lang.CPlusPlus11 || (TheContext != Declarator::ConversionIdContext &&
5142 TheContext != Declarator::CXXNewContext);
5147 // Indicates whether the given declarator is a pipe declarator.
5148 static bool isPipeDeclerator(const Declarator &D) {
5149 const unsigned NumTypes = D.getNumTypeObjects();
5151 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5152 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5158 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5159 /// is parsed by the function passed to it. Pass null, and the direct-declarator
5160 /// isn't parsed at all, making this function effectively parse the C++
5161 /// ptr-operator production.
5163 /// If the grammar of this construct is extended, matching changes must also be
5164 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5165 /// isConstructorDeclarator.
5167 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5168 /// [C] pointer[opt] direct-declarator
5169 /// [C++] direct-declarator
5170 /// [C++] ptr-operator declarator
5172 /// pointer: [C99 6.7.5]
5173 /// '*' type-qualifier-list[opt]
5174 /// '*' type-qualifier-list[opt] pointer
5177 /// '*' cv-qualifier-seq[opt]
5180 /// [GNU] '&' restrict[opt] attributes[opt]
5181 /// [GNU?] '&&' restrict[opt] attributes[opt]
5182 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
5183 void Parser::ParseDeclaratorInternal(Declarator &D,
5184 DirectDeclParseFunction DirectDeclParser) {
5185 if (Diags.hasAllExtensionsSilenced())
5188 // C++ member pointers start with a '::' or a nested-name.
5189 // Member pointers get special handling, since there's no place for the
5190 // scope spec in the generic path below.
5191 if (getLangOpts().CPlusPlus &&
5192 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
5193 (Tok.is(tok::identifier) &&
5194 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
5195 Tok.is(tok::annot_cxxscope))) {
5196 bool EnteringContext = D.getContext() == Declarator::FileContext ||
5197 D.getContext() == Declarator::MemberContext;
5199 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
5201 if (SS.isNotEmpty()) {
5202 if (Tok.isNot(tok::star)) {
5203 // The scope spec really belongs to the direct-declarator.
5204 if (D.mayHaveIdentifier())
5205 D.getCXXScopeSpec() = SS;
5207 AnnotateScopeToken(SS, true);
5209 if (DirectDeclParser)
5210 (this->*DirectDeclParser)(D);
5214 SourceLocation Loc = ConsumeToken();
5216 DeclSpec DS(AttrFactory);
5217 ParseTypeQualifierListOpt(DS);
5218 D.ExtendWithDeclSpec(DS);
5220 // Recurse to parse whatever is left.
5221 ParseDeclaratorInternal(D, DirectDeclParser);
5223 // Sema will have to catch (syntactically invalid) pointers into global
5224 // scope. It has to catch pointers into namespace scope anyway.
5225 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
5228 /* Don't replace range end. */SourceLocation());
5233 tok::TokenKind Kind = Tok.getKind();
5235 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
5236 DeclSpec DS(AttrFactory);
5237 ParseTypeQualifierListOpt(DS);
5240 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
5241 DS.getAttributes(), SourceLocation());
5244 // Not a pointer, C++ reference, or block.
5245 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
5246 if (DirectDeclParser)
5247 (this->*DirectDeclParser)(D);
5251 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5252 // '&&' -> rvalue reference
5253 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
5256 if (Kind == tok::star || Kind == tok::caret) {
5258 DeclSpec DS(AttrFactory);
5260 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5261 // C++11 attributes are allowed.
5262 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
5263 ((D.getContext() != Declarator::CXXNewContext)
5264 ? AR_GNUAttributesParsed
5265 : AR_GNUAttributesParsedAndRejected);
5266 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
5267 D.ExtendWithDeclSpec(DS);
5269 // Recursively parse the declarator.
5270 ParseDeclaratorInternal(D, DirectDeclParser);
5271 if (Kind == tok::star)
5272 // Remember that we parsed a pointer type, and remember the type-quals.
5273 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
5274 DS.getConstSpecLoc(),
5275 DS.getVolatileSpecLoc(),
5276 DS.getRestrictSpecLoc(),
5277 DS.getAtomicSpecLoc(),
5278 DS.getUnalignedSpecLoc()),
5282 // Remember that we parsed a Block type, and remember the type-quals.
5283 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
5289 DeclSpec DS(AttrFactory);
5291 // Complain about rvalue references in C++03, but then go on and build
5293 if (Kind == tok::ampamp)
5294 Diag(Loc, getLangOpts().CPlusPlus11 ?
5295 diag::warn_cxx98_compat_rvalue_reference :
5296 diag::ext_rvalue_reference);
5298 // GNU-style and C++11 attributes are allowed here, as is restrict.
5299 ParseTypeQualifierListOpt(DS);
5300 D.ExtendWithDeclSpec(DS);
5302 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5303 // cv-qualifiers are introduced through the use of a typedef or of a
5304 // template type argument, in which case the cv-qualifiers are ignored.
5305 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5306 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5307 Diag(DS.getConstSpecLoc(),
5308 diag::err_invalid_reference_qualifier_application) << "const";
5309 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5310 Diag(DS.getVolatileSpecLoc(),
5311 diag::err_invalid_reference_qualifier_application) << "volatile";
5312 // 'restrict' is permitted as an extension.
5313 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5314 Diag(DS.getAtomicSpecLoc(),
5315 diag::err_invalid_reference_qualifier_application) << "_Atomic";
5318 // Recursively parse the declarator.
5319 ParseDeclaratorInternal(D, DirectDeclParser);
5321 if (D.getNumTypeObjects() > 0) {
5322 // C++ [dcl.ref]p4: There shall be no references to references.
5323 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5324 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5325 if (const IdentifierInfo *II = D.getIdentifier())
5326 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5329 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5332 // Once we've complained about the reference-to-reference, we
5333 // can go ahead and build the (technically ill-formed)
5334 // declarator: reference collapsing will take care of it.
5338 // Remember that we parsed a reference type.
5339 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
5346 // When correcting from misplaced brackets before the identifier, the location
5347 // is saved inside the declarator so that other diagnostic messages can use
5348 // them. This extracts and returns that location, or returns the provided
5349 // location if a stored location does not exist.
5350 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5351 SourceLocation Loc) {
5352 if (D.getName().StartLocation.isInvalid() &&
5353 D.getName().EndLocation.isValid())
5354 return D.getName().EndLocation;
5359 /// ParseDirectDeclarator
5360 /// direct-declarator: [C99 6.7.5]
5361 /// [C99] identifier
5362 /// '(' declarator ')'
5363 /// [GNU] '(' attributes declarator ')'
5364 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5365 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5366 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5367 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5368 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5369 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5370 /// attribute-specifier-seq[opt]
5371 /// direct-declarator '(' parameter-type-list ')'
5372 /// direct-declarator '(' identifier-list[opt] ')'
5373 /// [GNU] direct-declarator '(' parameter-forward-declarations
5374 /// parameter-type-list[opt] ')'
5375 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
5376 /// cv-qualifier-seq[opt] exception-specification[opt]
5377 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5378 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5379 /// ref-qualifier[opt] exception-specification[opt]
5380 /// [C++] declarator-id
5381 /// [C++11] declarator-id attribute-specifier-seq[opt]
5383 /// declarator-id: [C++ 8]
5384 /// '...'[opt] id-expression
5385 /// '::'[opt] nested-name-specifier[opt] type-name
5387 /// id-expression: [C++ 5.1]
5391 /// unqualified-id: [C++ 5.1]
5393 /// operator-function-id
5394 /// conversion-function-id
5398 /// C++17 adds the following, which we also handle here:
5400 /// simple-declaration:
5401 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5403 /// Note, any additional constructs added here may need corresponding changes
5404 /// in isConstructorDeclarator.
5405 void Parser::ParseDirectDeclarator(Declarator &D) {
5406 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
5408 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
5409 // This might be a C++17 structured binding.
5410 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5411 D.getCXXScopeSpec().isEmpty())
5412 return ParseDecompositionDeclarator(D);
5414 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5415 // this context it is a bitfield. Also in range-based for statement colon
5416 // may delimit for-range-declaration.
5417 ColonProtectionRAIIObject X(*this,
5418 D.getContext() == Declarator::MemberContext ||
5419 (D.getContext() == Declarator::ForContext &&
5420 getLangOpts().CPlusPlus11));
5422 // ParseDeclaratorInternal might already have parsed the scope.
5423 if (D.getCXXScopeSpec().isEmpty()) {
5424 bool EnteringContext = D.getContext() == Declarator::FileContext ||
5425 D.getContext() == Declarator::MemberContext;
5426 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
5430 if (D.getCXXScopeSpec().isValid()) {
5431 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5432 D.getCXXScopeSpec()))
5433 // Change the declaration context for name lookup, until this function
5434 // is exited (and the declarator has been parsed).
5435 DeclScopeObj.EnterDeclaratorScope();
5436 else if (getObjCDeclContext()) {
5437 // Ensure that we don't interpret the next token as an identifier when
5438 // dealing with declarations in an Objective-C container.
5439 D.SetIdentifier(nullptr, Tok.getLocation());
5440 D.setInvalidType(true);
5442 goto PastIdentifier;
5446 // C++0x [dcl.fct]p14:
5447 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5448 // parameter-declaration-clause without a preceding comma. In this case,
5449 // the ellipsis is parsed as part of the abstract-declarator if the type
5450 // of the parameter either names a template parameter pack that has not
5451 // been expanded or contains auto; otherwise, it is parsed as part of the
5452 // parameter-declaration-clause.
5453 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
5454 !((D.getContext() == Declarator::PrototypeContext ||
5455 D.getContext() == Declarator::LambdaExprParameterContext ||
5456 D.getContext() == Declarator::BlockLiteralContext) &&
5457 NextToken().is(tok::r_paren) &&
5458 !D.hasGroupingParens() &&
5459 !Actions.containsUnexpandedParameterPacks(D) &&
5460 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
5461 SourceLocation EllipsisLoc = ConsumeToken();
5462 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
5463 // The ellipsis was put in the wrong place. Recover, and explain to
5464 // the user what they should have done.
5466 if (EllipsisLoc.isValid())
5467 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5470 D.setEllipsisLoc(EllipsisLoc);
5472 // The ellipsis can't be followed by a parenthesized declarator. We
5473 // check for that in ParseParenDeclarator, after we have disambiguated
5474 // the l_paren token.
5477 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5479 // We found something that indicates the start of an unqualified-id.
5480 // Parse that unqualified-id.
5481 bool AllowConstructorName;
5482 bool AllowDeductionGuide;
5483 if (D.getDeclSpec().hasTypeSpecifier()) {
5484 AllowConstructorName = false;
5485 AllowDeductionGuide = false;
5486 } else if (D.getCXXScopeSpec().isSet()) {
5487 AllowConstructorName =
5488 (D.getContext() == Declarator::FileContext ||
5489 D.getContext() == Declarator::MemberContext);
5490 AllowDeductionGuide = false;
5492 AllowConstructorName = (D.getContext() == Declarator::MemberContext);
5493 AllowDeductionGuide =
5494 (D.getContext() == Declarator::FileContext ||
5495 D.getContext() == Declarator::MemberContext);
5498 SourceLocation TemplateKWLoc;
5499 bool HadScope = D.getCXXScopeSpec().isValid();
5500 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5501 /*EnteringContext=*/true,
5502 /*AllowDestructorName=*/true, AllowConstructorName,
5503 AllowDeductionGuide, nullptr, TemplateKWLoc,
5505 // Once we're past the identifier, if the scope was bad, mark the
5506 // whole declarator bad.
5507 D.getCXXScopeSpec().isInvalid()) {
5508 D.SetIdentifier(nullptr, Tok.getLocation());
5509 D.setInvalidType(true);
5511 // ParseUnqualifiedId might have parsed a scope specifier during error
5512 // recovery. If it did so, enter that scope.
5513 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5514 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5515 D.getCXXScopeSpec()))
5516 DeclScopeObj.EnterDeclaratorScope();
5518 // Parsed the unqualified-id; update range information and move along.
5519 if (D.getSourceRange().getBegin().isInvalid())
5520 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5521 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
5523 goto PastIdentifier;
5526 if (D.getCXXScopeSpec().isNotEmpty()) {
5527 // We have a scope specifier but no following unqualified-id.
5528 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5529 diag::err_expected_unqualified_id)
5531 D.SetIdentifier(nullptr, Tok.getLocation());
5532 goto PastIdentifier;
5534 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
5535 assert(!getLangOpts().CPlusPlus &&
5536 "There's a C++-specific check for tok::identifier above");
5537 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5538 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5539 D.SetRangeEnd(Tok.getLocation());
5541 goto PastIdentifier;
5542 } else if (Tok.is(tok::identifier) && D.diagnoseIdentifier()) {
5543 // A virt-specifier isn't treated as an identifier if it appears after a
5544 // trailing-return-type.
5545 if (D.getContext() != Declarator::TrailingReturnContext ||
5546 !isCXX11VirtSpecifier(Tok)) {
5547 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5548 << FixItHint::CreateRemoval(Tok.getLocation());
5549 D.SetIdentifier(nullptr, Tok.getLocation());
5551 goto PastIdentifier;
5555 if (Tok.is(tok::l_paren)) {
5556 // direct-declarator: '(' declarator ')'
5557 // direct-declarator: '(' attributes declarator ')'
5558 // Example: 'char (*X)' or 'int (*XX)(void)'
5559 ParseParenDeclarator(D);
5561 // If the declarator was parenthesized, we entered the declarator
5562 // scope when parsing the parenthesized declarator, then exited
5563 // the scope already. Re-enter the scope, if we need to.
5564 if (D.getCXXScopeSpec().isSet()) {
5565 // If there was an error parsing parenthesized declarator, declarator
5566 // scope may have been entered before. Don't do it again.
5567 if (!D.isInvalidType() &&
5568 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5569 D.getCXXScopeSpec()))
5570 // Change the declaration context for name lookup, until this function
5571 // is exited (and the declarator has been parsed).
5572 DeclScopeObj.EnterDeclaratorScope();
5574 } else if (D.mayOmitIdentifier()) {
5575 // This could be something simple like "int" (in which case the declarator
5576 // portion is empty), if an abstract-declarator is allowed.
5577 D.SetIdentifier(nullptr, Tok.getLocation());
5579 // The grammar for abstract-pack-declarator does not allow grouping parens.
5580 // FIXME: Revisit this once core issue 1488 is resolved.
5581 if (D.hasEllipsis() && D.hasGroupingParens())
5582 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5583 diag::ext_abstract_pack_declarator_parens);
5585 if (Tok.getKind() == tok::annot_pragma_parser_crash)
5587 if (Tok.is(tok::l_square))
5588 return ParseMisplacedBracketDeclarator(D);
5589 if (D.getContext() == Declarator::MemberContext) {
5590 // Objective-C++: Detect C++ keywords and try to prevent further errors by
5591 // treating these keyword as valid member names.
5592 if (getLangOpts().ObjC1 && getLangOpts().CPlusPlus &&
5593 Tok.getIdentifierInfo() &&
5594 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5595 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5596 diag::err_expected_member_name_or_semi_objcxx_keyword)
5597 << Tok.getIdentifierInfo()
5598 << (D.getDeclSpec().isEmpty() ? SourceRange()
5599 : D.getDeclSpec().getSourceRange());
5600 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5601 D.SetRangeEnd(Tok.getLocation());
5603 goto PastIdentifier;
5605 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5606 diag::err_expected_member_name_or_semi)
5607 << (D.getDeclSpec().isEmpty() ? SourceRange()
5608 : D.getDeclSpec().getSourceRange());
5609 } else if (getLangOpts().CPlusPlus) {
5610 if (Tok.isOneOf(tok::period, tok::arrow))
5611 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
5613 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5614 if (Tok.isAtStartOfLine() && Loc.isValid())
5615 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5616 << getLangOpts().CPlusPlus;
5618 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5619 diag::err_expected_unqualified_id)
5620 << getLangOpts().CPlusPlus;
5623 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5624 diag::err_expected_either)
5625 << tok::identifier << tok::l_paren;
5627 D.SetIdentifier(nullptr, Tok.getLocation());
5628 D.setInvalidType(true);
5632 assert(D.isPastIdentifier() &&
5633 "Haven't past the location of the identifier yet?");
5635 // Don't parse attributes unless we have parsed an unparenthesized name.
5636 if (D.hasName() && !D.getNumTypeObjects())
5637 MaybeParseCXX11Attributes(D);
5640 if (Tok.is(tok::l_paren)) {
5641 // Enter function-declaration scope, limiting any declarators to the
5642 // function prototype scope, including parameter declarators.
5643 ParseScope PrototypeScope(this,
5644 Scope::FunctionPrototypeScope|Scope::DeclScope|
5645 (D.isFunctionDeclaratorAFunctionDeclaration()
5646 ? Scope::FunctionDeclarationScope : 0));
5648 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5649 // In such a case, check if we actually have a function declarator; if it
5650 // is not, the declarator has been fully parsed.
5651 bool IsAmbiguous = false;
5652 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5653 // The name of the declarator, if any, is tentatively declared within
5654 // a possible direct initializer.
5655 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5656 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5657 TentativelyDeclaredIdentifiers.pop_back();
5658 if (!IsFunctionDecl)
5661 ParsedAttributes attrs(AttrFactory);
5662 BalancedDelimiterTracker T(*this, tok::l_paren);
5664 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
5665 PrototypeScope.Exit();
5666 } else if (Tok.is(tok::l_square)) {
5667 ParseBracketDeclarator(D);
5674 void Parser::ParseDecompositionDeclarator(Declarator &D) {
5675 assert(Tok.is(tok::l_square));
5677 // If this doesn't look like a structured binding, maybe it's a misplaced
5678 // array declarator.
5679 // FIXME: Consume the l_square first so we don't need extra lookahead for
5681 if (!(NextToken().is(tok::identifier) &&
5682 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5683 !(NextToken().is(tok::r_square) &&
5684 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5685 return ParseMisplacedBracketDeclarator(D);
5687 BalancedDelimiterTracker T(*this, tok::l_square);
5690 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5691 while (Tok.isNot(tok::r_square)) {
5692 if (!Bindings.empty()) {
5693 if (Tok.is(tok::comma))
5696 if (Tok.is(tok::identifier)) {
5697 SourceLocation EndLoc = getEndOfPreviousToken();
5698 Diag(EndLoc, diag::err_expected)
5699 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
5701 Diag(Tok, diag::err_expected_comma_or_rsquare);
5704 SkipUntil(tok::r_square, tok::comma, tok::identifier,
5705 StopAtSemi | StopBeforeMatch);
5706 if (Tok.is(tok::comma))
5708 else if (Tok.isNot(tok::identifier))
5713 if (Tok.isNot(tok::identifier)) {
5714 Diag(Tok, diag::err_expected) << tok::identifier;
5718 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
5722 if (Tok.isNot(tok::r_square))
5723 // We've already diagnosed a problem here.
5726 // C++17 does not allow the identifier-list in a structured binding
5728 if (Bindings.empty())
5729 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
5734 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
5735 T.getCloseLocation());
5738 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
5739 /// only called before the identifier, so these are most likely just grouping
5740 /// parens for precedence. If we find that these are actually function
5741 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5743 /// direct-declarator:
5744 /// '(' declarator ')'
5745 /// [GNU] '(' attributes declarator ')'
5746 /// direct-declarator '(' parameter-type-list ')'
5747 /// direct-declarator '(' identifier-list[opt] ')'
5748 /// [GNU] direct-declarator '(' parameter-forward-declarations
5749 /// parameter-type-list[opt] ')'
5751 void Parser::ParseParenDeclarator(Declarator &D) {
5752 BalancedDelimiterTracker T(*this, tok::l_paren);
5755 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
5757 // Eat any attributes before we look at whether this is a grouping or function
5758 // declarator paren. If this is a grouping paren, the attribute applies to
5759 // the type being built up, for example:
5760 // int (__attribute__(()) *x)(long y)
5761 // If this ends up not being a grouping paren, the attribute applies to the
5762 // first argument, for example:
5763 // int (__attribute__(()) int x)
5764 // In either case, we need to eat any attributes to be able to determine what
5765 // sort of paren this is.
5767 ParsedAttributes attrs(AttrFactory);
5768 bool RequiresArg = false;
5769 if (Tok.is(tok::kw___attribute)) {
5770 ParseGNUAttributes(attrs);
5772 // We require that the argument list (if this is a non-grouping paren) be
5773 // present even if the attribute list was empty.
5777 // Eat any Microsoft extensions.
5778 ParseMicrosoftTypeAttributes(attrs);
5780 // Eat any Borland extensions.
5781 if (Tok.is(tok::kw___pascal))
5782 ParseBorlandTypeAttributes(attrs);
5784 // If we haven't past the identifier yet (or where the identifier would be
5785 // stored, if this is an abstract declarator), then this is probably just
5786 // grouping parens. However, if this could be an abstract-declarator, then
5787 // this could also be the start of function arguments (consider 'void()').
5790 if (!D.mayOmitIdentifier()) {
5791 // If this can't be an abstract-declarator, this *must* be a grouping
5792 // paren, because we haven't seen the identifier yet.
5794 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
5795 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
5796 NextToken().is(tok::r_paren)) || // C++ int(...)
5797 isDeclarationSpecifier() || // 'int(int)' is a function.
5798 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
5799 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
5800 // considered to be a type, not a K&R identifier-list.
5803 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
5807 // If this is a grouping paren, handle:
5808 // direct-declarator: '(' declarator ')'
5809 // direct-declarator: '(' attributes declarator ')'
5811 SourceLocation EllipsisLoc = D.getEllipsisLoc();
5812 D.setEllipsisLoc(SourceLocation());
5814 bool hadGroupingParens = D.hasGroupingParens();
5815 D.setGroupingParens(true);
5816 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5819 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
5820 T.getCloseLocation()),
5821 attrs, T.getCloseLocation());
5823 D.setGroupingParens(hadGroupingParens);
5825 // An ellipsis cannot be placed outside parentheses.
5826 if (EllipsisLoc.isValid())
5827 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5832 // Okay, if this wasn't a grouping paren, it must be the start of a function
5833 // argument list. Recognize that this declarator will never have an
5834 // identifier (and remember where it would have been), then call into
5835 // ParseFunctionDeclarator to handle of argument list.
5836 D.SetIdentifier(nullptr, Tok.getLocation());
5838 // Enter function-declaration scope, limiting any declarators to the
5839 // function prototype scope, including parameter declarators.
5840 ParseScope PrototypeScope(this,
5841 Scope::FunctionPrototypeScope | Scope::DeclScope |
5842 (D.isFunctionDeclaratorAFunctionDeclaration()
5843 ? Scope::FunctionDeclarationScope : 0));
5844 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
5845 PrototypeScope.Exit();
5848 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
5849 /// declarator D up to a paren, which indicates that we are parsing function
5852 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
5853 /// immediately after the open paren - they should be considered to be the
5854 /// first argument of a parameter.
5856 /// If RequiresArg is true, then the first argument of the function is required
5857 /// to be present and required to not be an identifier list.
5859 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
5860 /// (C++11) ref-qualifier[opt], exception-specification[opt],
5861 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
5863 /// [C++11] exception-specification:
5864 /// dynamic-exception-specification
5865 /// noexcept-specification
5867 void Parser::ParseFunctionDeclarator(Declarator &D,
5868 ParsedAttributes &FirstArgAttrs,
5869 BalancedDelimiterTracker &Tracker,
5872 assert(getCurScope()->isFunctionPrototypeScope() &&
5873 "Should call from a Function scope");
5874 // lparen is already consumed!
5875 assert(D.isPastIdentifier() && "Should not call before identifier!");
5877 // This should be true when the function has typed arguments.
5878 // Otherwise, it is treated as a K&R-style function.
5879 bool HasProto = false;
5880 // Build up an array of information about the parsed arguments.
5881 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
5882 // Remember where we see an ellipsis, if any.
5883 SourceLocation EllipsisLoc;
5885 DeclSpec DS(AttrFactory);
5886 bool RefQualifierIsLValueRef = true;
5887 SourceLocation RefQualifierLoc;
5888 SourceLocation ConstQualifierLoc;
5889 SourceLocation VolatileQualifierLoc;
5890 SourceLocation RestrictQualifierLoc;
5891 ExceptionSpecificationType ESpecType = EST_None;
5892 SourceRange ESpecRange;
5893 SmallVector<ParsedType, 2> DynamicExceptions;
5894 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5895 ExprResult NoexceptExpr;
5896 CachedTokens *ExceptionSpecTokens = nullptr;
5897 ParsedAttributes FnAttrs(AttrFactory);
5898 TypeResult TrailingReturnType;
5900 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
5901 EndLoc is the end location for the function declarator.
5902 They differ for trailing return types. */
5903 SourceLocation StartLoc, LocalEndLoc, EndLoc;
5904 SourceLocation LParenLoc, RParenLoc;
5905 LParenLoc = Tracker.getOpenLocation();
5906 StartLoc = LParenLoc;
5908 if (isFunctionDeclaratorIdentifierList()) {
5910 Diag(Tok, diag::err_argument_required_after_attribute);
5912 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
5914 Tracker.consumeClose();
5915 RParenLoc = Tracker.getCloseLocation();
5916 LocalEndLoc = RParenLoc;
5919 if (Tok.isNot(tok::r_paren))
5920 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
5922 else if (RequiresArg)
5923 Diag(Tok, diag::err_argument_required_after_attribute);
5925 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
5927 // If we have the closing ')', eat it.
5928 Tracker.consumeClose();
5929 RParenLoc = Tracker.getCloseLocation();
5930 LocalEndLoc = RParenLoc;
5933 if (getLangOpts().CPlusPlus) {
5934 // FIXME: Accept these components in any order, and produce fixits to
5935 // correct the order if the user gets it wrong. Ideally we should deal
5936 // with the pure-specifier in the same way.
5938 // Parse cv-qualifier-seq[opt].
5939 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
5940 /*AtomicAllowed*/ false,
5941 /*IdentifierRequired=*/false,
5942 llvm::function_ref<void()>([&]() {
5943 Actions.CodeCompleteFunctionQualifiers(DS, D);
5945 if (!DS.getSourceRange().getEnd().isInvalid()) {
5946 EndLoc = DS.getSourceRange().getEnd();
5947 ConstQualifierLoc = DS.getConstSpecLoc();
5948 VolatileQualifierLoc = DS.getVolatileSpecLoc();
5949 RestrictQualifierLoc = DS.getRestrictSpecLoc();
5952 // Parse ref-qualifier[opt].
5953 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
5954 EndLoc = RefQualifierLoc;
5956 // C++11 [expr.prim.general]p3:
5957 // If a declaration declares a member function or member function
5958 // template of a class X, the expression this is a prvalue of type
5959 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5960 // and the end of the function-definition, member-declarator, or
5962 // FIXME: currently, "static" case isn't handled correctly.
5963 bool IsCXX11MemberFunction =
5964 getLangOpts().CPlusPlus11 &&
5965 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5966 (D.getContext() == Declarator::MemberContext
5967 ? !D.getDeclSpec().isFriendSpecified()
5968 : D.getContext() == Declarator::FileContext &&
5969 D.getCXXScopeSpec().isValid() &&
5970 Actions.CurContext->isRecord());
5971 Sema::CXXThisScopeRAII ThisScope(Actions,
5972 dyn_cast<CXXRecordDecl>(Actions.CurContext),
5973 DS.getTypeQualifiers() |
5974 (D.getDeclSpec().isConstexprSpecified() &&
5975 !getLangOpts().CPlusPlus14
5976 ? Qualifiers::Const : 0),
5977 IsCXX11MemberFunction);
5979 // Parse exception-specification[opt].
5980 bool Delayed = D.isFirstDeclarationOfMember() &&
5981 D.isFunctionDeclaratorAFunctionDeclaration();
5982 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
5983 GetLookAheadToken(0).is(tok::kw_noexcept) &&
5984 GetLookAheadToken(1).is(tok::l_paren) &&
5985 GetLookAheadToken(2).is(tok::kw_noexcept) &&
5986 GetLookAheadToken(3).is(tok::l_paren) &&
5987 GetLookAheadToken(4).is(tok::identifier) &&
5988 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
5989 // HACK: We've got an exception-specification
5990 // noexcept(noexcept(swap(...)))
5992 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
5993 // on a 'swap' member function. This is a libstdc++ bug; the lookup
5994 // for 'swap' will only find the function we're currently declaring,
5995 // whereas it expects to find a non-member swap through ADL. Turn off
5996 // delayed parsing to give it a chance to find what it expects.
5999 ESpecType = tryParseExceptionSpecification(Delayed,
6002 DynamicExceptionRanges,
6004 ExceptionSpecTokens);
6005 if (ESpecType != EST_None)
6006 EndLoc = ESpecRange.getEnd();
6008 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6009 // after the exception-specification.
6010 MaybeParseCXX11Attributes(FnAttrs);
6012 // Parse trailing-return-type[opt].
6013 LocalEndLoc = EndLoc;
6014 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
6015 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
6016 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
6017 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
6018 LocalEndLoc = Tok.getLocation();
6020 TrailingReturnType = ParseTrailingReturnType(Range);
6021 EndLoc = Range.getEnd();
6026 // Collect non-parameter declarations from the prototype if this is a function
6027 // declaration. They will be moved into the scope of the function. Only do
6028 // this in C and not C++, where the decls will continue to live in the
6029 // surrounding context.
6030 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6031 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6032 !getLangOpts().CPlusPlus) {
6033 for (Decl *D : getCurScope()->decls()) {
6034 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6035 if (!ND || isa<ParmVarDecl>(ND))
6037 DeclsInPrototype.push_back(ND);
6041 // Remember that we parsed a function type, and remember the attributes.
6042 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
6045 ParamInfo.data(), ParamInfo.size(),
6046 EllipsisLoc, RParenLoc,
6047 DS.getTypeQualifiers(),
6048 RefQualifierIsLValueRef,
6049 RefQualifierLoc, ConstQualifierLoc,
6050 VolatileQualifierLoc,
6051 RestrictQualifierLoc,
6052 /*MutableLoc=*/SourceLocation(),
6053 ESpecType, ESpecRange,
6054 DynamicExceptions.data(),
6055 DynamicExceptionRanges.data(),
6056 DynamicExceptions.size(),
6057 NoexceptExpr.isUsable() ?
6058 NoexceptExpr.get() : nullptr,
6059 ExceptionSpecTokens,
6061 StartLoc, LocalEndLoc, D,
6062 TrailingReturnType),
6066 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6067 /// true if a ref-qualifier is found.
6068 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6069 SourceLocation &RefQualifierLoc) {
6070 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
6071 Diag(Tok, getLangOpts().CPlusPlus11 ?
6072 diag::warn_cxx98_compat_ref_qualifier :
6073 diag::ext_ref_qualifier);
6075 RefQualifierIsLValueRef = Tok.is(tok::amp);
6076 RefQualifierLoc = ConsumeToken();
6082 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
6083 /// identifier list form for a K&R-style function: void foo(a,b,c)
6085 /// Note that identifier-lists are only allowed for normal declarators, not for
6086 /// abstract-declarators.
6087 bool Parser::isFunctionDeclaratorIdentifierList() {
6088 return !getLangOpts().CPlusPlus
6089 && Tok.is(tok::identifier)
6090 && !TryAltiVecVectorToken()
6091 // K&R identifier lists can't have typedefs as identifiers, per C99
6093 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6094 // Identifier lists follow a really simple grammar: the identifiers can
6095 // be followed *only* by a ", identifier" or ")". However, K&R
6096 // identifier lists are really rare in the brave new modern world, and
6097 // it is very common for someone to typo a type in a non-K&R style
6098 // list. If we are presented with something like: "void foo(intptr x,
6099 // float y)", we don't want to start parsing the function declarator as
6100 // though it is a K&R style declarator just because intptr is an
6103 // To handle this, we check to see if the token after the first
6104 // identifier is a "," or ")". Only then do we parse it as an
6106 && (!Tok.is(tok::eof) &&
6107 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
6110 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6111 /// we found a K&R-style identifier list instead of a typed parameter list.
6113 /// After returning, ParamInfo will hold the parsed parameters.
6115 /// identifier-list: [C99 6.7.5]
6117 /// identifier-list ',' identifier
6119 void Parser::ParseFunctionDeclaratorIdentifierList(
6121 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
6122 // If there was no identifier specified for the declarator, either we are in
6123 // an abstract-declarator, or we are in a parameter declarator which was found
6124 // to be abstract. In abstract-declarators, identifier lists are not valid:
6126 if (!D.getIdentifier())
6127 Diag(Tok, diag::ext_ident_list_in_param);
6129 // Maintain an efficient lookup of params we have seen so far.
6130 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6133 // If this isn't an identifier, report the error and skip until ')'.
6134 if (Tok.isNot(tok::identifier)) {
6135 Diag(Tok, diag::err_expected) << tok::identifier;
6136 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
6137 // Forget we parsed anything.
6142 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6144 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6145 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6146 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6148 // Verify that the argument identifier has not already been mentioned.
6149 if (!ParamsSoFar.insert(ParmII).second) {
6150 Diag(Tok, diag::err_param_redefinition) << ParmII;
6152 // Remember this identifier in ParamInfo.
6153 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6158 // Eat the identifier.
6160 // The list continues if we see a comma.
6161 } while (TryConsumeToken(tok::comma));
6164 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6165 /// after the opening parenthesis. This function will not parse a K&R-style
6166 /// identifier list.
6168 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
6169 /// caller parsed those arguments immediately after the open paren - they should
6170 /// be considered to be part of the first parameter.
6172 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6173 /// be the location of the ellipsis, if any was parsed.
6175 /// parameter-type-list: [C99 6.7.5]
6177 /// parameter-list ',' '...'
6178 /// [C++] parameter-list '...'
6180 /// parameter-list: [C99 6.7.5]
6181 /// parameter-declaration
6182 /// parameter-list ',' parameter-declaration
6184 /// parameter-declaration: [C99 6.7.5]
6185 /// declaration-specifiers declarator
6186 /// [C++] declaration-specifiers declarator '=' assignment-expression
6187 /// [C++11] initializer-clause
6188 /// [GNU] declaration-specifiers declarator attributes
6189 /// declaration-specifiers abstract-declarator[opt]
6190 /// [C++] declaration-specifiers abstract-declarator[opt]
6191 /// '=' assignment-expression
6192 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
6193 /// [C++11] attribute-specifier-seq parameter-declaration
6195 void Parser::ParseParameterDeclarationClause(
6197 ParsedAttributes &FirstArgAttrs,
6198 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
6199 SourceLocation &EllipsisLoc) {
6201 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6202 // before deciding this was a parameter-declaration-clause.
6203 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
6206 // Parse the declaration-specifiers.
6207 // Just use the ParsingDeclaration "scope" of the declarator.
6208 DeclSpec DS(AttrFactory);
6210 // Parse any C++11 attributes.
6211 MaybeParseCXX11Attributes(DS.getAttributes());
6213 // Skip any Microsoft attributes before a param.
6214 MaybeParseMicrosoftAttributes(DS.getAttributes());
6216 SourceLocation DSStart = Tok.getLocation();
6218 // If the caller parsed attributes for the first argument, add them now.
6219 // Take them so that we only apply the attributes to the first parameter.
6220 // FIXME: If we can leave the attributes in the token stream somehow, we can
6221 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6223 DS.takeAttributesFrom(FirstArgAttrs);
6225 ParseDeclarationSpecifiers(DS);
6228 // Parse the declarator. This is "PrototypeContext" or
6229 // "LambdaExprParameterContext", because we must accept either
6230 // 'declarator' or 'abstract-declarator' here.
6231 Declarator ParmDeclarator(DS,
6232 D.getContext() == Declarator::LambdaExprContext ?
6233 Declarator::LambdaExprParameterContext :
6234 Declarator::PrototypeContext);
6235 ParseDeclarator(ParmDeclarator);
6237 // Parse GNU attributes, if present.
6238 MaybeParseGNUAttributes(ParmDeclarator);
6240 // Remember this parsed parameter in ParamInfo.
6241 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
6243 // DefArgToks is used when the parsing of default arguments needs
6245 std::unique_ptr<CachedTokens> DefArgToks;
6247 // If no parameter was specified, verify that *something* was specified,
6248 // otherwise we have a missing type and identifier.
6249 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
6250 ParmDeclarator.getNumTypeObjects() == 0) {
6251 // Completely missing, emit error.
6252 Diag(DSStart, diag::err_missing_param);
6254 // Otherwise, we have something. Add it and let semantic analysis try
6255 // to grok it and add the result to the ParamInfo we are building.
6257 // Last chance to recover from a misplaced ellipsis in an attempted
6258 // parameter pack declaration.
6259 if (Tok.is(tok::ellipsis) &&
6260 (NextToken().isNot(tok::r_paren) ||
6261 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6262 !Actions.isUnexpandedParameterPackPermitted())) &&
6263 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6264 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6266 // Inform the actions module about the parameter declarator, so it gets
6267 // added to the current scope.
6268 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
6269 // Parse the default argument, if any. We parse the default
6270 // arguments in all dialects; the semantic analysis in
6271 // ActOnParamDefaultArgument will reject the default argument in
6273 if (Tok.is(tok::equal)) {
6274 SourceLocation EqualLoc = Tok.getLocation();
6276 // Parse the default argument
6277 if (D.getContext() == Declarator::MemberContext) {
6278 // If we're inside a class definition, cache the tokens
6279 // corresponding to the default argument. We'll actually parse
6280 // them when we see the end of the class definition.
6281 DefArgToks.reset(new CachedTokens);
6283 SourceLocation ArgStartLoc = NextToken().getLocation();
6284 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
6286 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6288 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
6295 // The argument isn't actually potentially evaluated unless it is
6297 EnterExpressionEvaluationContext Eval(
6299 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6302 ExprResult DefArgResult;
6303 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
6304 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
6305 DefArgResult = ParseBraceInitializer();
6307 DefArgResult = ParseAssignmentExpression();
6308 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
6309 if (DefArgResult.isInvalid()) {
6310 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6311 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
6313 // Inform the actions module about the default argument
6314 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
6315 DefArgResult.get());
6320 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6321 ParmDeclarator.getIdentifierLoc(),
6322 Param, std::move(DefArgToks)));
6325 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6326 if (!getLangOpts().CPlusPlus) {
6327 // We have ellipsis without a preceding ',', which is ill-formed
6328 // in C. Complain and provide the fix.
6329 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6330 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6331 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6332 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6333 // It looks like this was supposed to be a parameter pack. Warn and
6334 // point out where the ellipsis should have gone.
6335 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6336 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6337 << ParmEllipsis.isValid() << ParmEllipsis;
6338 if (ParmEllipsis.isValid()) {
6340 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6342 Diag(ParmDeclarator.getIdentifierLoc(),
6343 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6344 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6346 << !ParmDeclarator.hasName();
6348 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
6349 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6352 // We can't have any more parameters after an ellipsis.
6356 // If the next token is a comma, consume it and keep reading arguments.
6357 } while (TryConsumeToken(tok::comma));
6360 /// [C90] direct-declarator '[' constant-expression[opt] ']'
6361 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6362 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6363 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6364 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
6365 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
6366 /// attribute-specifier-seq[opt]
6367 void Parser::ParseBracketDeclarator(Declarator &D) {
6368 if (CheckProhibitedCXX11Attribute())
6371 BalancedDelimiterTracker T(*this, tok::l_square);
6374 // C array syntax has many features, but by-far the most common is [] and [4].
6375 // This code does a fast path to handle some of the most obvious cases.
6376 if (Tok.getKind() == tok::r_square) {
6378 ParsedAttributes attrs(AttrFactory);
6379 MaybeParseCXX11Attributes(attrs);
6381 // Remember that we parsed the empty array type.
6382 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
6383 T.getOpenLocation(),
6384 T.getCloseLocation()),
6385 attrs, T.getCloseLocation());
6387 } else if (Tok.getKind() == tok::numeric_constant &&
6388 GetLookAheadToken(1).is(tok::r_square)) {
6389 // [4] is very common. Parse the numeric constant expression.
6390 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
6394 ParsedAttributes attrs(AttrFactory);
6395 MaybeParseCXX11Attributes(attrs);
6397 // Remember that we parsed a array type, and remember its features.
6398 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false,
6400 T.getOpenLocation(),
6401 T.getCloseLocation()),
6402 attrs, T.getCloseLocation());
6404 } else if (Tok.getKind() == tok::code_completion) {
6405 Actions.CodeCompleteBracketDeclarator(getCurScope());
6406 return cutOffParsing();
6409 // If valid, this location is the position where we read the 'static' keyword.
6410 SourceLocation StaticLoc;
6411 TryConsumeToken(tok::kw_static, StaticLoc);
6413 // If there is a type-qualifier-list, read it now.
6414 // Type qualifiers in an array subscript are a C99 feature.
6415 DeclSpec DS(AttrFactory);
6416 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
6418 // If we haven't already read 'static', check to see if there is one after the
6419 // type-qualifier-list.
6420 if (!StaticLoc.isValid())
6421 TryConsumeToken(tok::kw_static, StaticLoc);
6423 // Handle "direct-declarator [ type-qual-list[opt] * ]".
6424 bool isStar = false;
6425 ExprResult NumElements;
6427 // Handle the case where we have '[*]' as the array size. However, a leading
6428 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
6429 // the token after the star is a ']'. Since stars in arrays are
6430 // infrequent, use of lookahead is not costly here.
6431 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
6432 ConsumeToken(); // Eat the '*'.
6434 if (StaticLoc.isValid()) {
6435 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
6436 StaticLoc = SourceLocation(); // Drop the static.
6439 } else if (Tok.isNot(tok::r_square)) {
6440 // Note, in C89, this production uses the constant-expr production instead
6441 // of assignment-expr. The only difference is that assignment-expr allows
6442 // things like '=' and '*='. Sema rejects these in C89 mode because they
6443 // are not i-c-e's, so we don't need to distinguish between the two here.
6445 // Parse the constant-expression or assignment-expression now (depending
6447 if (getLangOpts().CPlusPlus) {
6448 NumElements = ParseConstantExpression();
6450 EnterExpressionEvaluationContext Unevaluated(
6451 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6453 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
6456 if (StaticLoc.isValid()) {
6457 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6458 StaticLoc = SourceLocation(); // Drop the static.
6462 // If there was an error parsing the assignment-expression, recover.
6463 if (NumElements.isInvalid()) {
6464 D.setInvalidType(true);
6465 // If the expression was invalid, skip it.
6466 SkipUntil(tok::r_square, StopAtSemi);
6472 MaybeParseCXX11Attributes(DS.getAttributes());
6474 // Remember that we parsed a array type, and remember its features.
6475 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
6476 StaticLoc.isValid(), isStar,
6478 T.getOpenLocation(),
6479 T.getCloseLocation()),
6480 DS.getAttributes(), T.getCloseLocation());
6483 /// Diagnose brackets before an identifier.
6484 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6485 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6486 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6488 SourceLocation StartBracketLoc = Tok.getLocation();
6489 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6491 while (Tok.is(tok::l_square)) {
6492 ParseBracketDeclarator(TempDeclarator);
6495 // Stuff the location of the start of the brackets into the Declarator.
6496 // The diagnostics from ParseDirectDeclarator will make more sense if
6497 // they use this location instead.
6498 if (Tok.is(tok::semi))
6499 D.getName().EndLocation = StartBracketLoc;
6501 SourceLocation SuggestParenLoc = Tok.getLocation();
6503 // Now that the brackets are removed, try parsing the declarator again.
6504 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6506 // Something went wrong parsing the brackets, in which case,
6507 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6509 if (TempDeclarator.getNumTypeObjects() == 0)
6512 // Determine if parens will need to be suggested in the diagnostic.
6513 bool NeedParens = false;
6514 if (D.getNumTypeObjects() != 0) {
6515 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6516 case DeclaratorChunk::Pointer:
6517 case DeclaratorChunk::Reference:
6518 case DeclaratorChunk::BlockPointer:
6519 case DeclaratorChunk::MemberPointer:
6520 case DeclaratorChunk::Pipe:
6523 case DeclaratorChunk::Array:
6524 case DeclaratorChunk::Function:
6525 case DeclaratorChunk::Paren:
6531 // Create a DeclaratorChunk for the inserted parens.
6532 ParsedAttributes attrs(AttrFactory);
6533 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6534 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), attrs,
6538 // Adding back the bracket info to the end of the Declarator.
6539 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6540 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
6541 ParsedAttributes attrs(AttrFactory);
6542 attrs.set(Chunk.Common.AttrList);
6543 D.AddTypeInfo(Chunk, attrs, SourceLocation());
6546 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6547 // If parentheses are required, always suggest them.
6548 if (!D.getIdentifier() && !NeedParens)
6551 SourceLocation EndBracketLoc = TempDeclarator.getLocEnd();
6553 // Generate the move bracket error message.
6554 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
6555 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6558 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6559 << getLangOpts().CPlusPlus
6560 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6561 << FixItHint::CreateInsertion(EndLoc, ")")
6562 << FixItHint::CreateInsertionFromRange(
6563 EndLoc, CharSourceRange(BracketRange, true))
6564 << FixItHint::CreateRemoval(BracketRange);
6566 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6567 << getLangOpts().CPlusPlus
6568 << FixItHint::CreateInsertionFromRange(
6569 EndLoc, CharSourceRange(BracketRange, true))
6570 << FixItHint::CreateRemoval(BracketRange);
6574 /// [GNU] typeof-specifier:
6575 /// typeof ( expressions )
6576 /// typeof ( type-name )
6577 /// [GNU/C++] typeof unary-expression
6579 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
6580 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
6582 SourceLocation StartLoc = ConsumeToken();
6584 const bool hasParens = Tok.is(tok::l_paren);
6586 EnterExpressionEvaluationContext Unevaluated(
6587 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6588 Sema::ReuseLambdaContextDecl);
6592 SourceRange CastRange;
6593 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6594 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
6596 DS.setTypeofParensRange(CastRange);
6598 if (CastRange.getEnd().isInvalid())
6599 // FIXME: Not accurate, the range gets one token more than it should.
6600 DS.SetRangeEnd(Tok.getLocation());
6602 DS.SetRangeEnd(CastRange.getEnd());
6606 DS.SetTypeSpecError();
6610 const char *PrevSpec = nullptr;
6612 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6613 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
6615 Actions.getASTContext().getPrintingPolicy()))
6616 Diag(StartLoc, DiagID) << PrevSpec;
6620 // If we get here, the operand to the typeof was an expresion.
6621 if (Operand.isInvalid()) {
6622 DS.SetTypeSpecError();
6626 // We might need to transform the operand if it is potentially evaluated.
6627 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6628 if (Operand.isInvalid()) {
6629 DS.SetTypeSpecError();
6633 const char *PrevSpec = nullptr;
6635 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6636 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
6637 DiagID, Operand.get(),
6638 Actions.getASTContext().getPrintingPolicy()))
6639 Diag(StartLoc, DiagID) << PrevSpec;
6642 /// [C11] atomic-specifier:
6643 /// _Atomic ( type-name )
6645 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
6646 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6647 "Not an atomic specifier");
6649 SourceLocation StartLoc = ConsumeToken();
6650 BalancedDelimiterTracker T(*this, tok::l_paren);
6651 if (T.consumeOpen())
6654 TypeResult Result = ParseTypeName();
6655 if (Result.isInvalid()) {
6656 SkipUntil(tok::r_paren, StopAtSemi);
6663 if (T.getCloseLocation().isInvalid())
6666 DS.setTypeofParensRange(T.getRange());
6667 DS.SetRangeEnd(T.getCloseLocation());
6669 const char *PrevSpec = nullptr;
6671 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
6672 DiagID, Result.get(),
6673 Actions.getASTContext().getPrintingPolicy()))
6674 Diag(StartLoc, DiagID) << PrevSpec;
6677 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6678 /// from TryAltiVecVectorToken.
6679 bool Parser::TryAltiVecVectorTokenOutOfLine() {
6680 Token Next = NextToken();
6681 switch (Next.getKind()) {
6682 default: return false;
6685 case tok::kw_signed:
6686 case tok::kw_unsigned:
6691 case tok::kw_double:
6693 case tok::kw___bool:
6694 case tok::kw___pixel:
6695 Tok.setKind(tok::kw___vector);
6697 case tok::identifier:
6698 if (Next.getIdentifierInfo() == Ident_pixel) {
6699 Tok.setKind(tok::kw___vector);
6702 if (Next.getIdentifierInfo() == Ident_bool) {
6703 Tok.setKind(tok::kw___vector);
6710 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6711 const char *&PrevSpec, unsigned &DiagID,
6713 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
6714 if (Tok.getIdentifierInfo() == Ident_vector) {
6715 Token Next = NextToken();
6716 switch (Next.getKind()) {
6719 case tok::kw_signed:
6720 case tok::kw_unsigned:
6725 case tok::kw_double:
6727 case tok::kw___bool:
6728 case tok::kw___pixel:
6729 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
6731 case tok::identifier:
6732 if (Next.getIdentifierInfo() == Ident_pixel) {
6733 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6736 if (Next.getIdentifierInfo() == Ident_bool) {
6737 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6744 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
6745 DS.isTypeAltiVecVector()) {
6746 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
6748 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
6749 DS.isTypeAltiVecVector()) {
6750 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);