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);
2563 // This looks like a variable or function declaration. The type is
2564 // probably missing. We're done parsing decl-specifiers.
2566 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2570 // This is probably supposed to be a type. This includes cases like:
2572 // struct S { unsinged : 4; };
2577 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2578 // and attempt to recover.
2580 IdentifierInfo *II = Tok.getIdentifierInfo();
2581 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2582 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2585 // The action has suggested that the type T could be used. Set that as
2586 // the type in the declaration specifiers, consume the would-be type
2587 // name token, and we're done.
2588 const char *PrevSpec;
2590 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2591 Actions.getASTContext().getPrintingPolicy());
2592 DS.SetRangeEnd(Tok.getLocation());
2594 // There may be other declaration specifiers after this.
2596 } else if (II != Tok.getIdentifierInfo()) {
2597 // If no type was suggested, the correction is to a keyword
2598 Tok.setKind(II->getTokenID());
2599 // There may be other declaration specifiers after this.
2603 // Otherwise, the action had no suggestion for us. Mark this as an error.
2604 DS.SetTypeSpecError();
2605 DS.SetRangeEnd(Tok.getLocation());
2608 // Eat any following template arguments.
2609 if (IsTemplateName) {
2610 SourceLocation LAngle, RAngle;
2611 TemplateArgList Args;
2612 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2615 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2616 // avoid rippling error messages on subsequent uses of the same type,
2617 // could be useful if #include was forgotten.
2621 /// \brief Determine the declaration specifier context from the declarator
2624 /// \param Context the declarator context, which is one of the
2625 /// Declarator::TheContext enumerator values.
2626 Parser::DeclSpecContext
2627 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
2628 if (Context == Declarator::MemberContext)
2630 if (Context == Declarator::FileContext)
2631 return DSC_top_level;
2632 if (Context == Declarator::TemplateTypeArgContext)
2633 return DSC_template_type_arg;
2634 if (Context == Declarator::TrailingReturnContext)
2635 return DSC_trailing;
2636 if (Context == Declarator::AliasDeclContext ||
2637 Context == Declarator::AliasTemplateContext)
2638 return DSC_alias_declaration;
2642 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2644 /// FIXME: Simply returns an alignof() expression if the argument is a
2645 /// type. Ideally, the type should be propagated directly into Sema.
2648 /// [C11] constant-expression
2649 /// [C++0x] type-id ...[opt]
2650 /// [C++0x] assignment-expression ...[opt]
2651 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2652 SourceLocation &EllipsisLoc) {
2654 if (isTypeIdInParens()) {
2655 SourceLocation TypeLoc = Tok.getLocation();
2656 ParsedType Ty = ParseTypeName().get();
2657 SourceRange TypeRange(Start, Tok.getLocation());
2658 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2659 Ty.getAsOpaquePtr(), TypeRange);
2661 ER = ParseConstantExpression();
2663 if (getLangOpts().CPlusPlus11)
2664 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2669 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2670 /// attribute to Attrs.
2672 /// alignment-specifier:
2673 /// [C11] '_Alignas' '(' type-id ')'
2674 /// [C11] '_Alignas' '(' constant-expression ')'
2675 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2676 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2677 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2678 SourceLocation *EndLoc) {
2679 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2680 "Not an alignment-specifier!");
2682 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2683 SourceLocation KWLoc = ConsumeToken();
2685 BalancedDelimiterTracker T(*this, tok::l_paren);
2686 if (T.expectAndConsume())
2689 SourceLocation EllipsisLoc;
2690 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2691 if (ArgExpr.isInvalid()) {
2698 *EndLoc = T.getCloseLocation();
2700 ArgsVector ArgExprs;
2701 ArgExprs.push_back(ArgExpr.get());
2702 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2703 AttributeList::AS_Keyword, EllipsisLoc);
2706 /// Determine whether we're looking at something that might be a declarator
2707 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2708 /// diagnose a missing semicolon after a prior tag definition in the decl
2711 /// \return \c true if an error occurred and this can't be any kind of
2714 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2715 DeclSpecContext DSContext,
2716 LateParsedAttrList *LateAttrs) {
2717 assert(DS.hasTagDefinition() && "shouldn't call this");
2719 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2721 if (getLangOpts().CPlusPlus &&
2722 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2723 tok::annot_template_id) &&
2724 TryAnnotateCXXScopeToken(EnteringContext)) {
2725 SkipMalformedDecl();
2729 bool HasScope = Tok.is(tok::annot_cxxscope);
2730 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2731 Token AfterScope = HasScope ? NextToken() : Tok;
2733 // Determine whether the following tokens could possibly be a
2735 bool MightBeDeclarator = true;
2736 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2737 // A declarator-id can't start with 'typename'.
2738 MightBeDeclarator = false;
2739 } else if (AfterScope.is(tok::annot_template_id)) {
2740 // If we have a type expressed as a template-id, this cannot be a
2741 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2742 TemplateIdAnnotation *Annot =
2743 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2744 if (Annot->Kind == TNK_Type_template)
2745 MightBeDeclarator = false;
2746 } else if (AfterScope.is(tok::identifier)) {
2747 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2749 // These tokens cannot come after the declarator-id in a
2750 // simple-declaration, and are likely to come after a type-specifier.
2751 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2752 tok::annot_cxxscope, tok::coloncolon)) {
2753 // Missing a semicolon.
2754 MightBeDeclarator = false;
2755 } else if (HasScope) {
2756 // If the declarator-id has a scope specifier, it must redeclare a
2757 // previously-declared entity. If that's a type (and this is not a
2758 // typedef), that's an error.
2760 Actions.RestoreNestedNameSpecifierAnnotation(
2761 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2762 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2763 Sema::NameClassification Classification = Actions.ClassifyName(
2764 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2765 /*IsAddressOfOperand*/false);
2766 switch (Classification.getKind()) {
2767 case Sema::NC_Error:
2768 SkipMalformedDecl();
2771 case Sema::NC_Keyword:
2772 case Sema::NC_NestedNameSpecifier:
2773 llvm_unreachable("typo correction and nested name specifiers not "
2777 case Sema::NC_TypeTemplate:
2778 // Not a previously-declared non-type entity.
2779 MightBeDeclarator = false;
2782 case Sema::NC_Unknown:
2783 case Sema::NC_Expression:
2784 case Sema::NC_VarTemplate:
2785 case Sema::NC_FunctionTemplate:
2786 // Might be a redeclaration of a prior entity.
2792 if (MightBeDeclarator)
2795 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2796 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()),
2797 diag::err_expected_after)
2798 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2800 // Try to recover from the typo, by dropping the tag definition and parsing
2801 // the problematic tokens as a type.
2803 // FIXME: Split the DeclSpec into pieces for the standalone
2804 // declaration and pieces for the following declaration, instead
2805 // of assuming that all the other pieces attach to new declaration,
2806 // and call ParsedFreeStandingDeclSpec as appropriate.
2807 DS.ClearTypeSpecType();
2808 ParsedTemplateInfo NotATemplate;
2809 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2813 /// ParseDeclarationSpecifiers
2814 /// declaration-specifiers: [C99 6.7]
2815 /// storage-class-specifier declaration-specifiers[opt]
2816 /// type-specifier declaration-specifiers[opt]
2817 /// [C99] function-specifier declaration-specifiers[opt]
2818 /// [C11] alignment-specifier declaration-specifiers[opt]
2819 /// [GNU] attributes declaration-specifiers[opt]
2820 /// [Clang] '__module_private__' declaration-specifiers[opt]
2821 /// [ObjC1] '__kindof' declaration-specifiers[opt]
2823 /// storage-class-specifier: [C99 6.7.1]
2830 /// [C++11] 'thread_local'
2831 /// [C11] '_Thread_local'
2832 /// [GNU] '__thread'
2833 /// function-specifier: [C99 6.7.4]
2836 /// [C++] 'explicit'
2837 /// [OpenCL] '__kernel'
2838 /// 'friend': [C++ dcl.friend]
2839 /// 'constexpr': [C++0x dcl.constexpr]
2840 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2841 const ParsedTemplateInfo &TemplateInfo,
2843 DeclSpecContext DSContext,
2844 LateParsedAttrList *LateAttrs) {
2845 if (DS.getSourceRange().isInvalid()) {
2846 // Start the range at the current token but make the end of the range
2847 // invalid. This will make the entire range invalid unless we successfully
2849 DS.SetRangeStart(Tok.getLocation());
2850 DS.SetRangeEnd(SourceLocation());
2853 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2854 bool AttrsLastTime = false;
2855 ParsedAttributesWithRange attrs(AttrFactory);
2856 // We use Sema's policy to get bool macros right.
2857 PrintingPolicy Policy = Actions.getPrintingPolicy();
2859 bool isInvalid = false;
2860 bool isStorageClass = false;
2861 const char *PrevSpec = nullptr;
2862 unsigned DiagID = 0;
2864 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2865 // implementation for VS2013 uses _Atomic as an identifier for one of the
2866 // classes in <atomic>.
2868 // A typedef declaration containing _Atomic<...> is among the places where
2869 // the class is used. If we are currently parsing such a declaration, treat
2870 // the token as an identifier.
2871 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2872 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
2873 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
2874 Tok.setKind(tok::identifier);
2876 SourceLocation Loc = Tok.getLocation();
2878 switch (Tok.getKind()) {
2882 ProhibitAttributes(attrs);
2884 // Reject C++11 attributes that appertain to decl specifiers as
2885 // we don't support any C++11 attributes that appertain to decl
2886 // specifiers. This also conforms to what g++ 4.8 is doing.
2887 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
2889 DS.takeAttributesFrom(attrs);
2892 // If this is not a declaration specifier token, we're done reading decl
2893 // specifiers. First verify that DeclSpec's are consistent.
2894 DS.Finish(Actions, Policy);
2898 case tok::kw_alignas:
2899 if (!getLangOpts().CPlusPlus11 || !isCXX11AttributeSpecifier())
2900 goto DoneWithDeclSpec;
2902 ProhibitAttributes(attrs);
2903 // FIXME: It would be good to recover by accepting the attributes,
2904 // but attempting to do that now would cause serious
2905 // madness in terms of diagnostics.
2907 attrs.Range = SourceRange();
2909 ParseCXX11Attributes(attrs);
2910 AttrsLastTime = true;
2913 case tok::code_completion: {
2914 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2915 if (DS.hasTypeSpecifier()) {
2916 bool AllowNonIdentifiers
2917 = (getCurScope()->getFlags() & (Scope::ControlScope |
2919 Scope::TemplateParamScope |
2920 Scope::FunctionPrototypeScope |
2921 Scope::AtCatchScope)) == 0;
2922 bool AllowNestedNameSpecifiers
2923 = DSContext == DSC_top_level ||
2924 (DSContext == DSC_class && DS.isFriendSpecified());
2926 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
2927 AllowNonIdentifiers,
2928 AllowNestedNameSpecifiers);
2929 return cutOffParsing();
2932 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
2933 CCC = Sema::PCC_LocalDeclarationSpecifiers;
2934 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
2935 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
2936 : Sema::PCC_Template;
2937 else if (DSContext == DSC_class)
2938 CCC = Sema::PCC_Class;
2939 else if (CurParsedObjCImpl)
2940 CCC = Sema::PCC_ObjCImplementation;
2942 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
2943 return cutOffParsing();
2946 case tok::coloncolon: // ::foo::bar
2947 // C++ scope specifier. Annotate and loop, or bail out on error.
2948 if (TryAnnotateCXXScopeToken(EnteringContext)) {
2949 if (!DS.hasTypeSpecifier())
2950 DS.SetTypeSpecError();
2951 goto DoneWithDeclSpec;
2953 if (Tok.is(tok::coloncolon)) // ::new or ::delete
2954 goto DoneWithDeclSpec;
2957 case tok::annot_cxxscope: {
2958 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
2959 goto DoneWithDeclSpec;
2962 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2963 Tok.getAnnotationRange(),
2966 // We are looking for a qualified typename.
2967 Token Next = NextToken();
2968 if (Next.is(tok::annot_template_id) &&
2969 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
2970 ->Kind == TNK_Type_template) {
2971 // We have a qualified template-id, e.g., N::A<int>
2973 // If this would be a valid constructor declaration with template
2974 // arguments, we will reject the attempt to form an invalid type-id
2975 // referring to the injected-class-name when we annotate the token,
2976 // per C++ [class.qual]p2.
2978 // To improve diagnostics for this case, parse the declaration as a
2979 // constructor (and reject the extra template arguments later).
2980 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
2981 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2983 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
2984 isConstructorDeclarator(/*Unqualified*/false)) {
2985 // The user meant this to be an out-of-line constructor
2986 // definition, but template arguments are not allowed
2987 // there. Just allow this as a constructor; we'll
2988 // complain about it later.
2989 goto DoneWithDeclSpec;
2992 DS.getTypeSpecScope() = SS;
2993 ConsumeAnnotationToken(); // The C++ scope.
2994 assert(Tok.is(tok::annot_template_id) &&
2995 "ParseOptionalCXXScopeSpecifier not working");
2996 AnnotateTemplateIdTokenAsType();
3000 if (Next.is(tok::annot_typename)) {
3001 DS.getTypeSpecScope() = SS;
3002 ConsumeAnnotationToken(); // The C++ scope.
3003 if (Tok.getAnnotationValue()) {
3004 ParsedType T = getTypeAnnotation(Tok);
3005 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3006 Tok.getAnnotationEndLoc(),
3007 PrevSpec, DiagID, T, Policy);
3012 DS.SetTypeSpecError();
3013 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3014 ConsumeAnnotationToken(); // The typename
3017 if (Next.isNot(tok::identifier))
3018 goto DoneWithDeclSpec;
3020 // Check whether this is a constructor declaration. If we're in a
3021 // context where the identifier could be a class name, and it has the
3022 // shape of a constructor declaration, process it as one.
3023 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
3024 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3026 isConstructorDeclarator(/*Unqualified*/ false))
3027 goto DoneWithDeclSpec;
3029 ParsedType TypeRep =
3030 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3031 getCurScope(), &SS, false, false, nullptr,
3032 /*IsCtorOrDtorName=*/false,
3033 /*WantNonTrivialSourceInfo=*/true,
3034 isClassTemplateDeductionContext(DSContext));
3036 // If the referenced identifier is not a type, then this declspec is
3037 // erroneous: We already checked about that it has no type specifier, and
3038 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3041 // Eat the scope spec so the identifier is current.
3042 ConsumeAnnotationToken();
3043 ParsedAttributesWithRange Attrs(AttrFactory);
3044 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3045 if (!Attrs.empty()) {
3046 AttrsLastTime = true;
3047 attrs.takeAllFrom(Attrs);
3051 goto DoneWithDeclSpec;
3054 DS.getTypeSpecScope() = SS;
3055 ConsumeAnnotationToken(); // The C++ scope.
3057 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3058 DiagID, TypeRep, Policy);
3062 DS.SetRangeEnd(Tok.getLocation());
3063 ConsumeToken(); // The typename.
3068 case tok::annot_typename: {
3069 // If we've previously seen a tag definition, we were almost surely
3070 // missing a semicolon after it.
3071 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3072 goto DoneWithDeclSpec;
3074 if (Tok.getAnnotationValue()) {
3075 ParsedType T = getTypeAnnotation(Tok);
3076 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3079 DS.SetTypeSpecError();
3084 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3085 ConsumeAnnotationToken(); // The typename
3090 case tok::kw___is_signed:
3091 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3092 // typically treats it as a trait. If we see __is_signed as it appears
3093 // in libstdc++, e.g.,
3095 // static const bool __is_signed;
3097 // then treat __is_signed as an identifier rather than as a keyword.
3098 if (DS.getTypeSpecType() == TST_bool &&
3099 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3100 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3101 TryKeywordIdentFallback(true);
3103 // We're done with the declaration-specifiers.
3104 goto DoneWithDeclSpec;
3107 case tok::kw___super:
3108 case tok::kw_decltype:
3109 case tok::identifier: {
3110 // This identifier can only be a typedef name if we haven't already seen
3111 // a type-specifier. Without this check we misparse:
3112 // typedef int X; struct Y { short X; }; as 'short int'.
3113 if (DS.hasTypeSpecifier())
3114 goto DoneWithDeclSpec;
3116 // If the token is an identifier named "__declspec" and Microsoft
3117 // extensions are not enabled, it is likely that there will be cascading
3118 // parse errors if this really is a __declspec attribute. Attempt to
3119 // recognize that scenario and recover gracefully.
3120 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3121 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3122 Diag(Loc, diag::err_ms_attributes_not_enabled);
3124 // The next token should be an open paren. If it is, eat the entire
3125 // attribute declaration and continue.
3126 if (NextToken().is(tok::l_paren)) {
3127 // Consume the __declspec identifier.
3130 // Eat the parens and everything between them.
3131 BalancedDelimiterTracker T(*this, tok::l_paren);
3132 if (T.consumeOpen()) {
3133 assert(false && "Not a left paren?");
3141 // In C++, check to see if this is a scope specifier like foo::bar::, if
3142 // so handle it as such. This is important for ctor parsing.
3143 if (getLangOpts().CPlusPlus) {
3144 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3145 DS.SetTypeSpecError();
3146 goto DoneWithDeclSpec;
3148 if (!Tok.is(tok::identifier))
3152 // Check for need to substitute AltiVec keyword tokens.
3153 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3156 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3157 // allow the use of a typedef name as a type specifier.
3158 if (DS.isTypeAltiVecVector())
3159 goto DoneWithDeclSpec;
3161 if (DSContext == DSC_objc_method_result && isObjCInstancetype()) {
3162 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3164 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3165 DiagID, TypeRep, Policy);
3169 DS.SetRangeEnd(Loc);
3174 ParsedType TypeRep = Actions.getTypeName(
3175 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3176 false, false, nullptr, false, false,
3177 isClassTemplateDeductionContext(DSContext));
3179 // If this is not a typedef name, don't parse it as part of the declspec,
3180 // it must be an implicit int or an error.
3182 ParsedAttributesWithRange Attrs(AttrFactory);
3183 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3184 if (!Attrs.empty()) {
3185 AttrsLastTime = true;
3186 attrs.takeAllFrom(Attrs);
3190 goto DoneWithDeclSpec;
3193 // If we're in a context where the identifier could be a class name,
3194 // check whether this is a constructor declaration.
3195 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
3196 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3197 isConstructorDeclarator(/*Unqualified*/true))
3198 goto DoneWithDeclSpec;
3200 // Likewise, if this is a context where the identifier could be a template
3201 // name, check whether this is a deduction guide declaration.
3202 if (getLangOpts().CPlusPlus1z &&
3203 (DSContext == DSC_class || DSContext == DSC_top_level) &&
3204 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3205 Tok.getLocation()) &&
3206 isConstructorDeclarator(/*Unqualified*/ true,
3207 /*DeductionGuide*/ true))
3208 goto DoneWithDeclSpec;
3210 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3211 DiagID, TypeRep, Policy);
3215 DS.SetRangeEnd(Tok.getLocation());
3216 ConsumeToken(); // The identifier
3218 // Objective-C supports type arguments and protocol references
3219 // following an Objective-C object or object pointer
3220 // type. Handle either one of them.
3221 if (Tok.is(tok::less) && getLangOpts().ObjC1) {
3222 SourceLocation NewEndLoc;
3223 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3224 Loc, TypeRep, /*consumeLastToken=*/true,
3226 if (NewTypeRep.isUsable()) {
3227 DS.UpdateTypeRep(NewTypeRep.get());
3228 DS.SetRangeEnd(NewEndLoc);
3232 // Need to support trailing type qualifiers (e.g. "id<p> const").
3233 // If a type specifier follows, it will be diagnosed elsewhere.
3238 case tok::annot_template_id: {
3239 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3240 if (TemplateId->Kind != TNK_Type_template) {
3241 // This template-id does not refer to a type name, so we're
3242 // done with the type-specifiers.
3243 goto DoneWithDeclSpec;
3246 // If we're in a context where the template-id could be a
3247 // constructor name or specialization, check whether this is a
3248 // constructor declaration.
3249 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
3250 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3251 isConstructorDeclarator(TemplateId->SS.isEmpty()))
3252 goto DoneWithDeclSpec;
3254 // Turn the template-id annotation token into a type annotation
3255 // token, then try again to parse it as a type-specifier.
3256 AnnotateTemplateIdTokenAsType();
3260 // GNU attributes support.
3261 case tok::kw___attribute:
3262 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3265 // Microsoft declspec support.
3266 case tok::kw___declspec:
3267 ParseMicrosoftDeclSpecs(DS.getAttributes());
3270 // Microsoft single token adornments.
3271 case tok::kw___forceinline: {
3272 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3273 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3274 SourceLocation AttrNameLoc = Tok.getLocation();
3275 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3276 nullptr, 0, AttributeList::AS_Keyword);
3280 case tok::kw___unaligned:
3281 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3285 case tok::kw___sptr:
3286 case tok::kw___uptr:
3287 case tok::kw___ptr64:
3288 case tok::kw___ptr32:
3290 case tok::kw___cdecl:
3291 case tok::kw___stdcall:
3292 case tok::kw___fastcall:
3293 case tok::kw___thiscall:
3294 case tok::kw___regcall:
3295 case tok::kw___vectorcall:
3296 ParseMicrosoftTypeAttributes(DS.getAttributes());
3299 // Borland single token adornments.
3300 case tok::kw___pascal:
3301 ParseBorlandTypeAttributes(DS.getAttributes());
3304 // OpenCL single token adornments.
3305 case tok::kw___kernel:
3306 ParseOpenCLKernelAttributes(DS.getAttributes());
3309 // Nullability type specifiers.
3310 case tok::kw__Nonnull:
3311 case tok::kw__Nullable:
3312 case tok::kw__Null_unspecified:
3313 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3316 // Objective-C 'kindof' types.
3317 case tok::kw___kindof:
3318 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3319 nullptr, 0, AttributeList::AS_Keyword);
3320 (void)ConsumeToken();
3323 // storage-class-specifier
3324 case tok::kw_typedef:
3325 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3326 PrevSpec, DiagID, Policy);
3327 isStorageClass = true;
3329 case tok::kw_extern:
3330 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3331 Diag(Tok, diag::ext_thread_before) << "extern";
3332 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3333 PrevSpec, DiagID, Policy);
3334 isStorageClass = true;
3336 case tok::kw___private_extern__:
3337 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3338 Loc, PrevSpec, DiagID, Policy);
3339 isStorageClass = true;
3341 case tok::kw_static:
3342 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3343 Diag(Tok, diag::ext_thread_before) << "static";
3344 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3345 PrevSpec, DiagID, Policy);
3346 isStorageClass = true;
3349 if (getLangOpts().CPlusPlus11) {
3350 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3351 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3352 PrevSpec, DiagID, Policy);
3354 Diag(Tok, diag::ext_auto_storage_class)
3355 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3357 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3360 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3361 PrevSpec, DiagID, Policy);
3362 isStorageClass = true;
3364 case tok::kw___auto_type:
3365 Diag(Tok, diag::ext_auto_type);
3366 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3369 case tok::kw_register:
3370 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3371 PrevSpec, DiagID, Policy);
3372 isStorageClass = true;
3374 case tok::kw_mutable:
3375 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3376 PrevSpec, DiagID, Policy);
3377 isStorageClass = true;
3379 case tok::kw___thread:
3380 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3382 isStorageClass = true;
3384 case tok::kw_thread_local:
3385 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3388 case tok::kw__Thread_local:
3389 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3390 Loc, PrevSpec, DiagID);
3391 isStorageClass = true;
3394 // function-specifier
3395 case tok::kw_inline:
3396 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3398 case tok::kw_virtual:
3399 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3401 case tok::kw_explicit:
3402 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
3404 case tok::kw__Noreturn:
3405 if (!getLangOpts().C11)
3406 Diag(Loc, diag::ext_c11_noreturn);
3407 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3410 // alignment-specifier
3411 case tok::kw__Alignas:
3412 if (!getLangOpts().C11)
3413 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
3414 ParseAlignmentSpecifier(DS.getAttributes());
3418 case tok::kw_friend:
3419 if (DSContext == DSC_class)
3420 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3422 PrevSpec = ""; // not actually used by the diagnostic
3423 DiagID = diag::err_friend_invalid_in_context;
3429 case tok::kw___module_private__:
3430 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3434 case tok::kw_constexpr:
3435 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3439 case tok::kw_concept:
3440 isInvalid = DS.SetConceptSpec(Loc, PrevSpec, DiagID);
3445 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3449 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
3450 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3453 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3456 case tok::kw___int64:
3457 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3460 case tok::kw_signed:
3461 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3464 case tok::kw_unsigned:
3465 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3468 case tok::kw__Complex:
3469 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3472 case tok::kw__Imaginary:
3473 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3477 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3481 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3485 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3488 case tok::kw___int128:
3489 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3493 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3497 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3500 case tok::kw_double:
3501 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3504 case tok::kw___float128:
3505 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3508 case tok::kw_wchar_t:
3509 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3512 case tok::kw_char16_t:
3513 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3516 case tok::kw_char32_t:
3517 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3522 if (Tok.is(tok::kw_bool) &&
3523 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3524 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3525 PrevSpec = ""; // Not used by the diagnostic.
3526 DiagID = diag::err_bool_redeclaration;
3527 // For better error recovery.
3528 Tok.setKind(tok::identifier);
3531 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3535 case tok::kw__Decimal32:
3536 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3539 case tok::kw__Decimal64:
3540 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3543 case tok::kw__Decimal128:
3544 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3547 case tok::kw___vector:
3548 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3550 case tok::kw___pixel:
3551 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3553 case tok::kw___bool:
3554 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3557 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3558 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3559 // support the "pipe" word as identifier.
3560 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3561 goto DoneWithDeclSpec;
3563 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3565 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
3566 case tok::kw_##ImgType##_t: \
3567 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3570 #include "clang/Basic/OpenCLImageTypes.def"
3571 case tok::kw___unknown_anytype:
3572 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3573 PrevSpec, DiagID, Policy);
3578 case tok::kw_struct:
3579 case tok::kw___interface:
3580 case tok::kw_union: {
3581 tok::TokenKind Kind = Tok.getKind();
3584 // These are attributes following class specifiers.
3585 // To produce better diagnostic, we parse them when
3586 // parsing class specifier.
3587 ParsedAttributesWithRange Attributes(AttrFactory);
3588 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3589 EnteringContext, DSContext, Attributes);
3591 // If there are attributes following class specifier,
3592 // take them over and handle them here.
3593 if (!Attributes.empty()) {
3594 AttrsLastTime = true;
3595 attrs.takeAllFrom(Attributes);
3603 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3608 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3611 case tok::kw_volatile:
3612 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3615 case tok::kw_restrict:
3616 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3620 // C++ typename-specifier:
3621 case tok::kw_typename:
3622 if (TryAnnotateTypeOrScopeToken()) {
3623 DS.SetTypeSpecError();
3624 goto DoneWithDeclSpec;
3626 if (!Tok.is(tok::kw_typename))
3630 // GNU typeof support.
3631 case tok::kw_typeof:
3632 ParseTypeofSpecifier(DS);
3635 case tok::annot_decltype:
3636 ParseDecltypeSpecifier(DS);
3639 case tok::annot_pragma_pack:
3643 case tok::annot_pragma_ms_pragma:
3644 HandlePragmaMSPragma();
3647 case tok::annot_pragma_ms_vtordisp:
3648 HandlePragmaMSVtorDisp();
3651 case tok::annot_pragma_ms_pointers_to_members:
3652 HandlePragmaMSPointersToMembers();
3655 case tok::kw___underlying_type:
3656 ParseUnderlyingTypeSpecifier(DS);
3659 case tok::kw__Atomic:
3661 // If the _Atomic keyword is immediately followed by a left parenthesis,
3662 // it is interpreted as a type specifier (with a type name), not as a
3664 if (NextToken().is(tok::l_paren)) {
3665 ParseAtomicSpecifier(DS);
3668 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3672 // OpenCL qualifiers:
3673 case tok::kw___generic:
3674 // generic address space is introduced only in OpenCL v2.0
3675 // see OpenCL C Spec v2.0 s6.5.5
3676 if (Actions.getLangOpts().OpenCLVersion < 200) {
3677 DiagID = diag::err_opencl_unknown_type_specifier;
3678 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3683 case tok::kw___private:
3684 case tok::kw___global:
3685 case tok::kw___local:
3686 case tok::kw___constant:
3687 case tok::kw___read_only:
3688 case tok::kw___write_only:
3689 case tok::kw___read_write:
3690 ParseOpenCLQualifiers(DS.getAttributes());
3694 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3695 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3696 // but we support it.
3697 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
3698 goto DoneWithDeclSpec;
3700 SourceLocation StartLoc = Tok.getLocation();
3701 SourceLocation EndLoc;
3702 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3703 if (Type.isUsable()) {
3704 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3705 PrevSpec, DiagID, Type.get(),
3706 Actions.getASTContext().getPrintingPolicy()))
3707 Diag(StartLoc, DiagID) << PrevSpec;
3709 DS.SetRangeEnd(EndLoc);
3711 DS.SetTypeSpecError();
3714 // Need to support trailing type qualifiers (e.g. "id<p> const").
3715 // If a type specifier follows, it will be diagnosed elsewhere.
3718 // If the specifier wasn't legal, issue a diagnostic.
3720 assert(PrevSpec && "Method did not return previous specifier!");
3723 if (DiagID == diag::ext_duplicate_declspec)
3725 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
3726 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
3727 const int OpenCLVer = getLangOpts().OpenCLVersion;
3728 std::string VerSpec = llvm::to_string(OpenCLVer / 100) +
3730 llvm::to_string((OpenCLVer % 100) / 10);
3731 Diag(Tok, DiagID) << VerSpec << PrevSpec << isStorageClass;
3733 Diag(Tok, DiagID) << PrevSpec;
3736 DS.SetRangeEnd(Tok.getLocation());
3737 if (DiagID != diag::err_bool_redeclaration)
3740 AttrsLastTime = false;
3744 /// ParseStructDeclaration - Parse a struct declaration without the terminating
3747 /// struct-declaration:
3748 /// specifier-qualifier-list struct-declarator-list
3749 /// [GNU] __extension__ struct-declaration
3750 /// [GNU] specifier-qualifier-list
3751 /// struct-declarator-list:
3752 /// struct-declarator
3753 /// struct-declarator-list ',' struct-declarator
3754 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3755 /// struct-declarator:
3757 /// [GNU] declarator attributes[opt]
3758 /// declarator[opt] ':' constant-expression
3759 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3761 void Parser::ParseStructDeclaration(
3762 ParsingDeclSpec &DS,
3763 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
3765 if (Tok.is(tok::kw___extension__)) {
3766 // __extension__ silences extension warnings in the subexpression.
3767 ExtensionRAIIObject O(Diags); // Use RAII to do this.
3769 return ParseStructDeclaration(DS, FieldsCallback);
3772 // Parse the common specifier-qualifiers-list piece.
3773 ParseSpecifierQualifierList(DS);
3775 // If there are no declarators, this is a free-standing declaration
3776 // specifier. Let the actions module cope with it.
3777 if (Tok.is(tok::semi)) {
3778 RecordDecl *AnonRecord = nullptr;
3779 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
3781 assert(!AnonRecord && "Did not expect anonymous struct or union here");
3782 DS.complete(TheDecl);
3786 // Read struct-declarators until we find the semicolon.
3787 bool FirstDeclarator = true;
3788 SourceLocation CommaLoc;
3790 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
3791 DeclaratorInfo.D.setCommaLoc(CommaLoc);
3793 // Attributes are only allowed here on successive declarators.
3794 if (!FirstDeclarator)
3795 MaybeParseGNUAttributes(DeclaratorInfo.D);
3797 /// struct-declarator: declarator
3798 /// struct-declarator: declarator[opt] ':' constant-expression
3799 if (Tok.isNot(tok::colon)) {
3800 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3801 ColonProtectionRAIIObject X(*this);
3802 ParseDeclarator(DeclaratorInfo.D);
3804 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
3806 if (TryConsumeToken(tok::colon)) {
3807 ExprResult Res(ParseConstantExpression());
3808 if (Res.isInvalid())
3809 SkipUntil(tok::semi, StopBeforeMatch);
3811 DeclaratorInfo.BitfieldSize = Res.get();
3814 // If attributes exist after the declarator, parse them.
3815 MaybeParseGNUAttributes(DeclaratorInfo.D);
3817 // We're done with this declarator; invoke the callback.
3818 FieldsCallback(DeclaratorInfo);
3820 // If we don't have a comma, it is either the end of the list (a ';')
3821 // or an error, bail out.
3822 if (!TryConsumeToken(tok::comma, CommaLoc))
3825 FirstDeclarator = false;
3829 /// ParseStructUnionBody
3830 /// struct-contents:
3831 /// struct-declaration-list
3833 /// [GNU] "struct-declaration-list" without terminatoring ';'
3834 /// struct-declaration-list:
3835 /// struct-declaration
3836 /// struct-declaration-list struct-declaration
3837 /// [OBC] '@' 'defs' '(' class-name ')'
3839 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
3840 unsigned TagType, Decl *TagDecl) {
3841 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3842 "parsing struct/union body");
3843 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
3845 BalancedDelimiterTracker T(*this, tok::l_brace);
3846 if (T.consumeOpen())
3849 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
3850 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3852 SmallVector<Decl *, 32> FieldDecls;
3854 // While we still have something to read, read the declarations in the struct.
3855 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3856 Tok.isNot(tok::eof)) {
3857 // Each iteration of this loop reads one struct-declaration.
3859 // Check for extraneous top-level semicolon.
3860 if (Tok.is(tok::semi)) {
3861 ConsumeExtraSemi(InsideStruct, TagType);
3865 // Parse _Static_assert declaration.
3866 if (Tok.is(tok::kw__Static_assert)) {
3867 SourceLocation DeclEnd;
3868 ParseStaticAssertDeclaration(DeclEnd);
3872 if (Tok.is(tok::annot_pragma_pack)) {
3877 if (Tok.is(tok::annot_pragma_align)) {
3878 HandlePragmaAlign();
3882 if (Tok.is(tok::annot_pragma_openmp)) {
3883 // Result can be ignored, because it must be always empty.
3884 AccessSpecifier AS = AS_none;
3885 ParsedAttributesWithRange Attrs(AttrFactory);
3886 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
3890 if (!Tok.is(tok::at)) {
3891 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
3892 // Install the declarator into the current TagDecl.
3894 Actions.ActOnField(getCurScope(), TagDecl,
3895 FD.D.getDeclSpec().getSourceRange().getBegin(),
3896 FD.D, FD.BitfieldSize);
3897 FieldDecls.push_back(Field);
3901 // Parse all the comma separated declarators.
3902 ParsingDeclSpec DS(*this);
3903 ParseStructDeclaration(DS, CFieldCallback);
3904 } else { // Handle @defs
3906 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
3907 Diag(Tok, diag::err_unexpected_at);
3908 SkipUntil(tok::semi);
3912 ExpectAndConsume(tok::l_paren);
3913 if (!Tok.is(tok::identifier)) {
3914 Diag(Tok, diag::err_expected) << tok::identifier;
3915 SkipUntil(tok::semi);
3918 SmallVector<Decl *, 16> Fields;
3919 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
3920 Tok.getIdentifierInfo(), Fields);
3921 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
3923 ExpectAndConsume(tok::r_paren);
3926 if (TryConsumeToken(tok::semi))
3929 if (Tok.is(tok::r_brace)) {
3930 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
3934 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
3935 // Skip to end of block or statement to avoid ext-warning on extra ';'.
3936 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
3937 // If we stopped at a ';', eat it.
3938 TryConsumeToken(tok::semi);
3943 ParsedAttributes attrs(AttrFactory);
3944 // If attributes exist after struct contents, parse them.
3945 MaybeParseGNUAttributes(attrs);
3947 Actions.ActOnFields(getCurScope(),
3948 RecordLoc, TagDecl, FieldDecls,
3949 T.getOpenLocation(), T.getCloseLocation(),
3952 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
3955 /// ParseEnumSpecifier
3956 /// enum-specifier: [C99 6.7.2.2]
3957 /// 'enum' identifier[opt] '{' enumerator-list '}'
3958 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
3959 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
3960 /// '}' attributes[opt]
3961 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
3963 /// 'enum' identifier
3964 /// [GNU] 'enum' attributes[opt] identifier
3966 /// [C++11] enum-head '{' enumerator-list[opt] '}'
3967 /// [C++11] enum-head '{' enumerator-list ',' '}'
3969 /// enum-head: [C++11]
3970 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
3971 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
3972 /// identifier enum-base[opt]
3974 /// enum-key: [C++11]
3979 /// enum-base: [C++11]
3980 /// ':' type-specifier-seq
3982 /// [C++] elaborated-type-specifier:
3983 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
3985 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
3986 const ParsedTemplateInfo &TemplateInfo,
3987 AccessSpecifier AS, DeclSpecContext DSC) {
3988 // Parse the tag portion of this.
3989 if (Tok.is(tok::code_completion)) {
3990 // Code completion for an enum name.
3991 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
3992 return cutOffParsing();
3995 // If attributes exist after tag, parse them.
3996 ParsedAttributesWithRange attrs(AttrFactory);
3997 MaybeParseGNUAttributes(attrs);
3998 MaybeParseCXX11Attributes(attrs);
3999 MaybeParseMicrosoftDeclSpecs(attrs);
4001 SourceLocation ScopedEnumKWLoc;
4002 bool IsScopedUsingClassTag = false;
4004 // In C++11, recognize 'enum class' and 'enum struct'.
4005 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4006 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4007 : diag::ext_scoped_enum);
4008 IsScopedUsingClassTag = Tok.is(tok::kw_class);
4009 ScopedEnumKWLoc = ConsumeToken();
4011 // Attributes are not allowed between these keywords. Diagnose,
4012 // but then just treat them like they appeared in the right place.
4013 ProhibitAttributes(attrs);
4015 // They are allowed afterwards, though.
4016 MaybeParseGNUAttributes(attrs);
4017 MaybeParseCXX11Attributes(attrs);
4018 MaybeParseMicrosoftDeclSpecs(attrs);
4021 // C++11 [temp.explicit]p12:
4022 // The usual access controls do not apply to names used to specify
4023 // explicit instantiations.
4024 // We extend this to also cover explicit specializations. Note that
4025 // we don't suppress if this turns out to be an elaborated type
4027 bool shouldDelayDiagsInTag =
4028 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4029 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4030 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4032 // Enum definitions should not be parsed in a trailing-return-type.
4033 bool AllowDeclaration = DSC != DSC_trailing;
4035 bool AllowFixedUnderlyingType = AllowDeclaration &&
4036 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
4037 getLangOpts().ObjC2);
4039 CXXScopeSpec &SS = DS.getTypeSpecScope();
4040 if (getLangOpts().CPlusPlus) {
4041 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4042 // if a fixed underlying type is allowed.
4043 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
4046 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
4047 /*EnteringContext=*/true))
4050 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4051 Diag(Tok, diag::err_expected) << tok::identifier;
4052 if (Tok.isNot(tok::l_brace)) {
4053 // Has no name and is not a definition.
4054 // Skip the rest of this declarator, up until the comma or semicolon.
4055 SkipUntil(tok::comma, StopAtSemi);
4063 // Must have either 'enum name' or 'enum {...}'.
4064 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4065 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
4066 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4068 // Skip the rest of this declarator, up until the comma or semicolon.
4069 SkipUntil(tok::comma, StopAtSemi);
4073 // If an identifier is present, consume and remember it.
4074 IdentifierInfo *Name = nullptr;
4075 SourceLocation NameLoc;
4076 if (Tok.is(tok::identifier)) {
4077 Name = Tok.getIdentifierInfo();
4078 NameLoc = ConsumeToken();
4081 if (!Name && ScopedEnumKWLoc.isValid()) {
4082 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4083 // declaration of a scoped enumeration.
4084 Diag(Tok, diag::err_scoped_enum_missing_identifier);
4085 ScopedEnumKWLoc = SourceLocation();
4086 IsScopedUsingClassTag = false;
4089 // Okay, end the suppression area. We'll decide whether to emit the
4090 // diagnostics in a second.
4091 if (shouldDelayDiagsInTag)
4092 diagsFromTag.done();
4094 TypeResult BaseType;
4096 // Parse the fixed underlying type.
4097 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4098 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
4099 bool PossibleBitfield = false;
4100 if (CanBeBitfield) {
4101 // If we're in class scope, this can either be an enum declaration with
4102 // an underlying type, or a declaration of a bitfield member. We try to
4103 // use a simple disambiguation scheme first to catch the common cases
4104 // (integer literal, sizeof); if it's still ambiguous, we then consider
4105 // anything that's a simple-type-specifier followed by '(' as an
4106 // expression. This suffices because function types are not valid
4107 // underlying types anyway.
4108 EnterExpressionEvaluationContext Unevaluated(
4109 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4110 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
4111 // If the next token starts an expression, we know we're parsing a
4112 // bit-field. This is the common case.
4113 if (TPR == TPResult::True)
4114 PossibleBitfield = true;
4115 // If the next token starts a type-specifier-seq, it may be either a
4116 // a fixed underlying type or the start of a function-style cast in C++;
4117 // lookahead one more token to see if it's obvious that we have a
4118 // fixed underlying type.
4119 else if (TPR == TPResult::False &&
4120 GetLookAheadToken(2).getKind() == tok::semi) {
4124 // We have the start of a type-specifier-seq, so we have to perform
4125 // tentative parsing to determine whether we have an expression or a
4127 TentativeParsingAction TPA(*this);
4132 // If we see a type specifier followed by an open-brace, we have an
4133 // ambiguity between an underlying type and a C++11 braced
4134 // function-style cast. Resolve this by always treating it as an
4136 // FIXME: The standard is not entirely clear on how to disambiguate in
4138 if ((getLangOpts().CPlusPlus &&
4139 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
4140 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
4141 // We'll parse this as a bitfield later.
4142 PossibleBitfield = true;
4145 // We have a type-specifier-seq.
4154 if (!PossibleBitfield) {
4156 BaseType = ParseTypeName(&Range);
4158 if (getLangOpts().CPlusPlus11) {
4159 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4160 } else if (!getLangOpts().ObjC2) {
4161 if (getLangOpts().CPlusPlus)
4162 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
4164 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
4169 // There are four options here. If we have 'friend enum foo;' then this is a
4170 // friend declaration, and cannot have an accompanying definition. If we have
4171 // 'enum foo;', then this is a forward declaration. If we have
4172 // 'enum foo {...' then this is a definition. Otherwise we have something
4173 // like 'enum foo xyz', a reference.
4175 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4176 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4177 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4179 Sema::TagUseKind TUK;
4180 if (!AllowDeclaration) {
4181 TUK = Sema::TUK_Reference;
4182 } else if (Tok.is(tok::l_brace)) {
4183 if (DS.isFriendSpecified()) {
4184 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4185 << SourceRange(DS.getFriendSpecLoc());
4187 SkipUntil(tok::r_brace, StopAtSemi);
4188 TUK = Sema::TUK_Friend;
4190 TUK = Sema::TUK_Definition;
4192 } else if (!isTypeSpecifier(DSC) &&
4193 (Tok.is(tok::semi) ||
4194 (Tok.isAtStartOfLine() &&
4195 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4196 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4197 if (Tok.isNot(tok::semi)) {
4198 // A semicolon was missing after this declaration. Diagnose and recover.
4199 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4201 Tok.setKind(tok::semi);
4204 TUK = Sema::TUK_Reference;
4207 // If this is an elaborated type specifier, and we delayed
4208 // diagnostics before, just merge them into the current pool.
4209 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4210 diagsFromTag.redelay();
4213 MultiTemplateParamsArg TParams;
4214 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4215 TUK != Sema::TUK_Reference) {
4216 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4217 // Skip the rest of this declarator, up until the comma or semicolon.
4218 Diag(Tok, diag::err_enum_template);
4219 SkipUntil(tok::comma, StopAtSemi);
4223 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4224 // Enumerations can't be explicitly instantiated.
4225 DS.SetTypeSpecError();
4226 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4230 assert(TemplateInfo.TemplateParams && "no template parameters");
4231 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4232 TemplateInfo.TemplateParams->size());
4235 if (TUK == Sema::TUK_Reference)
4236 ProhibitAttributes(attrs);
4238 if (!Name && TUK != Sema::TUK_Definition) {
4239 Diag(Tok, diag::err_enumerator_unnamed_no_def);
4241 // Skip the rest of this declarator, up until the comma or semicolon.
4242 SkipUntil(tok::comma, StopAtSemi);
4246 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4248 Sema::SkipBodyInfo SkipBody;
4249 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4250 NextToken().is(tok::identifier))
4251 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4252 NextToken().getIdentifierInfo(),
4253 NextToken().getLocation());
4256 bool IsDependent = false;
4257 const char *PrevSpec = nullptr;
4259 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
4260 StartLoc, SS, Name, NameLoc, attrs.getList(),
4261 AS, DS.getModulePrivateSpecLoc(), TParams,
4262 Owned, IsDependent, ScopedEnumKWLoc,
4263 IsScopedUsingClassTag, BaseType,
4264 DSC == DSC_type_specifier, &SkipBody);
4266 if (SkipBody.ShouldSkip) {
4267 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4269 BalancedDelimiterTracker T(*this, tok::l_brace);
4273 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4274 NameLoc.isValid() ? NameLoc : StartLoc,
4275 PrevSpec, DiagID, TagDecl, Owned,
4276 Actions.getASTContext().getPrintingPolicy()))
4277 Diag(StartLoc, DiagID) << PrevSpec;
4282 // This enum has a dependent nested-name-specifier. Handle it as a
4285 DS.SetTypeSpecError();
4286 Diag(Tok, diag::err_expected_type_name_after_typename);
4290 TypeResult Type = Actions.ActOnDependentTag(
4291 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4292 if (Type.isInvalid()) {
4293 DS.SetTypeSpecError();
4297 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4298 NameLoc.isValid() ? NameLoc : StartLoc,
4299 PrevSpec, DiagID, Type.get(),
4300 Actions.getASTContext().getPrintingPolicy()))
4301 Diag(StartLoc, DiagID) << PrevSpec;
4307 // The action failed to produce an enumeration tag. If this is a
4308 // definition, consume the entire definition.
4309 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4311 SkipUntil(tok::r_brace, StopAtSemi);
4314 DS.SetTypeSpecError();
4318 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference)
4319 ParseEnumBody(StartLoc, TagDecl);
4321 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4322 NameLoc.isValid() ? NameLoc : StartLoc,
4323 PrevSpec, DiagID, TagDecl, Owned,
4324 Actions.getASTContext().getPrintingPolicy()))
4325 Diag(StartLoc, DiagID) << PrevSpec;
4328 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4329 /// enumerator-list:
4331 /// enumerator-list ',' enumerator
4333 /// enumeration-constant attributes[opt]
4334 /// enumeration-constant attributes[opt] '=' constant-expression
4335 /// enumeration-constant:
4338 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4339 // Enter the scope of the enum body and start the definition.
4340 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4341 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4343 BalancedDelimiterTracker T(*this, tok::l_brace);
4346 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4347 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4348 Diag(Tok, diag::err_empty_enum);
4350 SmallVector<Decl *, 32> EnumConstantDecls;
4351 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4353 Decl *LastEnumConstDecl = nullptr;
4355 // Parse the enumerator-list.
4356 while (Tok.isNot(tok::r_brace)) {
4357 // Parse enumerator. If failed, try skipping till the start of the next
4358 // enumerator definition.
4359 if (Tok.isNot(tok::identifier)) {
4360 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4361 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4362 TryConsumeToken(tok::comma))
4366 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4367 SourceLocation IdentLoc = ConsumeToken();
4369 // If attributes exist after the enumerator, parse them.
4370 ParsedAttributesWithRange attrs(AttrFactory);
4371 MaybeParseGNUAttributes(attrs);
4372 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4373 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
4374 if (!getLangOpts().CPlusPlus1z)
4375 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
4376 << 1 /*enumerator*/;
4377 ParseCXX11Attributes(attrs);
4380 SourceLocation EqualLoc;
4381 ExprResult AssignedVal;
4382 EnumAvailabilityDiags.emplace_back(*this);
4384 if (TryConsumeToken(tok::equal, EqualLoc)) {
4385 AssignedVal = ParseConstantExpression();
4386 if (AssignedVal.isInvalid())
4387 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4390 // Install the enumerator constant into EnumDecl.
4391 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
4394 attrs.getList(), EqualLoc,
4396 EnumAvailabilityDiags.back().done();
4398 EnumConstantDecls.push_back(EnumConstDecl);
4399 LastEnumConstDecl = EnumConstDecl;
4401 if (Tok.is(tok::identifier)) {
4402 // We're missing a comma between enumerators.
4403 SourceLocation Loc = getEndOfPreviousToken();
4404 Diag(Loc, diag::err_enumerator_list_missing_comma)
4405 << FixItHint::CreateInsertion(Loc, ", ");
4409 // Emumerator definition must be finished, only comma or r_brace are
4411 SourceLocation CommaLoc;
4412 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4413 if (EqualLoc.isValid())
4414 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4417 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4418 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4419 if (TryConsumeToken(tok::comma, CommaLoc))
4426 // If comma is followed by r_brace, emit appropriate warning.
4427 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4428 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4429 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4430 diag::ext_enumerator_list_comma_cxx :
4431 diag::ext_enumerator_list_comma_c)
4432 << FixItHint::CreateRemoval(CommaLoc);
4433 else if (getLangOpts().CPlusPlus11)
4434 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4435 << FixItHint::CreateRemoval(CommaLoc);
4443 // If attributes exist after the identifier list, parse them.
4444 ParsedAttributes attrs(AttrFactory);
4445 MaybeParseGNUAttributes(attrs);
4447 Actions.ActOnEnumBody(StartLoc, T.getRange(),
4448 EnumDecl, EnumConstantDecls,
4452 // Now handle enum constant availability diagnostics.
4453 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4454 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4455 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4456 EnumAvailabilityDiags[i].redelay();
4457 PD.complete(EnumConstantDecls[i]);
4461 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4463 // The next token must be valid after an enum definition. If not, a ';'
4464 // was probably forgotten.
4465 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4466 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4467 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4468 // Push this token back into the preprocessor and change our current token
4469 // to ';' so that the rest of the code recovers as though there were an
4470 // ';' after the definition.
4472 Tok.setKind(tok::semi);
4476 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4477 /// is definitely a type-specifier. Return false if it isn't part of a type
4478 /// specifier or if we're not sure.
4479 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4480 switch (Tok.getKind()) {
4481 default: return false;
4485 case tok::kw___int64:
4486 case tok::kw___int128:
4487 case tok::kw_signed:
4488 case tok::kw_unsigned:
4489 case tok::kw__Complex:
4490 case tok::kw__Imaginary:
4493 case tok::kw_wchar_t:
4494 case tok::kw_char16_t:
4495 case tok::kw_char32_t:
4499 case tok::kw_double:
4500 case tok::kw___float128:
4503 case tok::kw__Decimal32:
4504 case tok::kw__Decimal64:
4505 case tok::kw__Decimal128:
4506 case tok::kw___vector:
4507 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4508 #include "clang/Basic/OpenCLImageTypes.def"
4510 // struct-or-union-specifier (C99) or class-specifier (C++)
4512 case tok::kw_struct:
4513 case tok::kw___interface:
4519 case tok::annot_typename:
4524 /// isTypeSpecifierQualifier - Return true if the current token could be the
4525 /// start of a specifier-qualifier-list.
4526 bool Parser::isTypeSpecifierQualifier() {
4527 switch (Tok.getKind()) {
4528 default: return false;
4530 case tok::identifier: // foo::bar
4531 if (TryAltiVecVectorToken())
4534 case tok::kw_typename: // typename T::type
4535 // Annotate typenames and C++ scope specifiers. If we get one, just
4536 // recurse to handle whatever we get.
4537 if (TryAnnotateTypeOrScopeToken())
4539 if (Tok.is(tok::identifier))
4541 return isTypeSpecifierQualifier();
4543 case tok::coloncolon: // ::foo::bar
4544 if (NextToken().is(tok::kw_new) || // ::new
4545 NextToken().is(tok::kw_delete)) // ::delete
4548 if (TryAnnotateTypeOrScopeToken())
4550 return isTypeSpecifierQualifier();
4552 // GNU attributes support.
4553 case tok::kw___attribute:
4554 // GNU typeof support.
4555 case tok::kw_typeof:
4560 case tok::kw___int64:
4561 case tok::kw___int128:
4562 case tok::kw_signed:
4563 case tok::kw_unsigned:
4564 case tok::kw__Complex:
4565 case tok::kw__Imaginary:
4568 case tok::kw_wchar_t:
4569 case tok::kw_char16_t:
4570 case tok::kw_char32_t:
4574 case tok::kw_double:
4575 case tok::kw___float128:
4578 case tok::kw__Decimal32:
4579 case tok::kw__Decimal64:
4580 case tok::kw__Decimal128:
4581 case tok::kw___vector:
4582 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4583 #include "clang/Basic/OpenCLImageTypes.def"
4585 // struct-or-union-specifier (C99) or class-specifier (C++)
4587 case tok::kw_struct:
4588 case tok::kw___interface:
4595 case tok::kw_volatile:
4596 case tok::kw_restrict:
4598 // Debugger support.
4599 case tok::kw___unknown_anytype:
4602 case tok::annot_typename:
4605 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4607 return getLangOpts().ObjC1;
4609 case tok::kw___cdecl:
4610 case tok::kw___stdcall:
4611 case tok::kw___fastcall:
4612 case tok::kw___thiscall:
4613 case tok::kw___regcall:
4614 case tok::kw___vectorcall:
4616 case tok::kw___ptr64:
4617 case tok::kw___ptr32:
4618 case tok::kw___pascal:
4619 case tok::kw___unaligned:
4621 case tok::kw__Nonnull:
4622 case tok::kw__Nullable:
4623 case tok::kw__Null_unspecified:
4625 case tok::kw___kindof:
4627 case tok::kw___private:
4628 case tok::kw___local:
4629 case tok::kw___global:
4630 case tok::kw___constant:
4631 case tok::kw___generic:
4632 case tok::kw___read_only:
4633 case tok::kw___read_write:
4634 case tok::kw___write_only:
4639 case tok::kw__Atomic:
4644 /// isDeclarationSpecifier() - Return true if the current token is part of a
4645 /// declaration specifier.
4647 /// \param DisambiguatingWithExpression True to indicate that the purpose of
4648 /// this check is to disambiguate between an expression and a declaration.
4649 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4650 switch (Tok.getKind()) {
4651 default: return false;
4654 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4656 case tok::identifier: // foo::bar
4657 // Unfortunate hack to support "Class.factoryMethod" notation.
4658 if (getLangOpts().ObjC1 && NextToken().is(tok::period))
4660 if (TryAltiVecVectorToken())
4663 case tok::kw_decltype: // decltype(T())::type
4664 case tok::kw_typename: // typename T::type
4665 // Annotate typenames and C++ scope specifiers. If we get one, just
4666 // recurse to handle whatever we get.
4667 if (TryAnnotateTypeOrScopeToken())
4669 if (Tok.is(tok::identifier))
4672 // If we're in Objective-C and we have an Objective-C class type followed
4673 // by an identifier and then either ':' or ']', in a place where an
4674 // expression is permitted, then this is probably a class message send
4675 // missing the initial '['. In this case, we won't consider this to be
4676 // the start of a declaration.
4677 if (DisambiguatingWithExpression &&
4678 isStartOfObjCClassMessageMissingOpenBracket())
4681 return isDeclarationSpecifier();
4683 case tok::coloncolon: // ::foo::bar
4684 if (NextToken().is(tok::kw_new) || // ::new
4685 NextToken().is(tok::kw_delete)) // ::delete
4688 // Annotate typenames and C++ scope specifiers. If we get one, just
4689 // recurse to handle whatever we get.
4690 if (TryAnnotateTypeOrScopeToken())
4692 return isDeclarationSpecifier();
4694 // storage-class-specifier
4695 case tok::kw_typedef:
4696 case tok::kw_extern:
4697 case tok::kw___private_extern__:
4698 case tok::kw_static:
4700 case tok::kw___auto_type:
4701 case tok::kw_register:
4702 case tok::kw___thread:
4703 case tok::kw_thread_local:
4704 case tok::kw__Thread_local:
4707 case tok::kw___module_private__:
4710 case tok::kw___unknown_anytype:
4715 case tok::kw___int64:
4716 case tok::kw___int128:
4717 case tok::kw_signed:
4718 case tok::kw_unsigned:
4719 case tok::kw__Complex:
4720 case tok::kw__Imaginary:
4723 case tok::kw_wchar_t:
4724 case tok::kw_char16_t:
4725 case tok::kw_char32_t:
4730 case tok::kw_double:
4731 case tok::kw___float128:
4734 case tok::kw__Decimal32:
4735 case tok::kw__Decimal64:
4736 case tok::kw__Decimal128:
4737 case tok::kw___vector:
4739 // struct-or-union-specifier (C99) or class-specifier (C++)
4741 case tok::kw_struct:
4743 case tok::kw___interface:
4749 case tok::kw_volatile:
4750 case tok::kw_restrict:
4752 // function-specifier
4753 case tok::kw_inline:
4754 case tok::kw_virtual:
4755 case tok::kw_explicit:
4756 case tok::kw__Noreturn:
4758 // alignment-specifier
4759 case tok::kw__Alignas:
4762 case tok::kw_friend:
4764 // static_assert-declaration
4765 case tok::kw__Static_assert:
4767 // GNU typeof support.
4768 case tok::kw_typeof:
4771 case tok::kw___attribute:
4773 // C++11 decltype and constexpr.
4774 case tok::annot_decltype:
4775 case tok::kw_constexpr:
4777 // C++ Concepts TS - concept
4778 case tok::kw_concept:
4781 case tok::kw__Atomic:
4784 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4786 return getLangOpts().ObjC1;
4789 case tok::annot_typename:
4790 return !DisambiguatingWithExpression ||
4791 !isStartOfObjCClassMessageMissingOpenBracket();
4793 case tok::kw___declspec:
4794 case tok::kw___cdecl:
4795 case tok::kw___stdcall:
4796 case tok::kw___fastcall:
4797 case tok::kw___thiscall:
4798 case tok::kw___regcall:
4799 case tok::kw___vectorcall:
4801 case tok::kw___sptr:
4802 case tok::kw___uptr:
4803 case tok::kw___ptr64:
4804 case tok::kw___ptr32:
4805 case tok::kw___forceinline:
4806 case tok::kw___pascal:
4807 case tok::kw___unaligned:
4809 case tok::kw__Nonnull:
4810 case tok::kw__Nullable:
4811 case tok::kw__Null_unspecified:
4813 case tok::kw___kindof:
4815 case tok::kw___private:
4816 case tok::kw___local:
4817 case tok::kw___global:
4818 case tok::kw___constant:
4819 case tok::kw___generic:
4820 case tok::kw___read_only:
4821 case tok::kw___read_write:
4822 case tok::kw___write_only:
4823 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4824 #include "clang/Basic/OpenCLImageTypes.def"
4830 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
4831 TentativeParsingAction TPA(*this);
4833 // Parse the C++ scope specifier.
4835 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
4836 /*EnteringContext=*/true)) {
4841 // Parse the constructor name.
4842 if (Tok.is(tok::identifier)) {
4843 // We already know that we have a constructor name; just consume
4846 } else if (Tok.is(tok::annot_template_id)) {
4847 ConsumeAnnotationToken();
4853 // There may be attributes here, appertaining to the constructor name or type
4854 // we just stepped past.
4855 SkipCXX11Attributes();
4857 // Current class name must be followed by a left parenthesis.
4858 if (Tok.isNot(tok::l_paren)) {
4864 // A right parenthesis, or ellipsis followed by a right parenthesis signals
4865 // that we have a constructor.
4866 if (Tok.is(tok::r_paren) ||
4867 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
4872 // A C++11 attribute here signals that we have a constructor, and is an
4873 // attribute on the first constructor parameter.
4874 if (getLangOpts().CPlusPlus11 &&
4875 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
4876 /*OuterMightBeMessageSend*/ true)) {
4881 // If we need to, enter the specified scope.
4882 DeclaratorScopeObj DeclScopeObj(*this, SS);
4883 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
4884 DeclScopeObj.EnterDeclaratorScope();
4886 // Optionally skip Microsoft attributes.
4887 ParsedAttributes Attrs(AttrFactory);
4888 MaybeParseMicrosoftAttributes(Attrs);
4890 // Check whether the next token(s) are part of a declaration
4891 // specifier, in which case we have the start of a parameter and,
4892 // therefore, we know that this is a constructor.
4893 bool IsConstructor = false;
4894 if (isDeclarationSpecifier())
4895 IsConstructor = true;
4896 else if (Tok.is(tok::identifier) ||
4897 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
4898 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
4899 // This might be a parenthesized member name, but is more likely to
4900 // be a constructor declaration with an invalid argument type. Keep
4902 if (Tok.is(tok::annot_cxxscope))
4903 ConsumeAnnotationToken();
4906 // If this is not a constructor, we must be parsing a declarator,
4907 // which must have one of the following syntactic forms (see the
4908 // grammar extract at the start of ParseDirectDeclarator):
4909 switch (Tok.getKind()) {
4914 // C(X [ [attribute]]);
4915 case tok::coloncolon:
4918 // Assume this isn't a constructor, rather than assuming it's a
4919 // constructor with an unnamed parameter of an ill-formed type.
4925 // Skip past the right-paren and any following attributes to get to
4926 // the function body or trailing-return-type.
4928 SkipCXX11Attributes();
4930 if (DeductionGuide) {
4931 // C(X) -> ... is a deduction guide.
4932 IsConstructor = Tok.is(tok::arrow);
4935 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
4936 // Assume these were meant to be constructors:
4937 // C(X) : (the name of a bit-field cannot be parenthesized).
4938 // C(X) try (this is otherwise ill-formed).
4939 IsConstructor = true;
4941 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
4942 // If we have a constructor name within the class definition,
4943 // assume these were meant to be constructors:
4946 // ... because otherwise we would be declaring a non-static data
4947 // member that is ill-formed because it's of the same type as its
4948 // surrounding class.
4950 // FIXME: We can actually do this whether or not the name is qualified,
4951 // because if it is qualified in this context it must be being used as
4952 // a constructor name.
4953 // currently, so we're somewhat conservative here.
4954 IsConstructor = IsUnqualified;
4959 IsConstructor = true;
4965 return IsConstructor;
4968 /// ParseTypeQualifierListOpt
4969 /// type-qualifier-list: [C99 6.7.5]
4971 /// [vendor] attributes
4972 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
4973 /// type-qualifier-list type-qualifier
4974 /// [vendor] type-qualifier-list attributes
4975 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
4976 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
4977 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
4978 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
4979 /// AttrRequirements bitmask values.
4980 void Parser::ParseTypeQualifierListOpt(
4981 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
4982 bool IdentifierRequired,
4983 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
4984 if (getLangOpts().CPlusPlus11 && (AttrReqs & AR_CXX11AttributesParsed) &&
4985 isCXX11AttributeSpecifier()) {
4986 ParsedAttributesWithRange attrs(AttrFactory);
4987 ParseCXX11Attributes(attrs);
4988 DS.takeAttributesFrom(attrs);
4991 SourceLocation EndLoc;
4994 bool isInvalid = false;
4995 const char *PrevSpec = nullptr;
4996 unsigned DiagID = 0;
4997 SourceLocation Loc = Tok.getLocation();
4999 switch (Tok.getKind()) {
5000 case tok::code_completion:
5001 if (CodeCompletionHandler)
5002 (*CodeCompletionHandler)();
5004 Actions.CodeCompleteTypeQualifiers(DS);
5005 return cutOffParsing();
5008 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
5011 case tok::kw_volatile:
5012 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5015 case tok::kw_restrict:
5016 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5019 case tok::kw__Atomic:
5021 goto DoneWithTypeQuals;
5022 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5026 // OpenCL qualifiers:
5027 case tok::kw___private:
5028 case tok::kw___global:
5029 case tok::kw___local:
5030 case tok::kw___constant:
5031 case tok::kw___generic:
5032 case tok::kw___read_only:
5033 case tok::kw___write_only:
5034 case tok::kw___read_write:
5035 ParseOpenCLQualifiers(DS.getAttributes());
5038 case tok::kw___unaligned:
5039 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5042 case tok::kw___uptr:
5043 // GNU libc headers in C mode use '__uptr' as an identifer which conflicts
5044 // with the MS modifier keyword.
5045 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
5046 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5047 if (TryKeywordIdentFallback(false))
5051 case tok::kw___sptr:
5053 case tok::kw___ptr64:
5054 case tok::kw___ptr32:
5055 case tok::kw___cdecl:
5056 case tok::kw___stdcall:
5057 case tok::kw___fastcall:
5058 case tok::kw___thiscall:
5059 case tok::kw___regcall:
5060 case tok::kw___vectorcall:
5061 if (AttrReqs & AR_DeclspecAttributesParsed) {
5062 ParseMicrosoftTypeAttributes(DS.getAttributes());
5065 goto DoneWithTypeQuals;
5066 case tok::kw___pascal:
5067 if (AttrReqs & AR_VendorAttributesParsed) {
5068 ParseBorlandTypeAttributes(DS.getAttributes());
5071 goto DoneWithTypeQuals;
5073 // Nullability type specifiers.
5074 case tok::kw__Nonnull:
5075 case tok::kw__Nullable:
5076 case tok::kw__Null_unspecified:
5077 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5080 // Objective-C 'kindof' types.
5081 case tok::kw___kindof:
5082 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
5083 nullptr, 0, AttributeList::AS_Keyword);
5084 (void)ConsumeToken();
5087 case tok::kw___attribute:
5088 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5089 // When GNU attributes are expressly forbidden, diagnose their usage.
5090 Diag(Tok, diag::err_attributes_not_allowed);
5092 // Parse the attributes even if they are rejected to ensure that error
5093 // recovery is graceful.
5094 if (AttrReqs & AR_GNUAttributesParsed ||
5095 AttrReqs & AR_GNUAttributesParsedAndRejected) {
5096 ParseGNUAttributes(DS.getAttributes());
5097 continue; // do *not* consume the next token!
5099 // otherwise, FALL THROUGH!
5103 // If this is not a type-qualifier token, we're done reading type
5104 // qualifiers. First verify that DeclSpec's are consistent.
5105 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
5106 if (EndLoc.isValid())
5107 DS.SetRangeEnd(EndLoc);
5111 // If the specifier combination wasn't legal, issue a diagnostic.
5113 assert(PrevSpec && "Method did not return previous specifier!");
5114 Diag(Tok, DiagID) << PrevSpec;
5116 EndLoc = ConsumeToken();
5120 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
5122 void Parser::ParseDeclarator(Declarator &D) {
5123 /// This implements the 'declarator' production in the C grammar, then checks
5124 /// for well-formedness and issues diagnostics.
5125 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5128 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
5129 unsigned TheContext) {
5130 if (Kind == tok::star || Kind == tok::caret)
5133 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
5136 if (!Lang.CPlusPlus)
5139 if (Kind == tok::amp)
5142 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5143 // But we must not parse them in conversion-type-ids and new-type-ids, since
5144 // those can be legitimately followed by a && operator.
5145 // (The same thing can in theory happen after a trailing-return-type, but
5146 // since those are a C++11 feature, there is no rejects-valid issue there.)
5147 if (Kind == tok::ampamp)
5148 return Lang.CPlusPlus11 || (TheContext != Declarator::ConversionIdContext &&
5149 TheContext != Declarator::CXXNewContext);
5154 // Indicates whether the given declarator is a pipe declarator.
5155 static bool isPipeDeclerator(const Declarator &D) {
5156 const unsigned NumTypes = D.getNumTypeObjects();
5158 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5159 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5165 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5166 /// is parsed by the function passed to it. Pass null, and the direct-declarator
5167 /// isn't parsed at all, making this function effectively parse the C++
5168 /// ptr-operator production.
5170 /// If the grammar of this construct is extended, matching changes must also be
5171 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5172 /// isConstructorDeclarator.
5174 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5175 /// [C] pointer[opt] direct-declarator
5176 /// [C++] direct-declarator
5177 /// [C++] ptr-operator declarator
5179 /// pointer: [C99 6.7.5]
5180 /// '*' type-qualifier-list[opt]
5181 /// '*' type-qualifier-list[opt] pointer
5184 /// '*' cv-qualifier-seq[opt]
5187 /// [GNU] '&' restrict[opt] attributes[opt]
5188 /// [GNU?] '&&' restrict[opt] attributes[opt]
5189 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
5190 void Parser::ParseDeclaratorInternal(Declarator &D,
5191 DirectDeclParseFunction DirectDeclParser) {
5192 if (Diags.hasAllExtensionsSilenced())
5195 // C++ member pointers start with a '::' or a nested-name.
5196 // Member pointers get special handling, since there's no place for the
5197 // scope spec in the generic path below.
5198 if (getLangOpts().CPlusPlus &&
5199 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
5200 (Tok.is(tok::identifier) &&
5201 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
5202 Tok.is(tok::annot_cxxscope))) {
5203 bool EnteringContext = D.getContext() == Declarator::FileContext ||
5204 D.getContext() == Declarator::MemberContext;
5206 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
5208 if (SS.isNotEmpty()) {
5209 if (Tok.isNot(tok::star)) {
5210 // The scope spec really belongs to the direct-declarator.
5211 if (D.mayHaveIdentifier())
5212 D.getCXXScopeSpec() = SS;
5214 AnnotateScopeToken(SS, true);
5216 if (DirectDeclParser)
5217 (this->*DirectDeclParser)(D);
5221 SourceLocation Loc = ConsumeToken();
5223 DeclSpec DS(AttrFactory);
5224 ParseTypeQualifierListOpt(DS);
5225 D.ExtendWithDeclSpec(DS);
5227 // Recurse to parse whatever is left.
5228 ParseDeclaratorInternal(D, DirectDeclParser);
5230 // Sema will have to catch (syntactically invalid) pointers into global
5231 // scope. It has to catch pointers into namespace scope anyway.
5232 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
5235 /* Don't replace range end. */SourceLocation());
5240 tok::TokenKind Kind = Tok.getKind();
5242 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
5243 DeclSpec DS(AttrFactory);
5244 ParseTypeQualifierListOpt(DS);
5247 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
5248 DS.getAttributes(), SourceLocation());
5251 // Not a pointer, C++ reference, or block.
5252 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
5253 if (DirectDeclParser)
5254 (this->*DirectDeclParser)(D);
5258 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5259 // '&&' -> rvalue reference
5260 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
5263 if (Kind == tok::star || Kind == tok::caret) {
5265 DeclSpec DS(AttrFactory);
5267 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5268 // C++11 attributes are allowed.
5269 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
5270 ((D.getContext() != Declarator::CXXNewContext)
5271 ? AR_GNUAttributesParsed
5272 : AR_GNUAttributesParsedAndRejected);
5273 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
5274 D.ExtendWithDeclSpec(DS);
5276 // Recursively parse the declarator.
5277 ParseDeclaratorInternal(D, DirectDeclParser);
5278 if (Kind == tok::star)
5279 // Remember that we parsed a pointer type, and remember the type-quals.
5280 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
5281 DS.getConstSpecLoc(),
5282 DS.getVolatileSpecLoc(),
5283 DS.getRestrictSpecLoc(),
5284 DS.getAtomicSpecLoc(),
5285 DS.getUnalignedSpecLoc()),
5289 // Remember that we parsed a Block type, and remember the type-quals.
5290 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
5296 DeclSpec DS(AttrFactory);
5298 // Complain about rvalue references in C++03, but then go on and build
5300 if (Kind == tok::ampamp)
5301 Diag(Loc, getLangOpts().CPlusPlus11 ?
5302 diag::warn_cxx98_compat_rvalue_reference :
5303 diag::ext_rvalue_reference);
5305 // GNU-style and C++11 attributes are allowed here, as is restrict.
5306 ParseTypeQualifierListOpt(DS);
5307 D.ExtendWithDeclSpec(DS);
5309 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5310 // cv-qualifiers are introduced through the use of a typedef or of a
5311 // template type argument, in which case the cv-qualifiers are ignored.
5312 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5313 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5314 Diag(DS.getConstSpecLoc(),
5315 diag::err_invalid_reference_qualifier_application) << "const";
5316 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5317 Diag(DS.getVolatileSpecLoc(),
5318 diag::err_invalid_reference_qualifier_application) << "volatile";
5319 // 'restrict' is permitted as an extension.
5320 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5321 Diag(DS.getAtomicSpecLoc(),
5322 diag::err_invalid_reference_qualifier_application) << "_Atomic";
5325 // Recursively parse the declarator.
5326 ParseDeclaratorInternal(D, DirectDeclParser);
5328 if (D.getNumTypeObjects() > 0) {
5329 // C++ [dcl.ref]p4: There shall be no references to references.
5330 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5331 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5332 if (const IdentifierInfo *II = D.getIdentifier())
5333 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5336 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5339 // Once we've complained about the reference-to-reference, we
5340 // can go ahead and build the (technically ill-formed)
5341 // declarator: reference collapsing will take care of it.
5345 // Remember that we parsed a reference type.
5346 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
5353 // When correcting from misplaced brackets before the identifier, the location
5354 // is saved inside the declarator so that other diagnostic messages can use
5355 // them. This extracts and returns that location, or returns the provided
5356 // location if a stored location does not exist.
5357 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5358 SourceLocation Loc) {
5359 if (D.getName().StartLocation.isInvalid() &&
5360 D.getName().EndLocation.isValid())
5361 return D.getName().EndLocation;
5366 /// ParseDirectDeclarator
5367 /// direct-declarator: [C99 6.7.5]
5368 /// [C99] identifier
5369 /// '(' declarator ')'
5370 /// [GNU] '(' attributes declarator ')'
5371 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5372 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5373 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5374 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5375 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5376 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5377 /// attribute-specifier-seq[opt]
5378 /// direct-declarator '(' parameter-type-list ')'
5379 /// direct-declarator '(' identifier-list[opt] ')'
5380 /// [GNU] direct-declarator '(' parameter-forward-declarations
5381 /// parameter-type-list[opt] ')'
5382 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
5383 /// cv-qualifier-seq[opt] exception-specification[opt]
5384 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5385 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5386 /// ref-qualifier[opt] exception-specification[opt]
5387 /// [C++] declarator-id
5388 /// [C++11] declarator-id attribute-specifier-seq[opt]
5390 /// declarator-id: [C++ 8]
5391 /// '...'[opt] id-expression
5392 /// '::'[opt] nested-name-specifier[opt] type-name
5394 /// id-expression: [C++ 5.1]
5398 /// unqualified-id: [C++ 5.1]
5400 /// operator-function-id
5401 /// conversion-function-id
5405 /// C++17 adds the following, which we also handle here:
5407 /// simple-declaration:
5408 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5410 /// Note, any additional constructs added here may need corresponding changes
5411 /// in isConstructorDeclarator.
5412 void Parser::ParseDirectDeclarator(Declarator &D) {
5413 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
5415 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
5416 // This might be a C++17 structured binding.
5417 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5418 D.getCXXScopeSpec().isEmpty())
5419 return ParseDecompositionDeclarator(D);
5421 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5422 // this context it is a bitfield. Also in range-based for statement colon
5423 // may delimit for-range-declaration.
5424 ColonProtectionRAIIObject X(*this,
5425 D.getContext() == Declarator::MemberContext ||
5426 (D.getContext() == Declarator::ForContext &&
5427 getLangOpts().CPlusPlus11));
5429 // ParseDeclaratorInternal might already have parsed the scope.
5430 if (D.getCXXScopeSpec().isEmpty()) {
5431 bool EnteringContext = D.getContext() == Declarator::FileContext ||
5432 D.getContext() == Declarator::MemberContext;
5433 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
5437 if (D.getCXXScopeSpec().isValid()) {
5438 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5439 D.getCXXScopeSpec()))
5440 // Change the declaration context for name lookup, until this function
5441 // is exited (and the declarator has been parsed).
5442 DeclScopeObj.EnterDeclaratorScope();
5443 else if (getObjCDeclContext()) {
5444 // Ensure that we don't interpret the next token as an identifier when
5445 // dealing with declarations in an Objective-C container.
5446 D.SetIdentifier(nullptr, Tok.getLocation());
5447 D.setInvalidType(true);
5449 goto PastIdentifier;
5453 // C++0x [dcl.fct]p14:
5454 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5455 // parameter-declaration-clause without a preceding comma. In this case,
5456 // the ellipsis is parsed as part of the abstract-declarator if the type
5457 // of the parameter either names a template parameter pack that has not
5458 // been expanded or contains auto; otherwise, it is parsed as part of the
5459 // parameter-declaration-clause.
5460 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
5461 !((D.getContext() == Declarator::PrototypeContext ||
5462 D.getContext() == Declarator::LambdaExprParameterContext ||
5463 D.getContext() == Declarator::BlockLiteralContext) &&
5464 NextToken().is(tok::r_paren) &&
5465 !D.hasGroupingParens() &&
5466 !Actions.containsUnexpandedParameterPacks(D) &&
5467 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
5468 SourceLocation EllipsisLoc = ConsumeToken();
5469 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
5470 // The ellipsis was put in the wrong place. Recover, and explain to
5471 // the user what they should have done.
5473 if (EllipsisLoc.isValid())
5474 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5477 D.setEllipsisLoc(EllipsisLoc);
5479 // The ellipsis can't be followed by a parenthesized declarator. We
5480 // check for that in ParseParenDeclarator, after we have disambiguated
5481 // the l_paren token.
5484 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5486 // We found something that indicates the start of an unqualified-id.
5487 // Parse that unqualified-id.
5488 bool AllowConstructorName;
5489 bool AllowDeductionGuide;
5490 if (D.getDeclSpec().hasTypeSpecifier()) {
5491 AllowConstructorName = false;
5492 AllowDeductionGuide = false;
5493 } else if (D.getCXXScopeSpec().isSet()) {
5494 AllowConstructorName =
5495 (D.getContext() == Declarator::FileContext ||
5496 D.getContext() == Declarator::MemberContext);
5497 AllowDeductionGuide = false;
5499 AllowConstructorName = (D.getContext() == Declarator::MemberContext);
5500 AllowDeductionGuide =
5501 (D.getContext() == Declarator::FileContext ||
5502 D.getContext() == Declarator::MemberContext);
5505 SourceLocation TemplateKWLoc;
5506 bool HadScope = D.getCXXScopeSpec().isValid();
5507 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5508 /*EnteringContext=*/true,
5509 /*AllowDestructorName=*/true, AllowConstructorName,
5510 AllowDeductionGuide, nullptr, TemplateKWLoc,
5512 // Once we're past the identifier, if the scope was bad, mark the
5513 // whole declarator bad.
5514 D.getCXXScopeSpec().isInvalid()) {
5515 D.SetIdentifier(nullptr, Tok.getLocation());
5516 D.setInvalidType(true);
5518 // ParseUnqualifiedId might have parsed a scope specifier during error
5519 // recovery. If it did so, enter that scope.
5520 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5521 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5522 D.getCXXScopeSpec()))
5523 DeclScopeObj.EnterDeclaratorScope();
5525 // Parsed the unqualified-id; update range information and move along.
5526 if (D.getSourceRange().getBegin().isInvalid())
5527 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5528 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
5530 goto PastIdentifier;
5533 if (D.getCXXScopeSpec().isNotEmpty()) {
5534 // We have a scope specifier but no following unqualified-id.
5535 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5536 diag::err_expected_unqualified_id)
5538 D.SetIdentifier(nullptr, Tok.getLocation());
5539 goto PastIdentifier;
5541 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
5542 assert(!getLangOpts().CPlusPlus &&
5543 "There's a C++-specific check for tok::identifier above");
5544 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5545 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5546 D.SetRangeEnd(Tok.getLocation());
5548 goto PastIdentifier;
5549 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5550 // We're not allowed an identifier here, but we got one. Try to figure out
5551 // if the user was trying to attach a name to the type, or whether the name
5552 // is some unrelated trailing syntax.
5553 bool DiagnoseIdentifier = false;
5554 if (D.hasGroupingParens())
5555 // An identifier within parens is unlikely to be intended to be anything
5556 // other than a name being "declared".
5557 DiagnoseIdentifier = true;
5558 else if (D.getContext() == Declarator::TemplateTypeArgContext)
5559 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5560 DiagnoseIdentifier =
5561 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
5562 else if (D.getContext() == Declarator::AliasDeclContext ||
5563 D.getContext() == Declarator::AliasTemplateContext)
5564 // The most likely error is that the ';' was forgotten.
5565 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
5566 else if (D.getContext() == Declarator::TrailingReturnContext &&
5567 !isCXX11VirtSpecifier(Tok))
5568 DiagnoseIdentifier = NextToken().isOneOf(
5569 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5570 if (DiagnoseIdentifier) {
5571 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5572 << FixItHint::CreateRemoval(Tok.getLocation());
5573 D.SetIdentifier(nullptr, Tok.getLocation());
5575 goto PastIdentifier;
5579 if (Tok.is(tok::l_paren)) {
5580 // direct-declarator: '(' declarator ')'
5581 // direct-declarator: '(' attributes declarator ')'
5582 // Example: 'char (*X)' or 'int (*XX)(void)'
5583 ParseParenDeclarator(D);
5585 // If the declarator was parenthesized, we entered the declarator
5586 // scope when parsing the parenthesized declarator, then exited
5587 // the scope already. Re-enter the scope, if we need to.
5588 if (D.getCXXScopeSpec().isSet()) {
5589 // If there was an error parsing parenthesized declarator, declarator
5590 // scope may have been entered before. Don't do it again.
5591 if (!D.isInvalidType() &&
5592 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5593 D.getCXXScopeSpec()))
5594 // Change the declaration context for name lookup, until this function
5595 // is exited (and the declarator has been parsed).
5596 DeclScopeObj.EnterDeclaratorScope();
5598 } else if (D.mayOmitIdentifier()) {
5599 // This could be something simple like "int" (in which case the declarator
5600 // portion is empty), if an abstract-declarator is allowed.
5601 D.SetIdentifier(nullptr, Tok.getLocation());
5603 // The grammar for abstract-pack-declarator does not allow grouping parens.
5604 // FIXME: Revisit this once core issue 1488 is resolved.
5605 if (D.hasEllipsis() && D.hasGroupingParens())
5606 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5607 diag::ext_abstract_pack_declarator_parens);
5609 if (Tok.getKind() == tok::annot_pragma_parser_crash)
5611 if (Tok.is(tok::l_square))
5612 return ParseMisplacedBracketDeclarator(D);
5613 if (D.getContext() == Declarator::MemberContext) {
5614 // Objective-C++: Detect C++ keywords and try to prevent further errors by
5615 // treating these keyword as valid member names.
5616 if (getLangOpts().ObjC1 && getLangOpts().CPlusPlus &&
5617 Tok.getIdentifierInfo() &&
5618 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5619 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5620 diag::err_expected_member_name_or_semi_objcxx_keyword)
5621 << Tok.getIdentifierInfo()
5622 << (D.getDeclSpec().isEmpty() ? SourceRange()
5623 : D.getDeclSpec().getSourceRange());
5624 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5625 D.SetRangeEnd(Tok.getLocation());
5627 goto PastIdentifier;
5629 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5630 diag::err_expected_member_name_or_semi)
5631 << (D.getDeclSpec().isEmpty() ? SourceRange()
5632 : D.getDeclSpec().getSourceRange());
5633 } else if (getLangOpts().CPlusPlus) {
5634 if (Tok.isOneOf(tok::period, tok::arrow))
5635 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
5637 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5638 if (Tok.isAtStartOfLine() && Loc.isValid())
5639 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5640 << getLangOpts().CPlusPlus;
5642 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5643 diag::err_expected_unqualified_id)
5644 << getLangOpts().CPlusPlus;
5647 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5648 diag::err_expected_either)
5649 << tok::identifier << tok::l_paren;
5651 D.SetIdentifier(nullptr, Tok.getLocation());
5652 D.setInvalidType(true);
5656 assert(D.isPastIdentifier() &&
5657 "Haven't past the location of the identifier yet?");
5659 // Don't parse attributes unless we have parsed an unparenthesized name.
5660 if (D.hasName() && !D.getNumTypeObjects())
5661 MaybeParseCXX11Attributes(D);
5664 if (Tok.is(tok::l_paren)) {
5665 // Enter function-declaration scope, limiting any declarators to the
5666 // function prototype scope, including parameter declarators.
5667 ParseScope PrototypeScope(this,
5668 Scope::FunctionPrototypeScope|Scope::DeclScope|
5669 (D.isFunctionDeclaratorAFunctionDeclaration()
5670 ? Scope::FunctionDeclarationScope : 0));
5672 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5673 // In such a case, check if we actually have a function declarator; if it
5674 // is not, the declarator has been fully parsed.
5675 bool IsAmbiguous = false;
5676 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5677 // The name of the declarator, if any, is tentatively declared within
5678 // a possible direct initializer.
5679 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5680 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5681 TentativelyDeclaredIdentifiers.pop_back();
5682 if (!IsFunctionDecl)
5685 ParsedAttributes attrs(AttrFactory);
5686 BalancedDelimiterTracker T(*this, tok::l_paren);
5688 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
5689 PrototypeScope.Exit();
5690 } else if (Tok.is(tok::l_square)) {
5691 ParseBracketDeclarator(D);
5698 void Parser::ParseDecompositionDeclarator(Declarator &D) {
5699 assert(Tok.is(tok::l_square));
5701 // If this doesn't look like a structured binding, maybe it's a misplaced
5702 // array declarator.
5703 // FIXME: Consume the l_square first so we don't need extra lookahead for
5705 if (!(NextToken().is(tok::identifier) &&
5706 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5707 !(NextToken().is(tok::r_square) &&
5708 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5709 return ParseMisplacedBracketDeclarator(D);
5711 BalancedDelimiterTracker T(*this, tok::l_square);
5714 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5715 while (Tok.isNot(tok::r_square)) {
5716 if (!Bindings.empty()) {
5717 if (Tok.is(tok::comma))
5720 if (Tok.is(tok::identifier)) {
5721 SourceLocation EndLoc = getEndOfPreviousToken();
5722 Diag(EndLoc, diag::err_expected)
5723 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
5725 Diag(Tok, diag::err_expected_comma_or_rsquare);
5728 SkipUntil(tok::r_square, tok::comma, tok::identifier,
5729 StopAtSemi | StopBeforeMatch);
5730 if (Tok.is(tok::comma))
5732 else if (Tok.isNot(tok::identifier))
5737 if (Tok.isNot(tok::identifier)) {
5738 Diag(Tok, diag::err_expected) << tok::identifier;
5742 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
5746 if (Tok.isNot(tok::r_square))
5747 // We've already diagnosed a problem here.
5750 // C++17 does not allow the identifier-list in a structured binding
5752 if (Bindings.empty())
5753 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
5758 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
5759 T.getCloseLocation());
5762 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
5763 /// only called before the identifier, so these are most likely just grouping
5764 /// parens for precedence. If we find that these are actually function
5765 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5767 /// direct-declarator:
5768 /// '(' declarator ')'
5769 /// [GNU] '(' attributes declarator ')'
5770 /// direct-declarator '(' parameter-type-list ')'
5771 /// direct-declarator '(' identifier-list[opt] ')'
5772 /// [GNU] direct-declarator '(' parameter-forward-declarations
5773 /// parameter-type-list[opt] ')'
5775 void Parser::ParseParenDeclarator(Declarator &D) {
5776 BalancedDelimiterTracker T(*this, tok::l_paren);
5779 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
5781 // Eat any attributes before we look at whether this is a grouping or function
5782 // declarator paren. If this is a grouping paren, the attribute applies to
5783 // the type being built up, for example:
5784 // int (__attribute__(()) *x)(long y)
5785 // If this ends up not being a grouping paren, the attribute applies to the
5786 // first argument, for example:
5787 // int (__attribute__(()) int x)
5788 // In either case, we need to eat any attributes to be able to determine what
5789 // sort of paren this is.
5791 ParsedAttributes attrs(AttrFactory);
5792 bool RequiresArg = false;
5793 if (Tok.is(tok::kw___attribute)) {
5794 ParseGNUAttributes(attrs);
5796 // We require that the argument list (if this is a non-grouping paren) be
5797 // present even if the attribute list was empty.
5801 // Eat any Microsoft extensions.
5802 ParseMicrosoftTypeAttributes(attrs);
5804 // Eat any Borland extensions.
5805 if (Tok.is(tok::kw___pascal))
5806 ParseBorlandTypeAttributes(attrs);
5808 // If we haven't past the identifier yet (or where the identifier would be
5809 // stored, if this is an abstract declarator), then this is probably just
5810 // grouping parens. However, if this could be an abstract-declarator, then
5811 // this could also be the start of function arguments (consider 'void()').
5814 if (!D.mayOmitIdentifier()) {
5815 // If this can't be an abstract-declarator, this *must* be a grouping
5816 // paren, because we haven't seen the identifier yet.
5818 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
5819 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
5820 NextToken().is(tok::r_paren)) || // C++ int(...)
5821 isDeclarationSpecifier() || // 'int(int)' is a function.
5822 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
5823 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
5824 // considered to be a type, not a K&R identifier-list.
5827 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
5831 // If this is a grouping paren, handle:
5832 // direct-declarator: '(' declarator ')'
5833 // direct-declarator: '(' attributes declarator ')'
5835 SourceLocation EllipsisLoc = D.getEllipsisLoc();
5836 D.setEllipsisLoc(SourceLocation());
5838 bool hadGroupingParens = D.hasGroupingParens();
5839 D.setGroupingParens(true);
5840 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5843 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
5844 T.getCloseLocation()),
5845 attrs, T.getCloseLocation());
5847 D.setGroupingParens(hadGroupingParens);
5849 // An ellipsis cannot be placed outside parentheses.
5850 if (EllipsisLoc.isValid())
5851 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5856 // Okay, if this wasn't a grouping paren, it must be the start of a function
5857 // argument list. Recognize that this declarator will never have an
5858 // identifier (and remember where it would have been), then call into
5859 // ParseFunctionDeclarator to handle of argument list.
5860 D.SetIdentifier(nullptr, Tok.getLocation());
5862 // Enter function-declaration scope, limiting any declarators to the
5863 // function prototype scope, including parameter declarators.
5864 ParseScope PrototypeScope(this,
5865 Scope::FunctionPrototypeScope | Scope::DeclScope |
5866 (D.isFunctionDeclaratorAFunctionDeclaration()
5867 ? Scope::FunctionDeclarationScope : 0));
5868 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
5869 PrototypeScope.Exit();
5872 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
5873 /// declarator D up to a paren, which indicates that we are parsing function
5876 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
5877 /// immediately after the open paren - they should be considered to be the
5878 /// first argument of a parameter.
5880 /// If RequiresArg is true, then the first argument of the function is required
5881 /// to be present and required to not be an identifier list.
5883 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
5884 /// (C++11) ref-qualifier[opt], exception-specification[opt],
5885 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
5887 /// [C++11] exception-specification:
5888 /// dynamic-exception-specification
5889 /// noexcept-specification
5891 void Parser::ParseFunctionDeclarator(Declarator &D,
5892 ParsedAttributes &FirstArgAttrs,
5893 BalancedDelimiterTracker &Tracker,
5896 assert(getCurScope()->isFunctionPrototypeScope() &&
5897 "Should call from a Function scope");
5898 // lparen is already consumed!
5899 assert(D.isPastIdentifier() && "Should not call before identifier!");
5901 // This should be true when the function has typed arguments.
5902 // Otherwise, it is treated as a K&R-style function.
5903 bool HasProto = false;
5904 // Build up an array of information about the parsed arguments.
5905 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
5906 // Remember where we see an ellipsis, if any.
5907 SourceLocation EllipsisLoc;
5909 DeclSpec DS(AttrFactory);
5910 bool RefQualifierIsLValueRef = true;
5911 SourceLocation RefQualifierLoc;
5912 SourceLocation ConstQualifierLoc;
5913 SourceLocation VolatileQualifierLoc;
5914 SourceLocation RestrictQualifierLoc;
5915 ExceptionSpecificationType ESpecType = EST_None;
5916 SourceRange ESpecRange;
5917 SmallVector<ParsedType, 2> DynamicExceptions;
5918 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5919 ExprResult NoexceptExpr;
5920 CachedTokens *ExceptionSpecTokens = nullptr;
5921 ParsedAttributes FnAttrs(AttrFactory);
5922 TypeResult TrailingReturnType;
5924 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
5925 EndLoc is the end location for the function declarator.
5926 They differ for trailing return types. */
5927 SourceLocation StartLoc, LocalEndLoc, EndLoc;
5928 SourceLocation LParenLoc, RParenLoc;
5929 LParenLoc = Tracker.getOpenLocation();
5930 StartLoc = LParenLoc;
5932 if (isFunctionDeclaratorIdentifierList()) {
5934 Diag(Tok, diag::err_argument_required_after_attribute);
5936 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
5938 Tracker.consumeClose();
5939 RParenLoc = Tracker.getCloseLocation();
5940 LocalEndLoc = RParenLoc;
5943 if (Tok.isNot(tok::r_paren))
5944 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
5946 else if (RequiresArg)
5947 Diag(Tok, diag::err_argument_required_after_attribute);
5949 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
5951 // If we have the closing ')', eat it.
5952 Tracker.consumeClose();
5953 RParenLoc = Tracker.getCloseLocation();
5954 LocalEndLoc = RParenLoc;
5957 if (getLangOpts().CPlusPlus) {
5958 // FIXME: Accept these components in any order, and produce fixits to
5959 // correct the order if the user gets it wrong. Ideally we should deal
5960 // with the pure-specifier in the same way.
5962 // Parse cv-qualifier-seq[opt].
5963 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
5964 /*AtomicAllowed*/ false,
5965 /*IdentifierRequired=*/false,
5966 llvm::function_ref<void()>([&]() {
5967 Actions.CodeCompleteFunctionQualifiers(DS, D);
5969 if (!DS.getSourceRange().getEnd().isInvalid()) {
5970 EndLoc = DS.getSourceRange().getEnd();
5971 ConstQualifierLoc = DS.getConstSpecLoc();
5972 VolatileQualifierLoc = DS.getVolatileSpecLoc();
5973 RestrictQualifierLoc = DS.getRestrictSpecLoc();
5976 // Parse ref-qualifier[opt].
5977 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
5978 EndLoc = RefQualifierLoc;
5980 // C++11 [expr.prim.general]p3:
5981 // If a declaration declares a member function or member function
5982 // template of a class X, the expression this is a prvalue of type
5983 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5984 // and the end of the function-definition, member-declarator, or
5986 // FIXME: currently, "static" case isn't handled correctly.
5987 bool IsCXX11MemberFunction =
5988 getLangOpts().CPlusPlus11 &&
5989 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5990 (D.getContext() == Declarator::MemberContext
5991 ? !D.getDeclSpec().isFriendSpecified()
5992 : D.getContext() == Declarator::FileContext &&
5993 D.getCXXScopeSpec().isValid() &&
5994 Actions.CurContext->isRecord());
5995 Sema::CXXThisScopeRAII ThisScope(Actions,
5996 dyn_cast<CXXRecordDecl>(Actions.CurContext),
5997 DS.getTypeQualifiers() |
5998 (D.getDeclSpec().isConstexprSpecified() &&
5999 !getLangOpts().CPlusPlus14
6000 ? Qualifiers::Const : 0),
6001 IsCXX11MemberFunction);
6003 // Parse exception-specification[opt].
6004 bool Delayed = D.isFirstDeclarationOfMember() &&
6005 D.isFunctionDeclaratorAFunctionDeclaration();
6006 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6007 GetLookAheadToken(0).is(tok::kw_noexcept) &&
6008 GetLookAheadToken(1).is(tok::l_paren) &&
6009 GetLookAheadToken(2).is(tok::kw_noexcept) &&
6010 GetLookAheadToken(3).is(tok::l_paren) &&
6011 GetLookAheadToken(4).is(tok::identifier) &&
6012 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6013 // HACK: We've got an exception-specification
6014 // noexcept(noexcept(swap(...)))
6016 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6017 // on a 'swap' member function. This is a libstdc++ bug; the lookup
6018 // for 'swap' will only find the function we're currently declaring,
6019 // whereas it expects to find a non-member swap through ADL. Turn off
6020 // delayed parsing to give it a chance to find what it expects.
6023 ESpecType = tryParseExceptionSpecification(Delayed,
6026 DynamicExceptionRanges,
6028 ExceptionSpecTokens);
6029 if (ESpecType != EST_None)
6030 EndLoc = ESpecRange.getEnd();
6032 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6033 // after the exception-specification.
6034 MaybeParseCXX11Attributes(FnAttrs);
6036 // Parse trailing-return-type[opt].
6037 LocalEndLoc = EndLoc;
6038 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
6039 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
6040 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
6041 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
6042 LocalEndLoc = Tok.getLocation();
6044 TrailingReturnType = ParseTrailingReturnType(Range);
6045 EndLoc = Range.getEnd();
6050 // Collect non-parameter declarations from the prototype if this is a function
6051 // declaration. They will be moved into the scope of the function. Only do
6052 // this in C and not C++, where the decls will continue to live in the
6053 // surrounding context.
6054 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6055 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6056 !getLangOpts().CPlusPlus) {
6057 for (Decl *D : getCurScope()->decls()) {
6058 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6059 if (!ND || isa<ParmVarDecl>(ND))
6061 DeclsInPrototype.push_back(ND);
6065 // Remember that we parsed a function type, and remember the attributes.
6066 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
6069 ParamInfo.data(), ParamInfo.size(),
6070 EllipsisLoc, RParenLoc,
6071 DS.getTypeQualifiers(),
6072 RefQualifierIsLValueRef,
6073 RefQualifierLoc, ConstQualifierLoc,
6074 VolatileQualifierLoc,
6075 RestrictQualifierLoc,
6076 /*MutableLoc=*/SourceLocation(),
6077 ESpecType, ESpecRange,
6078 DynamicExceptions.data(),
6079 DynamicExceptionRanges.data(),
6080 DynamicExceptions.size(),
6081 NoexceptExpr.isUsable() ?
6082 NoexceptExpr.get() : nullptr,
6083 ExceptionSpecTokens,
6085 StartLoc, LocalEndLoc, D,
6086 TrailingReturnType),
6090 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6091 /// true if a ref-qualifier is found.
6092 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6093 SourceLocation &RefQualifierLoc) {
6094 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
6095 Diag(Tok, getLangOpts().CPlusPlus11 ?
6096 diag::warn_cxx98_compat_ref_qualifier :
6097 diag::ext_ref_qualifier);
6099 RefQualifierIsLValueRef = Tok.is(tok::amp);
6100 RefQualifierLoc = ConsumeToken();
6106 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
6107 /// identifier list form for a K&R-style function: void foo(a,b,c)
6109 /// Note that identifier-lists are only allowed for normal declarators, not for
6110 /// abstract-declarators.
6111 bool Parser::isFunctionDeclaratorIdentifierList() {
6112 return !getLangOpts().CPlusPlus
6113 && Tok.is(tok::identifier)
6114 && !TryAltiVecVectorToken()
6115 // K&R identifier lists can't have typedefs as identifiers, per C99
6117 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6118 // Identifier lists follow a really simple grammar: the identifiers can
6119 // be followed *only* by a ", identifier" or ")". However, K&R
6120 // identifier lists are really rare in the brave new modern world, and
6121 // it is very common for someone to typo a type in a non-K&R style
6122 // list. If we are presented with something like: "void foo(intptr x,
6123 // float y)", we don't want to start parsing the function declarator as
6124 // though it is a K&R style declarator just because intptr is an
6127 // To handle this, we check to see if the token after the first
6128 // identifier is a "," or ")". Only then do we parse it as an
6130 && (!Tok.is(tok::eof) &&
6131 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
6134 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6135 /// we found a K&R-style identifier list instead of a typed parameter list.
6137 /// After returning, ParamInfo will hold the parsed parameters.
6139 /// identifier-list: [C99 6.7.5]
6141 /// identifier-list ',' identifier
6143 void Parser::ParseFunctionDeclaratorIdentifierList(
6145 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
6146 // If there was no identifier specified for the declarator, either we are in
6147 // an abstract-declarator, or we are in a parameter declarator which was found
6148 // to be abstract. In abstract-declarators, identifier lists are not valid:
6150 if (!D.getIdentifier())
6151 Diag(Tok, diag::ext_ident_list_in_param);
6153 // Maintain an efficient lookup of params we have seen so far.
6154 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6157 // If this isn't an identifier, report the error and skip until ')'.
6158 if (Tok.isNot(tok::identifier)) {
6159 Diag(Tok, diag::err_expected) << tok::identifier;
6160 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
6161 // Forget we parsed anything.
6166 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6168 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6169 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6170 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6172 // Verify that the argument identifier has not already been mentioned.
6173 if (!ParamsSoFar.insert(ParmII).second) {
6174 Diag(Tok, diag::err_param_redefinition) << ParmII;
6176 // Remember this identifier in ParamInfo.
6177 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6182 // Eat the identifier.
6184 // The list continues if we see a comma.
6185 } while (TryConsumeToken(tok::comma));
6188 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6189 /// after the opening parenthesis. This function will not parse a K&R-style
6190 /// identifier list.
6192 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
6193 /// caller parsed those arguments immediately after the open paren - they should
6194 /// be considered to be part of the first parameter.
6196 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6197 /// be the location of the ellipsis, if any was parsed.
6199 /// parameter-type-list: [C99 6.7.5]
6201 /// parameter-list ',' '...'
6202 /// [C++] parameter-list '...'
6204 /// parameter-list: [C99 6.7.5]
6205 /// parameter-declaration
6206 /// parameter-list ',' parameter-declaration
6208 /// parameter-declaration: [C99 6.7.5]
6209 /// declaration-specifiers declarator
6210 /// [C++] declaration-specifiers declarator '=' assignment-expression
6211 /// [C++11] initializer-clause
6212 /// [GNU] declaration-specifiers declarator attributes
6213 /// declaration-specifiers abstract-declarator[opt]
6214 /// [C++] declaration-specifiers abstract-declarator[opt]
6215 /// '=' assignment-expression
6216 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
6217 /// [C++11] attribute-specifier-seq parameter-declaration
6219 void Parser::ParseParameterDeclarationClause(
6221 ParsedAttributes &FirstArgAttrs,
6222 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
6223 SourceLocation &EllipsisLoc) {
6225 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6226 // before deciding this was a parameter-declaration-clause.
6227 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
6230 // Parse the declaration-specifiers.
6231 // Just use the ParsingDeclaration "scope" of the declarator.
6232 DeclSpec DS(AttrFactory);
6234 // Parse any C++11 attributes.
6235 MaybeParseCXX11Attributes(DS.getAttributes());
6237 // Skip any Microsoft attributes before a param.
6238 MaybeParseMicrosoftAttributes(DS.getAttributes());
6240 SourceLocation DSStart = Tok.getLocation();
6242 // If the caller parsed attributes for the first argument, add them now.
6243 // Take them so that we only apply the attributes to the first parameter.
6244 // FIXME: If we can leave the attributes in the token stream somehow, we can
6245 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6247 DS.takeAttributesFrom(FirstArgAttrs);
6249 ParseDeclarationSpecifiers(DS);
6252 // Parse the declarator. This is "PrototypeContext" or
6253 // "LambdaExprParameterContext", because we must accept either
6254 // 'declarator' or 'abstract-declarator' here.
6255 Declarator ParmDeclarator(DS,
6256 D.getContext() == Declarator::LambdaExprContext ?
6257 Declarator::LambdaExprParameterContext :
6258 Declarator::PrototypeContext);
6259 ParseDeclarator(ParmDeclarator);
6261 // Parse GNU attributes, if present.
6262 MaybeParseGNUAttributes(ParmDeclarator);
6264 // Remember this parsed parameter in ParamInfo.
6265 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
6267 // DefArgToks is used when the parsing of default arguments needs
6269 std::unique_ptr<CachedTokens> DefArgToks;
6271 // If no parameter was specified, verify that *something* was specified,
6272 // otherwise we have a missing type and identifier.
6273 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
6274 ParmDeclarator.getNumTypeObjects() == 0) {
6275 // Completely missing, emit error.
6276 Diag(DSStart, diag::err_missing_param);
6278 // Otherwise, we have something. Add it and let semantic analysis try
6279 // to grok it and add the result to the ParamInfo we are building.
6281 // Last chance to recover from a misplaced ellipsis in an attempted
6282 // parameter pack declaration.
6283 if (Tok.is(tok::ellipsis) &&
6284 (NextToken().isNot(tok::r_paren) ||
6285 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6286 !Actions.isUnexpandedParameterPackPermitted())) &&
6287 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6288 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6290 // Inform the actions module about the parameter declarator, so it gets
6291 // added to the current scope.
6292 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
6293 // Parse the default argument, if any. We parse the default
6294 // arguments in all dialects; the semantic analysis in
6295 // ActOnParamDefaultArgument will reject the default argument in
6297 if (Tok.is(tok::equal)) {
6298 SourceLocation EqualLoc = Tok.getLocation();
6300 // Parse the default argument
6301 if (D.getContext() == Declarator::MemberContext) {
6302 // If we're inside a class definition, cache the tokens
6303 // corresponding to the default argument. We'll actually parse
6304 // them when we see the end of the class definition.
6305 DefArgToks.reset(new CachedTokens);
6307 SourceLocation ArgStartLoc = NextToken().getLocation();
6308 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
6310 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6312 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
6319 // The argument isn't actually potentially evaluated unless it is
6321 EnterExpressionEvaluationContext Eval(
6323 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6326 ExprResult DefArgResult;
6327 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
6328 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
6329 DefArgResult = ParseBraceInitializer();
6331 DefArgResult = ParseAssignmentExpression();
6332 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
6333 if (DefArgResult.isInvalid()) {
6334 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6335 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
6337 // Inform the actions module about the default argument
6338 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
6339 DefArgResult.get());
6344 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6345 ParmDeclarator.getIdentifierLoc(),
6346 Param, std::move(DefArgToks)));
6349 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6350 if (!getLangOpts().CPlusPlus) {
6351 // We have ellipsis without a preceding ',', which is ill-formed
6352 // in C. Complain and provide the fix.
6353 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6354 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6355 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6356 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6357 // It looks like this was supposed to be a parameter pack. Warn and
6358 // point out where the ellipsis should have gone.
6359 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6360 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6361 << ParmEllipsis.isValid() << ParmEllipsis;
6362 if (ParmEllipsis.isValid()) {
6364 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6366 Diag(ParmDeclarator.getIdentifierLoc(),
6367 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6368 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6370 << !ParmDeclarator.hasName();
6372 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
6373 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6376 // We can't have any more parameters after an ellipsis.
6380 // If the next token is a comma, consume it and keep reading arguments.
6381 } while (TryConsumeToken(tok::comma));
6384 /// [C90] direct-declarator '[' constant-expression[opt] ']'
6385 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6386 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6387 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6388 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
6389 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
6390 /// attribute-specifier-seq[opt]
6391 void Parser::ParseBracketDeclarator(Declarator &D) {
6392 if (CheckProhibitedCXX11Attribute())
6395 BalancedDelimiterTracker T(*this, tok::l_square);
6398 // C array syntax has many features, but by-far the most common is [] and [4].
6399 // This code does a fast path to handle some of the most obvious cases.
6400 if (Tok.getKind() == tok::r_square) {
6402 ParsedAttributes attrs(AttrFactory);
6403 MaybeParseCXX11Attributes(attrs);
6405 // Remember that we parsed the empty array type.
6406 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
6407 T.getOpenLocation(),
6408 T.getCloseLocation()),
6409 attrs, T.getCloseLocation());
6411 } else if (Tok.getKind() == tok::numeric_constant &&
6412 GetLookAheadToken(1).is(tok::r_square)) {
6413 // [4] is very common. Parse the numeric constant expression.
6414 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
6418 ParsedAttributes attrs(AttrFactory);
6419 MaybeParseCXX11Attributes(attrs);
6421 // Remember that we parsed a array type, and remember its features.
6422 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false,
6424 T.getOpenLocation(),
6425 T.getCloseLocation()),
6426 attrs, T.getCloseLocation());
6428 } else if (Tok.getKind() == tok::code_completion) {
6429 Actions.CodeCompleteBracketDeclarator(getCurScope());
6430 return cutOffParsing();
6433 // If valid, this location is the position where we read the 'static' keyword.
6434 SourceLocation StaticLoc;
6435 TryConsumeToken(tok::kw_static, StaticLoc);
6437 // If there is a type-qualifier-list, read it now.
6438 // Type qualifiers in an array subscript are a C99 feature.
6439 DeclSpec DS(AttrFactory);
6440 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
6442 // If we haven't already read 'static', check to see if there is one after the
6443 // type-qualifier-list.
6444 if (!StaticLoc.isValid())
6445 TryConsumeToken(tok::kw_static, StaticLoc);
6447 // Handle "direct-declarator [ type-qual-list[opt] * ]".
6448 bool isStar = false;
6449 ExprResult NumElements;
6451 // Handle the case where we have '[*]' as the array size. However, a leading
6452 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
6453 // the token after the star is a ']'. Since stars in arrays are
6454 // infrequent, use of lookahead is not costly here.
6455 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
6456 ConsumeToken(); // Eat the '*'.
6458 if (StaticLoc.isValid()) {
6459 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
6460 StaticLoc = SourceLocation(); // Drop the static.
6463 } else if (Tok.isNot(tok::r_square)) {
6464 // Note, in C89, this production uses the constant-expr production instead
6465 // of assignment-expr. The only difference is that assignment-expr allows
6466 // things like '=' and '*='. Sema rejects these in C89 mode because they
6467 // are not i-c-e's, so we don't need to distinguish between the two here.
6469 // Parse the constant-expression or assignment-expression now (depending
6471 if (getLangOpts().CPlusPlus) {
6472 NumElements = ParseConstantExpression();
6474 EnterExpressionEvaluationContext Unevaluated(
6475 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6477 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
6480 if (StaticLoc.isValid()) {
6481 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6482 StaticLoc = SourceLocation(); // Drop the static.
6486 // If there was an error parsing the assignment-expression, recover.
6487 if (NumElements.isInvalid()) {
6488 D.setInvalidType(true);
6489 // If the expression was invalid, skip it.
6490 SkipUntil(tok::r_square, StopAtSemi);
6496 MaybeParseCXX11Attributes(DS.getAttributes());
6498 // Remember that we parsed a array type, and remember its features.
6499 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
6500 StaticLoc.isValid(), isStar,
6502 T.getOpenLocation(),
6503 T.getCloseLocation()),
6504 DS.getAttributes(), T.getCloseLocation());
6507 /// Diagnose brackets before an identifier.
6508 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6509 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6510 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6512 SourceLocation StartBracketLoc = Tok.getLocation();
6513 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6515 while (Tok.is(tok::l_square)) {
6516 ParseBracketDeclarator(TempDeclarator);
6519 // Stuff the location of the start of the brackets into the Declarator.
6520 // The diagnostics from ParseDirectDeclarator will make more sense if
6521 // they use this location instead.
6522 if (Tok.is(tok::semi))
6523 D.getName().EndLocation = StartBracketLoc;
6525 SourceLocation SuggestParenLoc = Tok.getLocation();
6527 // Now that the brackets are removed, try parsing the declarator again.
6528 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6530 // Something went wrong parsing the brackets, in which case,
6531 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6533 if (TempDeclarator.getNumTypeObjects() == 0)
6536 // Determine if parens will need to be suggested in the diagnostic.
6537 bool NeedParens = false;
6538 if (D.getNumTypeObjects() != 0) {
6539 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6540 case DeclaratorChunk::Pointer:
6541 case DeclaratorChunk::Reference:
6542 case DeclaratorChunk::BlockPointer:
6543 case DeclaratorChunk::MemberPointer:
6544 case DeclaratorChunk::Pipe:
6547 case DeclaratorChunk::Array:
6548 case DeclaratorChunk::Function:
6549 case DeclaratorChunk::Paren:
6555 // Create a DeclaratorChunk for the inserted parens.
6556 ParsedAttributes attrs(AttrFactory);
6557 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6558 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), attrs,
6562 // Adding back the bracket info to the end of the Declarator.
6563 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6564 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
6565 ParsedAttributes attrs(AttrFactory);
6566 attrs.set(Chunk.Common.AttrList);
6567 D.AddTypeInfo(Chunk, attrs, SourceLocation());
6570 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6571 // If parentheses are required, always suggest them.
6572 if (!D.getIdentifier() && !NeedParens)
6575 SourceLocation EndBracketLoc = TempDeclarator.getLocEnd();
6577 // Generate the move bracket error message.
6578 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
6579 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6582 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6583 << getLangOpts().CPlusPlus
6584 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6585 << FixItHint::CreateInsertion(EndLoc, ")")
6586 << FixItHint::CreateInsertionFromRange(
6587 EndLoc, CharSourceRange(BracketRange, true))
6588 << FixItHint::CreateRemoval(BracketRange);
6590 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6591 << getLangOpts().CPlusPlus
6592 << FixItHint::CreateInsertionFromRange(
6593 EndLoc, CharSourceRange(BracketRange, true))
6594 << FixItHint::CreateRemoval(BracketRange);
6598 /// [GNU] typeof-specifier:
6599 /// typeof ( expressions )
6600 /// typeof ( type-name )
6601 /// [GNU/C++] typeof unary-expression
6603 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
6604 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
6606 SourceLocation StartLoc = ConsumeToken();
6608 const bool hasParens = Tok.is(tok::l_paren);
6610 EnterExpressionEvaluationContext Unevaluated(
6611 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6612 Sema::ReuseLambdaContextDecl);
6616 SourceRange CastRange;
6617 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6618 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
6620 DS.setTypeofParensRange(CastRange);
6622 if (CastRange.getEnd().isInvalid())
6623 // FIXME: Not accurate, the range gets one token more than it should.
6624 DS.SetRangeEnd(Tok.getLocation());
6626 DS.SetRangeEnd(CastRange.getEnd());
6630 DS.SetTypeSpecError();
6634 const char *PrevSpec = nullptr;
6636 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6637 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
6639 Actions.getASTContext().getPrintingPolicy()))
6640 Diag(StartLoc, DiagID) << PrevSpec;
6644 // If we get here, the operand to the typeof was an expresion.
6645 if (Operand.isInvalid()) {
6646 DS.SetTypeSpecError();
6650 // We might need to transform the operand if it is potentially evaluated.
6651 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6652 if (Operand.isInvalid()) {
6653 DS.SetTypeSpecError();
6657 const char *PrevSpec = nullptr;
6659 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6660 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
6661 DiagID, Operand.get(),
6662 Actions.getASTContext().getPrintingPolicy()))
6663 Diag(StartLoc, DiagID) << PrevSpec;
6666 /// [C11] atomic-specifier:
6667 /// _Atomic ( type-name )
6669 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
6670 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6671 "Not an atomic specifier");
6673 SourceLocation StartLoc = ConsumeToken();
6674 BalancedDelimiterTracker T(*this, tok::l_paren);
6675 if (T.consumeOpen())
6678 TypeResult Result = ParseTypeName();
6679 if (Result.isInvalid()) {
6680 SkipUntil(tok::r_paren, StopAtSemi);
6687 if (T.getCloseLocation().isInvalid())
6690 DS.setTypeofParensRange(T.getRange());
6691 DS.SetRangeEnd(T.getCloseLocation());
6693 const char *PrevSpec = nullptr;
6695 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
6696 DiagID, Result.get(),
6697 Actions.getASTContext().getPrintingPolicy()))
6698 Diag(StartLoc, DiagID) << PrevSpec;
6701 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6702 /// from TryAltiVecVectorToken.
6703 bool Parser::TryAltiVecVectorTokenOutOfLine() {
6704 Token Next = NextToken();
6705 switch (Next.getKind()) {
6706 default: return false;
6709 case tok::kw_signed:
6710 case tok::kw_unsigned:
6715 case tok::kw_double:
6717 case tok::kw___bool:
6718 case tok::kw___pixel:
6719 Tok.setKind(tok::kw___vector);
6721 case tok::identifier:
6722 if (Next.getIdentifierInfo() == Ident_pixel) {
6723 Tok.setKind(tok::kw___vector);
6726 if (Next.getIdentifierInfo() == Ident_bool) {
6727 Tok.setKind(tok::kw___vector);
6734 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6735 const char *&PrevSpec, unsigned &DiagID,
6737 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
6738 if (Tok.getIdentifierInfo() == Ident_vector) {
6739 Token Next = NextToken();
6740 switch (Next.getKind()) {
6743 case tok::kw_signed:
6744 case tok::kw_unsigned:
6749 case tok::kw_double:
6751 case tok::kw___bool:
6752 case tok::kw___pixel:
6753 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
6755 case tok::identifier:
6756 if (Next.getIdentifierInfo() == Ident_pixel) {
6757 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6760 if (Next.getIdentifierInfo() == Ident_bool) {
6761 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6768 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
6769 DS.isTypeAltiVecVector()) {
6770 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
6772 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
6773 DS.isTypeAltiVecVector()) {
6774 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);