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 DeclaratorContext Context,
49 ParsedAttributes *Attrs) {
50 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
51 if (DSC == DeclSpecContext::DSC_normal)
52 DSC = DeclSpecContext::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 /// \brief Normalizes an attribute name by dropping prefixed and suffixed __.
75 static StringRef normalizeAttrName(StringRef Name) {
76 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
77 return Name.drop_front(2).drop_back(2);
81 /// isAttributeLateParsed - Return true if the attribute has arguments that
82 /// require late parsing.
83 static bool isAttributeLateParsed(const IdentifierInfo &II) {
84 #define CLANG_ATTR_LATE_PARSED_LIST
85 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
86 #include "clang/Parse/AttrParserStringSwitches.inc"
88 #undef CLANG_ATTR_LATE_PARSED_LIST
91 /// ParseGNUAttributes - Parse a non-empty attributes list.
95 /// attributes attribute
98 /// '__attribute__' '(' '(' attribute-list ')' ')'
100 /// [GNU] attribute-list:
102 /// attribute_list ',' attrib
107 /// attrib-name '(' identifier ')'
108 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
109 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
111 /// [GNU] attrib-name:
117 /// Whether an attribute takes an 'identifier' is determined by the
118 /// attrib-name. GCC's behavior here is not worth imitating:
120 /// * In C mode, if the attribute argument list starts with an identifier
121 /// followed by a ',' or an ')', and the identifier doesn't resolve to
122 /// a type, it is parsed as an identifier. If the attribute actually
123 /// wanted an expression, it's out of luck (but it turns out that no
124 /// attributes work that way, because C constant expressions are very
126 /// * In C++ mode, if the attribute argument list starts with an identifier,
127 /// and the attribute *wants* an identifier, it is parsed as an identifier.
128 /// At block scope, any additional tokens between the identifier and the
129 /// ',' or ')' are ignored, otherwise they produce a parse error.
131 /// We follow the C++ model, but don't allow junk after the identifier.
132 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
133 SourceLocation *endLoc,
134 LateParsedAttrList *LateAttrs,
136 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
138 while (Tok.is(tok::kw___attribute)) {
140 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
142 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
145 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
146 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
149 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
151 // Allow empty/non-empty attributes. ((__vector_size__(16),,,,))
152 if (TryConsumeToken(tok::comma))
155 // Expect an identifier or declaration specifier (const, int, etc.)
156 if (Tok.isAnnotation())
158 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
162 SourceLocation AttrNameLoc = ConsumeToken();
164 if (Tok.isNot(tok::l_paren)) {
165 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
166 AttributeList::AS_GNU);
170 // Handle "parameterized" attributes
171 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
172 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
173 SourceLocation(), AttributeList::AS_GNU, D);
177 // Handle attributes with arguments that require late parsing.
178 LateParsedAttribute *LA =
179 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
180 LateAttrs->push_back(LA);
182 // Attributes in a class are parsed at the end of the class, along
183 // with other late-parsed declarations.
184 if (!ClassStack.empty() && !LateAttrs->parseSoon())
185 getCurrentClass().LateParsedDeclarations.push_back(LA);
187 // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
188 // recursively consumes balanced parens.
189 LA->Toks.push_back(Tok);
191 // Consume everything up to and including the matching right parens.
192 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
196 Eof.setLocation(Tok.getLocation());
197 LA->Toks.push_back(Eof);
200 if (ExpectAndConsume(tok::r_paren))
201 SkipUntil(tok::r_paren, StopAtSemi);
202 SourceLocation Loc = Tok.getLocation();
203 if (ExpectAndConsume(tok::r_paren))
204 SkipUntil(tok::r_paren, StopAtSemi);
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 if (const IdentifierInfo *const Ident = Platform->Ident) {
916 // Canonicalize platform name from "macosx" to "macos".
917 if (Ident->getName() == "macosx")
918 Platform->Ident = PP.getIdentifierInfo("macos");
919 // Canonicalize platform name from "macosx_app_extension" to
920 // "macos_app_extension".
921 else if (Ident->getName() == "macosx_app_extension")
922 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
924 Platform->Ident = PP.getIdentifierInfo(
925 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
928 // Parse the ',' following the platform name.
929 if (ExpectAndConsume(tok::comma)) {
930 SkipUntil(tok::r_paren, StopAtSemi);
934 // If we haven't grabbed the pointers for the identifiers
935 // "introduced", "deprecated", and "obsoleted", do so now.
936 if (!Ident_introduced) {
937 Ident_introduced = PP.getIdentifierInfo("introduced");
938 Ident_deprecated = PP.getIdentifierInfo("deprecated");
939 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
940 Ident_unavailable = PP.getIdentifierInfo("unavailable");
941 Ident_message = PP.getIdentifierInfo("message");
942 Ident_strict = PP.getIdentifierInfo("strict");
943 Ident_replacement = PP.getIdentifierInfo("replacement");
946 // Parse the optional "strict", the optional "replacement" and the set of
947 // introductions/deprecations/removals.
948 SourceLocation UnavailableLoc, StrictLoc;
950 if (Tok.isNot(tok::identifier)) {
951 Diag(Tok, diag::err_availability_expected_change);
952 SkipUntil(tok::r_paren, StopAtSemi);
955 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
956 SourceLocation KeywordLoc = ConsumeToken();
958 if (Keyword == Ident_strict) {
959 if (StrictLoc.isValid()) {
960 Diag(KeywordLoc, diag::err_availability_redundant)
961 << Keyword << SourceRange(StrictLoc);
963 StrictLoc = KeywordLoc;
967 if (Keyword == Ident_unavailable) {
968 if (UnavailableLoc.isValid()) {
969 Diag(KeywordLoc, diag::err_availability_redundant)
970 << Keyword << SourceRange(UnavailableLoc);
972 UnavailableLoc = KeywordLoc;
976 if (Tok.isNot(tok::equal)) {
977 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
978 SkipUntil(tok::r_paren, StopAtSemi);
982 if (Keyword == Ident_message || Keyword == Ident_replacement) {
983 if (Tok.isNot(tok::string_literal)) {
984 Diag(Tok, diag::err_expected_string_literal)
985 << /*Source='availability attribute'*/2;
986 SkipUntil(tok::r_paren, StopAtSemi);
989 if (Keyword == Ident_message)
990 MessageExpr = ParseStringLiteralExpression();
992 ReplacementExpr = ParseStringLiteralExpression();
993 // Also reject wide string literals.
994 if (StringLiteral *MessageStringLiteral =
995 cast_or_null<StringLiteral>(MessageExpr.get())) {
996 if (MessageStringLiteral->getCharByteWidth() != 1) {
997 Diag(MessageStringLiteral->getSourceRange().getBegin(),
998 diag::err_expected_string_literal)
999 << /*Source='availability attribute'*/ 2;
1000 SkipUntil(tok::r_paren, StopAtSemi);
1004 if (Keyword == Ident_message)
1010 // Special handling of 'NA' only when applied to introduced or
1012 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1013 Tok.is(tok::identifier)) {
1014 IdentifierInfo *NA = Tok.getIdentifierInfo();
1015 if (NA->getName() == "NA") {
1017 if (Keyword == Ident_introduced)
1018 UnavailableLoc = KeywordLoc;
1023 SourceRange VersionRange;
1024 VersionTuple Version = ParseVersionTuple(VersionRange);
1026 if (Version.empty()) {
1027 SkipUntil(tok::r_paren, StopAtSemi);
1032 if (Keyword == Ident_introduced)
1034 else if (Keyword == Ident_deprecated)
1036 else if (Keyword == Ident_obsoleted)
1041 if (Index < Unknown) {
1042 if (!Changes[Index].KeywordLoc.isInvalid()) {
1043 Diag(KeywordLoc, diag::err_availability_redundant)
1045 << SourceRange(Changes[Index].KeywordLoc,
1046 Changes[Index].VersionRange.getEnd());
1049 Changes[Index].KeywordLoc = KeywordLoc;
1050 Changes[Index].Version = Version;
1051 Changes[Index].VersionRange = VersionRange;
1053 Diag(KeywordLoc, diag::err_availability_unknown_change)
1054 << Keyword << VersionRange;
1057 } while (TryConsumeToken(tok::comma));
1060 if (T.consumeClose())
1064 *endLoc = T.getCloseLocation();
1066 // The 'unavailable' availability cannot be combined with any other
1067 // availability changes. Make sure that hasn't happened.
1068 if (UnavailableLoc.isValid()) {
1069 bool Complained = false;
1070 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1071 if (Changes[Index].KeywordLoc.isValid()) {
1073 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1074 << SourceRange(Changes[Index].KeywordLoc,
1075 Changes[Index].VersionRange.getEnd());
1079 // Clear out the availability.
1080 Changes[Index] = AvailabilityChange();
1085 // Record this attribute
1086 attrs.addNew(&Availability,
1087 SourceRange(AvailabilityLoc, T.getCloseLocation()),
1088 ScopeName, ScopeLoc,
1090 Changes[Introduced],
1091 Changes[Deprecated],
1093 UnavailableLoc, MessageExpr.get(),
1094 Syntax, StrictLoc, ReplacementExpr.get());
1097 /// \brief Parse the contents of the "external_source_symbol" attribute.
1099 /// external-source-symbol-attribute:
1100 /// 'external_source_symbol' '(' keyword-arg-list ')'
1102 /// keyword-arg-list:
1104 /// keyword-arg ',' keyword-arg-list
1107 /// 'language' '=' <string>
1108 /// 'defined_in' '=' <string>
1109 /// 'generated_declaration'
1110 void Parser::ParseExternalSourceSymbolAttribute(
1111 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1112 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1113 SourceLocation ScopeLoc, AttributeList::Syntax Syntax) {
1115 BalancedDelimiterTracker T(*this, tok::l_paren);
1116 if (T.expectAndConsume())
1119 // Initialize the pointers for the keyword identifiers when required.
1120 if (!Ident_language) {
1121 Ident_language = PP.getIdentifierInfo("language");
1122 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1123 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1126 ExprResult Language;
1127 bool HasLanguage = false;
1128 ExprResult DefinedInExpr;
1129 bool HasDefinedIn = false;
1130 IdentifierLoc *GeneratedDeclaration = nullptr;
1132 // Parse the language/defined_in/generated_declaration keywords
1134 if (Tok.isNot(tok::identifier)) {
1135 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1136 SkipUntil(tok::r_paren, StopAtSemi);
1140 SourceLocation KeywordLoc = Tok.getLocation();
1141 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1142 if (Keyword == Ident_generated_declaration) {
1143 if (GeneratedDeclaration) {
1144 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1145 SkipUntil(tok::r_paren, StopAtSemi);
1148 GeneratedDeclaration = ParseIdentifierLoc();
1152 if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1153 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1154 SkipUntil(tok::r_paren, StopAtSemi);
1159 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1160 Keyword->getName())) {
1161 SkipUntil(tok::r_paren, StopAtSemi);
1165 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1166 if (Keyword == Ident_language)
1169 HasDefinedIn = true;
1171 if (Tok.isNot(tok::string_literal)) {
1172 Diag(Tok, diag::err_expected_string_literal)
1173 << /*Source='external_source_symbol attribute'*/ 3
1174 << /*language | source container*/ (Keyword != Ident_language);
1175 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1178 if (Keyword == Ident_language) {
1180 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1182 ParseStringLiteralExpression();
1185 Language = ParseStringLiteralExpression();
1187 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1189 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1191 ParseStringLiteralExpression();
1194 DefinedInExpr = ParseStringLiteralExpression();
1196 } while (TryConsumeToken(tok::comma));
1199 if (T.consumeClose())
1202 *EndLoc = T.getCloseLocation();
1204 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1205 GeneratedDeclaration};
1206 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1207 ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1210 /// \brief Parse the contents of the "objc_bridge_related" attribute.
1211 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1215 /// opt-class_method:
1216 /// Identifier: | <empty>
1218 /// opt-instance_method:
1219 /// Identifier | <empty>
1221 void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1222 SourceLocation ObjCBridgeRelatedLoc,
1223 ParsedAttributes &attrs,
1224 SourceLocation *endLoc,
1225 IdentifierInfo *ScopeName,
1226 SourceLocation ScopeLoc,
1227 AttributeList::Syntax Syntax) {
1229 BalancedDelimiterTracker T(*this, tok::l_paren);
1230 if (T.consumeOpen()) {
1231 Diag(Tok, diag::err_expected) << tok::l_paren;
1235 // Parse the related class name.
1236 if (Tok.isNot(tok::identifier)) {
1237 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1238 SkipUntil(tok::r_paren, StopAtSemi);
1241 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1242 if (ExpectAndConsume(tok::comma)) {
1243 SkipUntil(tok::r_paren, StopAtSemi);
1247 // Parse optional class method name.
1248 IdentifierLoc *ClassMethod = nullptr;
1249 if (Tok.is(tok::identifier)) {
1250 ClassMethod = ParseIdentifierLoc();
1251 if (!TryConsumeToken(tok::colon)) {
1252 Diag(Tok, diag::err_objcbridge_related_selector_name);
1253 SkipUntil(tok::r_paren, StopAtSemi);
1257 if (!TryConsumeToken(tok::comma)) {
1258 if (Tok.is(tok::colon))
1259 Diag(Tok, diag::err_objcbridge_related_selector_name);
1261 Diag(Tok, diag::err_expected) << tok::comma;
1262 SkipUntil(tok::r_paren, StopAtSemi);
1266 // Parse optional instance method name.
1267 IdentifierLoc *InstanceMethod = nullptr;
1268 if (Tok.is(tok::identifier))
1269 InstanceMethod = ParseIdentifierLoc();
1270 else if (Tok.isNot(tok::r_paren)) {
1271 Diag(Tok, diag::err_expected) << tok::r_paren;
1272 SkipUntil(tok::r_paren, StopAtSemi);
1277 if (T.consumeClose())
1281 *endLoc = T.getCloseLocation();
1283 // Record this attribute
1284 attrs.addNew(&ObjCBridgeRelated,
1285 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1286 ScopeName, ScopeLoc,
1293 // Late Parsed Attributes:
1294 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1296 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1298 void Parser::LateParsedClass::ParseLexedAttributes() {
1299 Self->ParseLexedAttributes(*Class);
1302 void Parser::LateParsedAttribute::ParseLexedAttributes() {
1303 Self->ParseLexedAttribute(*this, true, false);
1306 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1307 /// scope appropriately.
1308 void Parser::ParseLexedAttributes(ParsingClass &Class) {
1309 // Deal with templates
1310 // FIXME: Test cases to make sure this does the right thing for templates.
1311 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1312 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1314 if (HasTemplateScope)
1315 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1317 // Set or update the scope flags.
1318 bool AlreadyHasClassScope = Class.TopLevelClass;
1319 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
1320 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1321 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1323 // Enter the scope of nested classes
1324 if (!AlreadyHasClassScope)
1325 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1326 Class.TagOrTemplate);
1327 if (!Class.LateParsedDeclarations.empty()) {
1328 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1329 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1333 if (!AlreadyHasClassScope)
1334 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1335 Class.TagOrTemplate);
1338 /// \brief Parse all attributes in LAs, and attach them to Decl D.
1339 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1340 bool EnterScope, bool OnDefinition) {
1341 assert(LAs.parseSoon() &&
1342 "Attribute list should be marked for immediate parsing.");
1343 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1346 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1352 /// \brief Finish parsing an attribute for which parsing was delayed.
1353 /// This will be called at the end of parsing a class declaration
1354 /// for each LateParsedAttribute. We consume the saved tokens and
1355 /// create an attribute with the arguments filled in. We add this
1356 /// to the Attribute list for the decl.
1357 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1358 bool EnterScope, bool OnDefinition) {
1359 // Create a fake EOF so that attribute parsing won't go off the end of the
1362 AttrEnd.startToken();
1363 AttrEnd.setKind(tok::eof);
1364 AttrEnd.setLocation(Tok.getLocation());
1365 AttrEnd.setEofData(LA.Toks.data());
1366 LA.Toks.push_back(AttrEnd);
1368 // Append the current token at the end of the new token stream so that it
1369 // doesn't get lost.
1370 LA.Toks.push_back(Tok);
1371 PP.EnterTokenStream(LA.Toks, true);
1372 // Consume the previously pushed token.
1373 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1375 ParsedAttributes Attrs(AttrFactory);
1376 SourceLocation endLoc;
1378 if (LA.Decls.size() > 0) {
1379 Decl *D = LA.Decls[0];
1380 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1381 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1383 // Allow 'this' within late-parsed attributes.
1384 Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0,
1385 ND && ND->isCXXInstanceMember());
1387 if (LA.Decls.size() == 1) {
1388 // If the Decl is templatized, add template parameters to scope.
1389 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1390 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1391 if (HasTemplateScope)
1392 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1394 // If the Decl is on a function, add function parameters to the scope.
1395 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1397 this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope,
1400 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1402 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1403 nullptr, SourceLocation(), AttributeList::AS_GNU,
1407 Actions.ActOnExitFunctionContext();
1408 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1410 if (HasTemplateScope) {
1414 // If there are multiple decls, then the decl cannot be within the
1416 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1417 nullptr, SourceLocation(), AttributeList::AS_GNU,
1421 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1424 const AttributeList *AL = Attrs.getList();
1425 if (OnDefinition && AL && !AL->isCXX11Attribute() &&
1427 Diag(Tok, diag::warn_attribute_on_function_definition)
1430 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
1431 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1433 // Due to a parsing error, we either went over the cached tokens or
1434 // there are still cached tokens left, so we skip the leftover tokens.
1435 while (Tok.isNot(tok::eof))
1438 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1442 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1443 SourceLocation AttrNameLoc,
1444 ParsedAttributes &Attrs,
1445 SourceLocation *EndLoc,
1446 IdentifierInfo *ScopeName,
1447 SourceLocation ScopeLoc,
1448 AttributeList::Syntax Syntax) {
1449 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1451 BalancedDelimiterTracker T(*this, tok::l_paren);
1454 if (Tok.isNot(tok::identifier)) {
1455 Diag(Tok, diag::err_expected) << tok::identifier;
1459 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1461 if (ExpectAndConsume(tok::comma)) {
1466 SourceRange MatchingCTypeRange;
1467 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1468 if (MatchingCType.isInvalid()) {
1473 bool LayoutCompatible = false;
1474 bool MustBeNull = false;
1475 while (TryConsumeToken(tok::comma)) {
1476 if (Tok.isNot(tok::identifier)) {
1477 Diag(Tok, diag::err_expected) << tok::identifier;
1481 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1482 if (Flag->isStr("layout_compatible"))
1483 LayoutCompatible = true;
1484 else if (Flag->isStr("must_be_null"))
1487 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1491 ConsumeToken(); // consume flag
1494 if (!T.consumeClose()) {
1495 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1496 ArgumentKind, MatchingCType.get(),
1497 LayoutCompatible, MustBeNull, Syntax);
1501 *EndLoc = T.getCloseLocation();
1504 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1505 /// of a C++11 attribute-specifier in a location where an attribute is not
1506 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1509 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1510 /// this doesn't appear to actually be an attribute-specifier, and the caller
1511 /// should try to parse it.
1512 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1513 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1515 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1516 case CAK_NotAttributeSpecifier:
1517 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1520 case CAK_InvalidAttributeSpecifier:
1521 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1524 case CAK_AttributeSpecifier:
1525 // Parse and discard the attributes.
1526 SourceLocation BeginLoc = ConsumeBracket();
1528 SkipUntil(tok::r_square);
1529 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1530 SourceLocation EndLoc = ConsumeBracket();
1531 Diag(BeginLoc, diag::err_attributes_not_allowed)
1532 << SourceRange(BeginLoc, EndLoc);
1535 llvm_unreachable("All cases handled above.");
1538 /// \brief We have found the opening square brackets of a C++11
1539 /// attribute-specifier in a location where an attribute is not permitted, but
1540 /// we know where the attributes ought to be written. Parse them anyway, and
1541 /// provide a fixit moving them to the right place.
1542 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1543 SourceLocation CorrectLocation) {
1544 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1545 Tok.is(tok::kw_alignas));
1547 // Consume the attributes.
1548 SourceLocation Loc = Tok.getLocation();
1549 ParseCXX11Attributes(Attrs);
1550 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1551 // FIXME: use err_attributes_misplaced
1552 Diag(Loc, diag::err_attributes_not_allowed)
1553 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1554 << FixItHint::CreateRemoval(AttrRange);
1557 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs,
1558 const SourceLocation CorrectLocation) {
1559 if (CorrectLocation.isValid()) {
1560 CharSourceRange AttrRange(attrs.Range, true);
1561 Diag(CorrectLocation, diag::err_attributes_misplaced)
1562 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1563 << FixItHint::CreateRemoval(AttrRange);
1565 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed) << attrs.Range;
1568 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1570 for (AttributeList *Attr = Attrs.getList(); Attr; Attr = Attr->getNext()) {
1571 if (!Attr->isCXX11Attribute() && !Attr->isC2xAttribute())
1573 if (Attr->getKind() == AttributeList::UnknownAttribute)
1574 Diag(Attr->getLoc(), diag::warn_unknown_attribute_ignored)
1577 Diag(Attr->getLoc(), DiagID)
1584 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1585 // applies to var, not the type Foo.
1586 // As an exception to the rule, __declspec(align(...)) before the
1587 // class-key affects the type instead of the variable.
1588 // Also, Microsoft-style [attributes] seem to affect the type instead of the
1590 // This function moves attributes that should apply to the type off DS to Attrs.
1591 void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1593 Sema::TagUseKind TUK) {
1594 if (TUK == Sema::TUK_Reference)
1597 ParsedAttributes &PA = DS.getAttributes();
1598 AttributeList *AL = PA.getList();
1599 AttributeList *Prev = nullptr;
1600 AttributeList *TypeAttrHead = nullptr;
1601 AttributeList *TypeAttrTail = nullptr;
1603 AttributeList *Next = AL->getNext();
1605 if ((AL->getKind() == AttributeList::AT_Aligned &&
1606 AL->isDeclspecAttribute()) ||
1607 AL->isMicrosoftAttribute()) {
1608 // Stitch the attribute into the tag's attribute list.
1610 TypeAttrTail->setNext(AL);
1614 TypeAttrTail->setNext(nullptr);
1616 // Remove the attribute from the variable's attribute list.
1618 // Set the last variable attribute's next attribute to be the attribute
1619 // after the current one.
1620 Prev->setNext(Next);
1622 // Removing the head of the list requires us to reset the head to the
1633 // Find end of type attributes Attrs and add NewTypeAttributes in the same
1634 // order they were in originally. (Remember, in AttributeList things earlier
1635 // in source order are later in the list, since new attributes are added to
1636 // the front of the list.)
1637 Attrs.addAllAtEnd(TypeAttrHead);
1640 /// ParseDeclaration - Parse a full 'declaration', which consists of
1641 /// declaration-specifiers, some number of declarators, and a semicolon.
1642 /// 'Context' should be a DeclaratorContext value. This returns the
1643 /// location of the semicolon in DeclEnd.
1645 /// declaration: [C99 6.7]
1646 /// block-declaration ->
1647 /// simple-declaration
1649 /// [C++] template-declaration
1650 /// [C++] namespace-definition
1651 /// [C++] using-directive
1652 /// [C++] using-declaration
1653 /// [C++11/C11] static_assert-declaration
1654 /// others... [FIXME]
1656 Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
1657 SourceLocation &DeclEnd,
1658 ParsedAttributesWithRange &attrs) {
1659 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1660 // Must temporarily exit the objective-c container scope for
1661 // parsing c none objective-c decls.
1662 ObjCDeclContextSwitch ObjCDC(*this);
1664 Decl *SingleDecl = nullptr;
1665 switch (Tok.getKind()) {
1666 case tok::kw_template:
1667 case tok::kw_export:
1668 ProhibitAttributes(attrs);
1669 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
1671 case tok::kw_inline:
1672 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1673 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1674 ProhibitAttributes(attrs);
1675 SourceLocation InlineLoc = ConsumeToken();
1676 return ParseNamespace(Context, DeclEnd, InlineLoc);
1678 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
1680 case tok::kw_namespace:
1681 ProhibitAttributes(attrs);
1682 return ParseNamespace(Context, DeclEnd);
1684 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1686 case tok::kw_static_assert:
1687 case tok::kw__Static_assert:
1688 ProhibitAttributes(attrs);
1689 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1692 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
1695 // This routine returns a DeclGroup, if the thing we parsed only contains a
1696 // single decl, convert it now.
1697 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1700 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1701 /// declaration-specifiers init-declarator-list[opt] ';'
1702 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1703 /// init-declarator-list ';'
1704 ///[C90/C++]init-declarator-list ';' [TODO]
1705 /// [OMP] threadprivate-directive [TODO]
1707 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1708 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1710 /// If RequireSemi is false, this does not check for a ';' at the end of the
1711 /// declaration. If it is true, it checks for and eats it.
1713 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1714 /// of a simple-declaration. If we find that we are, we also parse the
1715 /// for-range-initializer, and place it here.
1716 Parser::DeclGroupPtrTy
1717 Parser::ParseSimpleDeclaration(DeclaratorContext Context,
1718 SourceLocation &DeclEnd,
1719 ParsedAttributesWithRange &Attrs,
1720 bool RequireSemi, ForRangeInit *FRI) {
1721 // Parse the common declaration-specifiers piece.
1722 ParsingDeclSpec DS(*this);
1724 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1725 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1727 // If we had a free-standing type definition with a missing semicolon, we
1728 // may get this far before the problem becomes obvious.
1729 if (DS.hasTagDefinition() &&
1730 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1733 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1734 // declaration-specifiers init-declarator-list[opt] ';'
1735 if (Tok.is(tok::semi)) {
1736 ProhibitAttributes(Attrs);
1737 DeclEnd = Tok.getLocation();
1738 if (RequireSemi) ConsumeToken();
1739 RecordDecl *AnonRecord = nullptr;
1740 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1742 DS.complete(TheDecl);
1744 Decl* decls[] = {AnonRecord, TheDecl};
1745 return Actions.BuildDeclaratorGroup(decls);
1747 return Actions.ConvertDeclToDeclGroup(TheDecl);
1750 DS.takeAttributesFrom(Attrs);
1751 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1754 /// Returns true if this might be the start of a declarator, or a common typo
1755 /// for a declarator.
1756 bool Parser::MightBeDeclarator(DeclaratorContext Context) {
1757 switch (Tok.getKind()) {
1758 case tok::annot_cxxscope:
1759 case tok::annot_template_id:
1761 case tok::code_completion:
1762 case tok::coloncolon:
1764 case tok::kw___attribute:
1765 case tok::kw_operator:
1772 return getLangOpts().CPlusPlus;
1774 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1775 return Context == DeclaratorContext::MemberContext &&
1776 getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
1778 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1779 return Context == DeclaratorContext::MemberContext ||
1780 getLangOpts().CPlusPlus;
1782 case tok::identifier:
1783 switch (NextToken().getKind()) {
1784 case tok::code_completion:
1785 case tok::coloncolon:
1788 case tok::equalequal: // Might be a typo for '='.
1789 case tok::kw_alignas:
1791 case tok::kw___attribute:
1803 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1804 // and in block scope it's probably a label. Inside a class definition,
1805 // this is a bit-field.
1806 return Context == DeclaratorContext::MemberContext ||
1807 (getLangOpts().CPlusPlus &&
1808 Context == DeclaratorContext::FileContext);
1810 case tok::identifier: // Possible virt-specifier.
1811 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1822 /// Skip until we reach something which seems like a sensible place to pick
1823 /// up parsing after a malformed declaration. This will sometimes stop sooner
1824 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1825 void Parser::SkipMalformedDecl() {
1827 switch (Tok.getKind()) {
1829 // Skip until matching }, then stop. We've probably skipped over
1830 // a malformed class or function definition or similar.
1832 SkipUntil(tok::r_brace);
1833 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1834 // This declaration isn't over yet. Keep skipping.
1837 TryConsumeToken(tok::semi);
1842 SkipUntil(tok::r_square);
1847 SkipUntil(tok::r_paren);
1857 case tok::kw_inline:
1858 // 'inline namespace' at the start of a line is almost certainly
1859 // a good place to pick back up parsing, except in an Objective-C
1860 // @interface context.
1861 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1862 (!ParsingInObjCContainer || CurParsedObjCImpl))
1866 case tok::kw_namespace:
1867 // 'namespace' at the start of a line is almost certainly a good
1868 // place to pick back up parsing, except in an Objective-C
1869 // @interface context.
1870 if (Tok.isAtStartOfLine() &&
1871 (!ParsingInObjCContainer || CurParsedObjCImpl))
1876 // @end is very much like } in Objective-C contexts.
1877 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1878 ParsingInObjCContainer)
1884 // - and + probably start new method declarations in Objective-C contexts.
1885 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1890 case tok::annot_module_begin:
1891 case tok::annot_module_end:
1892 case tok::annot_module_include:
1903 /// ParseDeclGroup - Having concluded that this is either a function
1904 /// definition or a group of object declarations, actually parse the
1906 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1907 DeclaratorContext Context,
1908 SourceLocation *DeclEnd,
1909 ForRangeInit *FRI) {
1910 // Parse the first declarator.
1911 ParsingDeclarator D(*this, DS, Context);
1914 // Bail out if the first declarator didn't seem well-formed.
1915 if (!D.hasName() && !D.mayOmitIdentifier()) {
1916 SkipMalformedDecl();
1920 // Save late-parsed attributes for now; they need to be parsed in the
1921 // appropriate function scope after the function Decl has been constructed.
1922 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1923 LateParsedAttrList LateParsedAttrs(true);
1924 if (D.isFunctionDeclarator()) {
1925 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1927 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1928 // attribute. If we find the keyword here, tell the user to put it
1929 // at the start instead.
1930 if (Tok.is(tok::kw__Noreturn)) {
1931 SourceLocation Loc = ConsumeToken();
1932 const char *PrevSpec;
1935 // We can offer a fixit if it's valid to mark this function as _Noreturn
1936 // and we don't have any other declarators in this declaration.
1937 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1938 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1939 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
1941 Diag(Loc, diag::err_c11_noreturn_misplaced)
1942 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
1943 << (Fixit ? FixItHint::CreateInsertion(D.getLocStart(), "_Noreturn ")
1948 // Check to see if we have a function *definition* which must have a body.
1949 if (D.isFunctionDeclarator() &&
1950 // Look at the next token to make sure that this isn't a function
1951 // declaration. We have to check this because __attribute__ might be the
1952 // start of a function definition in GCC-extended K&R C.
1953 !isDeclarationAfterDeclarator()) {
1955 // Function definitions are only allowed at file scope and in C++ classes.
1956 // The C++ inline method definition case is handled elsewhere, so we only
1957 // need to handle the file scope definition case.
1958 if (Context == DeclaratorContext::FileContext) {
1959 if (isStartOfFunctionDefinition(D)) {
1960 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1961 Diag(Tok, diag::err_function_declared_typedef);
1963 // Recover by treating the 'typedef' as spurious.
1964 DS.ClearStorageClassSpecs();
1968 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1969 return Actions.ConvertDeclToDeclGroup(TheDecl);
1972 if (isDeclarationSpecifier()) {
1973 // If there is an invalid declaration specifier right after the
1974 // function prototype, then we must be in a missing semicolon case
1975 // where this isn't actually a body. Just fall through into the code
1976 // that handles it as a prototype, and let the top-level code handle
1977 // the erroneous declspec where it would otherwise expect a comma or
1980 Diag(Tok, diag::err_expected_fn_body);
1981 SkipUntil(tok::semi);
1985 if (Tok.is(tok::l_brace)) {
1986 Diag(Tok, diag::err_function_definition_not_allowed);
1987 SkipMalformedDecl();
1993 if (ParseAsmAttributesAfterDeclarator(D))
1996 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1997 // must parse and analyze the for-range-initializer before the declaration is
2000 // Handle the Objective-C for-in loop variable similarly, although we
2001 // don't need to parse the container in advance.
2002 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2003 bool IsForRangeLoop = false;
2004 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2005 IsForRangeLoop = true;
2006 if (Tok.is(tok::l_brace))
2007 FRI->RangeExpr = ParseBraceInitializer();
2009 FRI->RangeExpr = ParseExpression();
2012 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2014 Actions.ActOnCXXForRangeDecl(ThisDecl);
2015 Actions.FinalizeDeclaration(ThisDecl);
2016 D.complete(ThisDecl);
2017 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2020 SmallVector<Decl *, 8> DeclsInGroup;
2021 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2022 D, ParsedTemplateInfo(), FRI);
2023 if (LateParsedAttrs.size() > 0)
2024 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2025 D.complete(FirstDecl);
2027 DeclsInGroup.push_back(FirstDecl);
2029 bool ExpectSemi = Context != DeclaratorContext::ForContext;
2031 // If we don't have a comma, it is either the end of the list (a ';') or an
2033 SourceLocation CommaLoc;
2034 while (TryConsumeToken(tok::comma, CommaLoc)) {
2035 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2036 // This comma was followed by a line-break and something which can't be
2037 // the start of a declarator. The comma was probably a typo for a
2039 Diag(CommaLoc, diag::err_expected_semi_declaration)
2040 << FixItHint::CreateReplacement(CommaLoc, ";");
2045 // Parse the next declarator.
2047 D.setCommaLoc(CommaLoc);
2049 // Accept attributes in an init-declarator. In the first declarator in a
2050 // declaration, these would be part of the declspec. In subsequent
2051 // declarators, they become part of the declarator itself, so that they
2052 // don't apply to declarators after *this* one. Examples:
2053 // short __attribute__((common)) var; -> declspec
2054 // short var __attribute__((common)); -> declarator
2055 // short x, __attribute__((common)) var; -> declarator
2056 MaybeParseGNUAttributes(D);
2058 // MSVC parses but ignores qualifiers after the comma as an extension.
2059 if (getLangOpts().MicrosoftExt)
2060 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2063 if (!D.isInvalidType()) {
2064 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2065 D.complete(ThisDecl);
2067 DeclsInGroup.push_back(ThisDecl);
2072 *DeclEnd = Tok.getLocation();
2075 ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
2076 ? diag::err_invalid_token_after_toplevel_declarator
2077 : diag::err_expected_semi_declaration)) {
2078 // Okay, there was no semicolon and one was expected. If we see a
2079 // declaration specifier, just assume it was missing and continue parsing.
2080 // Otherwise things are very confused and we skip to recover.
2081 if (!isDeclarationSpecifier()) {
2082 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2083 TryConsumeToken(tok::semi);
2087 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2090 /// Parse an optional simple-asm-expr and attributes, and attach them to a
2091 /// declarator. Returns true on an error.
2092 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2093 // If a simple-asm-expr is present, parse it.
2094 if (Tok.is(tok::kw_asm)) {
2096 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2097 if (AsmLabel.isInvalid()) {
2098 SkipUntil(tok::semi, StopBeforeMatch);
2102 D.setAsmLabel(AsmLabel.get());
2106 MaybeParseGNUAttributes(D);
2110 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
2111 /// declarator'. This method parses the remainder of the declaration
2112 /// (including any attributes or initializer, among other things) and
2113 /// finalizes the declaration.
2115 /// init-declarator: [C99 6.7]
2117 /// declarator '=' initializer
2118 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2119 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2120 /// [C++] declarator initializer[opt]
2122 /// [C++] initializer:
2123 /// [C++] '=' initializer-clause
2124 /// [C++] '(' expression-list ')'
2125 /// [C++0x] '=' 'default' [TODO]
2126 /// [C++0x] '=' 'delete'
2127 /// [C++0x] braced-init-list
2129 /// According to the standard grammar, =default and =delete are function
2130 /// definitions, but that definitely doesn't fit with the parser here.
2132 Decl *Parser::ParseDeclarationAfterDeclarator(
2133 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2134 if (ParseAsmAttributesAfterDeclarator(D))
2137 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2140 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2141 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2142 // RAII type used to track whether we're inside an initializer.
2143 struct InitializerScopeRAII {
2148 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2149 : P(P), D(D), ThisDecl(ThisDecl) {
2150 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2152 if (D.getCXXScopeSpec().isSet()) {
2154 S = P.getCurScope();
2156 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2159 ~InitializerScopeRAII() { pop(); }
2161 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2163 if (D.getCXXScopeSpec().isSet())
2164 S = P.getCurScope();
2165 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2173 // Inform the current actions module that we just parsed this declarator.
2174 Decl *ThisDecl = nullptr;
2175 switch (TemplateInfo.Kind) {
2176 case ParsedTemplateInfo::NonTemplate:
2177 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2180 case ParsedTemplateInfo::Template:
2181 case ParsedTemplateInfo::ExplicitSpecialization: {
2182 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2183 *TemplateInfo.TemplateParams,
2185 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
2186 // Re-direct this decl to refer to the templated decl so that we can
2188 ThisDecl = VT->getTemplatedDecl();
2191 case ParsedTemplateInfo::ExplicitInstantiation: {
2192 if (Tok.is(tok::semi)) {
2193 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2194 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2195 if (ThisRes.isInvalid()) {
2196 SkipUntil(tok::semi, StopBeforeMatch);
2199 ThisDecl = ThisRes.get();
2201 // FIXME: This check should be for a variable template instantiation only.
2203 // Check that this is a valid instantiation
2204 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
2205 // If the declarator-id is not a template-id, issue a diagnostic and
2206 // recover by ignoring the 'template' keyword.
2207 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2208 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2209 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2211 SourceLocation LAngleLoc =
2212 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2213 Diag(D.getIdentifierLoc(),
2214 diag::err_explicit_instantiation_with_definition)
2215 << SourceRange(TemplateInfo.TemplateLoc)
2216 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2218 // Recover as if it were an explicit specialization.
2219 TemplateParameterLists FakedParamLists;
2220 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2221 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
2222 LAngleLoc, nullptr));
2225 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2232 // Parse declarator '=' initializer.
2233 // If a '==' or '+=' is found, suggest a fixit to '='.
2234 if (isTokenEqualOrEqualTypo()) {
2235 SourceLocation EqualLoc = ConsumeToken();
2237 if (Tok.is(tok::kw_delete)) {
2238 if (D.isFunctionDeclarator())
2239 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2242 Diag(ConsumeToken(), diag::err_deleted_non_function);
2243 } else if (Tok.is(tok::kw_default)) {
2244 if (D.isFunctionDeclarator())
2245 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2248 Diag(ConsumeToken(), diag::err_default_special_members);
2250 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2252 if (Tok.is(tok::code_completion)) {
2253 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2254 Actions.FinalizeDeclaration(ThisDecl);
2259 ExprResult Init(ParseInitializer());
2261 // If this is the only decl in (possibly) range based for statement,
2262 // our best guess is that the user meant ':' instead of '='.
2263 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2264 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2265 << FixItHint::CreateReplacement(EqualLoc, ":");
2266 // We are trying to stop parser from looking for ';' in this for
2267 // statement, therefore preventing spurious errors to be issued.
2268 FRI->ColonLoc = EqualLoc;
2270 FRI->RangeExpr = Init;
2275 if (Init.isInvalid()) {
2276 SmallVector<tok::TokenKind, 2> StopTokens;
2277 StopTokens.push_back(tok::comma);
2278 if (D.getContext() == DeclaratorContext::ForContext ||
2279 D.getContext() == DeclaratorContext::InitStmtContext)
2280 StopTokens.push_back(tok::r_paren);
2281 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2282 Actions.ActOnInitializerError(ThisDecl);
2284 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2285 /*DirectInit=*/false);
2287 } else if (Tok.is(tok::l_paren)) {
2288 // Parse C++ direct initializer: '(' expression-list ')'
2289 BalancedDelimiterTracker T(*this, tok::l_paren);
2293 CommaLocsTy CommaLocs;
2295 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2297 llvm::function_ref<void()> ExprListCompleter;
2298 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2299 auto ConstructorCompleter = [&, ThisVarDecl] {
2300 Actions.CodeCompleteConstructor(
2301 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2302 ThisDecl->getLocation(), Exprs);
2305 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2306 // VarDecl. This is an error and it is reported in a call to
2307 // Actions.ActOnInitializerError(). However, we call
2308 // CodeCompleteConstructor only on VarDecls, falling back to default
2309 // completer in other cases.
2310 ExprListCompleter = ConstructorCompleter;
2313 if (ParseExpressionList(Exprs, CommaLocs, ExprListCompleter)) {
2314 Actions.ActOnInitializerError(ThisDecl);
2315 SkipUntil(tok::r_paren, StopAtSemi);
2320 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2321 "Unexpected number of commas!");
2325 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2326 T.getCloseLocation(),
2328 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2329 /*DirectInit=*/true);
2331 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2332 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
2333 // Parse C++0x braced-init-list.
2334 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2336 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2338 ExprResult Init(ParseBraceInitializer());
2342 if (Init.isInvalid()) {
2343 Actions.ActOnInitializerError(ThisDecl);
2345 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2348 Actions.ActOnUninitializedDecl(ThisDecl);
2351 Actions.FinalizeDeclaration(ThisDecl);
2356 /// ParseSpecifierQualifierList
2357 /// specifier-qualifier-list:
2358 /// type-specifier specifier-qualifier-list[opt]
2359 /// type-qualifier specifier-qualifier-list[opt]
2360 /// [GNU] attributes specifier-qualifier-list[opt]
2362 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2363 DeclSpecContext DSC) {
2364 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2365 /// parse declaration-specifiers and complain about extra stuff.
2366 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2367 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2369 // Validate declspec for type-name.
2370 unsigned Specs = DS.getParsedSpecifiers();
2371 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2372 Diag(Tok, diag::err_expected_type);
2373 DS.SetTypeSpecError();
2374 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2375 Diag(Tok, diag::err_typename_requires_specqual);
2376 if (!DS.hasTypeSpecifier())
2377 DS.SetTypeSpecError();
2380 // Issue diagnostic and remove storage class if present.
2381 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2382 if (DS.getStorageClassSpecLoc().isValid())
2383 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2385 Diag(DS.getThreadStorageClassSpecLoc(),
2386 diag::err_typename_invalid_storageclass);
2387 DS.ClearStorageClassSpecs();
2390 // Issue diagnostic and remove function specifier if present.
2391 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2392 if (DS.isInlineSpecified())
2393 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2394 if (DS.isVirtualSpecified())
2395 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2396 if (DS.isExplicitSpecified())
2397 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2398 DS.ClearFunctionSpecs();
2401 // Issue diagnostic and remove constexpr specfier if present.
2402 if (DS.isConstexprSpecified() && DSC != DeclSpecContext::DSC_condition) {
2403 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2404 DS.ClearConstexprSpec();
2408 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2409 /// specified token is valid after the identifier in a declarator which
2410 /// immediately follows the declspec. For example, these things are valid:
2412 /// int x [ 4]; // direct-declarator
2413 /// int x ( int y); // direct-declarator
2414 /// int(int x ) // direct-declarator
2415 /// int x ; // simple-declaration
2416 /// int x = 17; // init-declarator-list
2417 /// int x , y; // init-declarator-list
2418 /// int x __asm__ ("foo"); // init-declarator-list
2419 /// int x : 4; // struct-declarator
2420 /// int x { 5}; // C++'0x unified initializers
2422 /// This is not, because 'x' does not immediately follow the declspec (though
2423 /// ')' happens to be valid anyway).
2426 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2427 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2428 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2432 /// ParseImplicitInt - This method is called when we have an non-typename
2433 /// identifier in a declspec (which normally terminates the decl spec) when
2434 /// the declspec has no type specifier. In this case, the declspec is either
2435 /// malformed or is "implicit int" (in K&R and C89).
2437 /// This method handles diagnosing this prettily and returns false if the
2438 /// declspec is done being processed. If it recovers and thinks there may be
2439 /// other pieces of declspec after it, it returns true.
2441 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2442 const ParsedTemplateInfo &TemplateInfo,
2443 AccessSpecifier AS, DeclSpecContext DSC,
2444 ParsedAttributesWithRange &Attrs) {
2445 assert(Tok.is(tok::identifier) && "should have identifier");
2447 SourceLocation Loc = Tok.getLocation();
2448 // If we see an identifier that is not a type name, we normally would
2449 // parse it as the identifer being declared. However, when a typename
2450 // is typo'd or the definition is not included, this will incorrectly
2451 // parse the typename as the identifier name and fall over misparsing
2452 // later parts of the diagnostic.
2454 // As such, we try to do some look-ahead in cases where this would
2455 // otherwise be an "implicit-int" case to see if this is invalid. For
2456 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2457 // an identifier with implicit int, we'd get a parse error because the
2458 // next token is obviously invalid for a type. Parse these as a case
2459 // with an invalid type specifier.
2460 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2462 // Since we know that this either implicit int (which is rare) or an
2463 // error, do lookahead to try to do better recovery. This never applies
2464 // within a type specifier. Outside of C++, we allow this even if the
2465 // language doesn't "officially" support implicit int -- we support
2466 // implicit int as an extension in C99 and C11.
2467 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2468 isValidAfterIdentifierInDeclarator(NextToken())) {
2469 // If this token is valid for implicit int, e.g. "static x = 4", then
2470 // we just avoid eating the identifier, so it will be parsed as the
2471 // identifier in the declarator.
2475 if (getLangOpts().CPlusPlus &&
2476 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2477 // Don't require a type specifier if we have the 'auto' storage class
2478 // specifier in C++98 -- we'll promote it to a type specifier.
2480 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2484 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2485 getLangOpts().MSVCCompat) {
2486 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2487 // Give Sema a chance to recover if we are in a template with dependent base
2489 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2490 *Tok.getIdentifierInfo(), Tok.getLocation(),
2491 DSC == DeclSpecContext::DSC_template_type_arg)) {
2492 const char *PrevSpec;
2494 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2495 Actions.getASTContext().getPrintingPolicy());
2496 DS.SetRangeEnd(Tok.getLocation());
2502 // Otherwise, if we don't consume this token, we are going to emit an
2503 // error anyway. Try to recover from various common problems. Check
2504 // to see if this was a reference to a tag name without a tag specified.
2505 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2507 // C++ doesn't need this, and isTagName doesn't take SS.
2508 if (SS == nullptr) {
2509 const char *TagName = nullptr, *FixitTagName = nullptr;
2510 tok::TokenKind TagKind = tok::unknown;
2512 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2514 case DeclSpec::TST_enum:
2515 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2516 case DeclSpec::TST_union:
2517 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2518 case DeclSpec::TST_struct:
2519 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2520 case DeclSpec::TST_interface:
2521 TagName="__interface"; FixitTagName = "__interface ";
2522 TagKind=tok::kw___interface;break;
2523 case DeclSpec::TST_class:
2524 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2528 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2529 LookupResult R(Actions, TokenName, SourceLocation(),
2530 Sema::LookupOrdinaryName);
2532 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2533 << TokenName << TagName << getLangOpts().CPlusPlus
2534 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2536 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2537 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2539 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2540 << TokenName << TagName;
2543 // Parse this as a tag as if the missing tag were present.
2544 if (TagKind == tok::kw_enum)
2545 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2546 DeclSpecContext::DSC_normal);
2548 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2549 /*EnteringContext*/ false,
2550 DeclSpecContext::DSC_normal, Attrs);
2555 // Determine whether this identifier could plausibly be the name of something
2556 // being declared (with a missing type).
2557 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2558 DSC == DeclSpecContext::DSC_class)) {
2559 // Look ahead to the next token to try to figure out what this declaration
2560 // was supposed to be.
2561 switch (NextToken().getKind()) {
2562 case tok::l_paren: {
2563 // static x(4); // 'x' is not a type
2564 // x(int n); // 'x' is not a type
2565 // x (*p)[]; // 'x' is a type
2567 // Since we're in an error case, we can afford to perform a tentative
2568 // parse to determine which case we're in.
2569 TentativeParsingAction PA(*this);
2571 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2574 if (TPR != TPResult::False) {
2575 // The identifier is followed by a parenthesized declarator.
2576 // It's supposed to be a type.
2580 // If we're in a context where we could be declaring a constructor,
2581 // check whether this is a constructor declaration with a bogus name.
2582 if (DSC == DeclSpecContext::DSC_class ||
2583 (DSC == DeclSpecContext::DSC_top_level && SS)) {
2584 IdentifierInfo *II = Tok.getIdentifierInfo();
2585 if (Actions.isCurrentClassNameTypo(II, SS)) {
2586 Diag(Loc, diag::err_constructor_bad_name)
2587 << Tok.getIdentifierInfo() << II
2588 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2589 Tok.setIdentifierInfo(II);
2601 // This looks like a variable or function declaration. The type is
2602 // probably missing. We're done parsing decl-specifiers.
2604 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2608 // This is probably supposed to be a type. This includes cases like:
2610 // struct S { unsinged : 4; };
2615 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2616 // and attempt to recover.
2618 IdentifierInfo *II = Tok.getIdentifierInfo();
2619 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2620 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2623 // The action has suggested that the type T could be used. Set that as
2624 // the type in the declaration specifiers, consume the would-be type
2625 // name token, and we're done.
2626 const char *PrevSpec;
2628 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2629 Actions.getASTContext().getPrintingPolicy());
2630 DS.SetRangeEnd(Tok.getLocation());
2632 // There may be other declaration specifiers after this.
2634 } else if (II != Tok.getIdentifierInfo()) {
2635 // If no type was suggested, the correction is to a keyword
2636 Tok.setKind(II->getTokenID());
2637 // There may be other declaration specifiers after this.
2641 // Otherwise, the action had no suggestion for us. Mark this as an error.
2642 DS.SetTypeSpecError();
2643 DS.SetRangeEnd(Tok.getLocation());
2646 // Eat any following template arguments.
2647 if (IsTemplateName) {
2648 SourceLocation LAngle, RAngle;
2649 TemplateArgList Args;
2650 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2653 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2654 // avoid rippling error messages on subsequent uses of the same type,
2655 // could be useful if #include was forgotten.
2659 /// \brief Determine the declaration specifier context from the declarator
2662 /// \param Context the declarator context, which is one of the
2663 /// DeclaratorContext enumerator values.
2664 Parser::DeclSpecContext
2665 Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2666 if (Context == DeclaratorContext::MemberContext)
2667 return DeclSpecContext::DSC_class;
2668 if (Context == DeclaratorContext::FileContext)
2669 return DeclSpecContext::DSC_top_level;
2670 if (Context == DeclaratorContext::TemplateParamContext)
2671 return DeclSpecContext::DSC_template_param;
2672 if (Context == DeclaratorContext::TemplateTypeArgContext)
2673 return DeclSpecContext::DSC_template_type_arg;
2674 if (Context == DeclaratorContext::TrailingReturnContext)
2675 return DeclSpecContext::DSC_trailing;
2676 if (Context == DeclaratorContext::AliasDeclContext ||
2677 Context == DeclaratorContext::AliasTemplateContext)
2678 return DeclSpecContext::DSC_alias_declaration;
2679 return DeclSpecContext::DSC_normal;
2682 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2684 /// FIXME: Simply returns an alignof() expression if the argument is a
2685 /// type. Ideally, the type should be propagated directly into Sema.
2688 /// [C11] constant-expression
2689 /// [C++0x] type-id ...[opt]
2690 /// [C++0x] assignment-expression ...[opt]
2691 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2692 SourceLocation &EllipsisLoc) {
2694 if (isTypeIdInParens()) {
2695 SourceLocation TypeLoc = Tok.getLocation();
2696 ParsedType Ty = ParseTypeName().get();
2697 SourceRange TypeRange(Start, Tok.getLocation());
2698 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2699 Ty.getAsOpaquePtr(), TypeRange);
2701 ER = ParseConstantExpression();
2703 if (getLangOpts().CPlusPlus11)
2704 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2709 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2710 /// attribute to Attrs.
2712 /// alignment-specifier:
2713 /// [C11] '_Alignas' '(' type-id ')'
2714 /// [C11] '_Alignas' '(' constant-expression ')'
2715 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2716 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2717 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2718 SourceLocation *EndLoc) {
2719 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2720 "Not an alignment-specifier!");
2722 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2723 SourceLocation KWLoc = ConsumeToken();
2725 BalancedDelimiterTracker T(*this, tok::l_paren);
2726 if (T.expectAndConsume())
2729 SourceLocation EllipsisLoc;
2730 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2731 if (ArgExpr.isInvalid()) {
2738 *EndLoc = T.getCloseLocation();
2740 ArgsVector ArgExprs;
2741 ArgExprs.push_back(ArgExpr.get());
2742 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2743 AttributeList::AS_Keyword, EllipsisLoc);
2746 /// Determine whether we're looking at something that might be a declarator
2747 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2748 /// diagnose a missing semicolon after a prior tag definition in the decl
2751 /// \return \c true if an error occurred and this can't be any kind of
2754 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2755 DeclSpecContext DSContext,
2756 LateParsedAttrList *LateAttrs) {
2757 assert(DS.hasTagDefinition() && "shouldn't call this");
2759 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2760 DSContext == DeclSpecContext::DSC_top_level);
2762 if (getLangOpts().CPlusPlus &&
2763 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2764 tok::annot_template_id) &&
2765 TryAnnotateCXXScopeToken(EnteringContext)) {
2766 SkipMalformedDecl();
2770 bool HasScope = Tok.is(tok::annot_cxxscope);
2771 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2772 Token AfterScope = HasScope ? NextToken() : Tok;
2774 // Determine whether the following tokens could possibly be a
2776 bool MightBeDeclarator = true;
2777 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2778 // A declarator-id can't start with 'typename'.
2779 MightBeDeclarator = false;
2780 } else if (AfterScope.is(tok::annot_template_id)) {
2781 // If we have a type expressed as a template-id, this cannot be a
2782 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2783 TemplateIdAnnotation *Annot =
2784 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2785 if (Annot->Kind == TNK_Type_template)
2786 MightBeDeclarator = false;
2787 } else if (AfterScope.is(tok::identifier)) {
2788 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2790 // These tokens cannot come after the declarator-id in a
2791 // simple-declaration, and are likely to come after a type-specifier.
2792 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2793 tok::annot_cxxscope, tok::coloncolon)) {
2794 // Missing a semicolon.
2795 MightBeDeclarator = false;
2796 } else if (HasScope) {
2797 // If the declarator-id has a scope specifier, it must redeclare a
2798 // previously-declared entity. If that's a type (and this is not a
2799 // typedef), that's an error.
2801 Actions.RestoreNestedNameSpecifierAnnotation(
2802 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2803 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2804 Sema::NameClassification Classification = Actions.ClassifyName(
2805 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2806 /*IsAddressOfOperand*/false);
2807 switch (Classification.getKind()) {
2808 case Sema::NC_Error:
2809 SkipMalformedDecl();
2812 case Sema::NC_Keyword:
2813 case Sema::NC_NestedNameSpecifier:
2814 llvm_unreachable("typo correction and nested name specifiers not "
2818 case Sema::NC_TypeTemplate:
2819 // Not a previously-declared non-type entity.
2820 MightBeDeclarator = false;
2823 case Sema::NC_Unknown:
2824 case Sema::NC_Expression:
2825 case Sema::NC_VarTemplate:
2826 case Sema::NC_FunctionTemplate:
2827 // Might be a redeclaration of a prior entity.
2833 if (MightBeDeclarator)
2836 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2837 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()),
2838 diag::err_expected_after)
2839 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2841 // Try to recover from the typo, by dropping the tag definition and parsing
2842 // the problematic tokens as a type.
2844 // FIXME: Split the DeclSpec into pieces for the standalone
2845 // declaration and pieces for the following declaration, instead
2846 // of assuming that all the other pieces attach to new declaration,
2847 // and call ParsedFreeStandingDeclSpec as appropriate.
2848 DS.ClearTypeSpecType();
2849 ParsedTemplateInfo NotATemplate;
2850 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2854 /// ParseDeclarationSpecifiers
2855 /// declaration-specifiers: [C99 6.7]
2856 /// storage-class-specifier declaration-specifiers[opt]
2857 /// type-specifier declaration-specifiers[opt]
2858 /// [C99] function-specifier declaration-specifiers[opt]
2859 /// [C11] alignment-specifier declaration-specifiers[opt]
2860 /// [GNU] attributes declaration-specifiers[opt]
2861 /// [Clang] '__module_private__' declaration-specifiers[opt]
2862 /// [ObjC1] '__kindof' declaration-specifiers[opt]
2864 /// storage-class-specifier: [C99 6.7.1]
2871 /// [C++11] 'thread_local'
2872 /// [C11] '_Thread_local'
2873 /// [GNU] '__thread'
2874 /// function-specifier: [C99 6.7.4]
2877 /// [C++] 'explicit'
2878 /// [OpenCL] '__kernel'
2879 /// 'friend': [C++ dcl.friend]
2880 /// 'constexpr': [C++0x dcl.constexpr]
2881 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2882 const ParsedTemplateInfo &TemplateInfo,
2884 DeclSpecContext DSContext,
2885 LateParsedAttrList *LateAttrs) {
2886 if (DS.getSourceRange().isInvalid()) {
2887 // Start the range at the current token but make the end of the range
2888 // invalid. This will make the entire range invalid unless we successfully
2890 DS.SetRangeStart(Tok.getLocation());
2891 DS.SetRangeEnd(SourceLocation());
2894 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2895 DSContext == DeclSpecContext::DSC_top_level);
2896 bool AttrsLastTime = false;
2897 ParsedAttributesWithRange attrs(AttrFactory);
2898 // We use Sema's policy to get bool macros right.
2899 PrintingPolicy Policy = Actions.getPrintingPolicy();
2901 bool isInvalid = false;
2902 bool isStorageClass = false;
2903 const char *PrevSpec = nullptr;
2904 unsigned DiagID = 0;
2906 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2907 // implementation for VS2013 uses _Atomic as an identifier for one of the
2908 // classes in <atomic>.
2910 // A typedef declaration containing _Atomic<...> is among the places where
2911 // the class is used. If we are currently parsing such a declaration, treat
2912 // the token as an identifier.
2913 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2914 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
2915 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
2916 Tok.setKind(tok::identifier);
2918 SourceLocation Loc = Tok.getLocation();
2920 switch (Tok.getKind()) {
2924 ProhibitAttributes(attrs);
2926 // Reject C++11 attributes that appertain to decl specifiers as
2927 // we don't support any C++11 attributes that appertain to decl
2928 // specifiers. This also conforms to what g++ 4.8 is doing.
2929 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
2931 DS.takeAttributesFrom(attrs);
2934 // If this is not a declaration specifier token, we're done reading decl
2935 // specifiers. First verify that DeclSpec's are consistent.
2936 DS.Finish(Actions, Policy);
2940 case tok::kw_alignas:
2941 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
2942 goto DoneWithDeclSpec;
2944 ProhibitAttributes(attrs);
2945 // FIXME: It would be good to recover by accepting the attributes,
2946 // but attempting to do that now would cause serious
2947 // madness in terms of diagnostics.
2949 attrs.Range = SourceRange();
2951 ParseCXX11Attributes(attrs);
2952 AttrsLastTime = true;
2955 case tok::code_completion: {
2956 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2957 if (DS.hasTypeSpecifier()) {
2958 bool AllowNonIdentifiers
2959 = (getCurScope()->getFlags() & (Scope::ControlScope |
2961 Scope::TemplateParamScope |
2962 Scope::FunctionPrototypeScope |
2963 Scope::AtCatchScope)) == 0;
2964 bool AllowNestedNameSpecifiers
2965 = DSContext == DeclSpecContext::DSC_top_level ||
2966 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
2968 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
2969 AllowNonIdentifiers,
2970 AllowNestedNameSpecifiers);
2971 return cutOffParsing();
2974 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
2975 CCC = Sema::PCC_LocalDeclarationSpecifiers;
2976 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
2977 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
2978 : Sema::PCC_Template;
2979 else if (DSContext == DeclSpecContext::DSC_class)
2980 CCC = Sema::PCC_Class;
2981 else if (CurParsedObjCImpl)
2982 CCC = Sema::PCC_ObjCImplementation;
2984 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
2985 return cutOffParsing();
2988 case tok::coloncolon: // ::foo::bar
2989 // C++ scope specifier. Annotate and loop, or bail out on error.
2990 if (TryAnnotateCXXScopeToken(EnteringContext)) {
2991 if (!DS.hasTypeSpecifier())
2992 DS.SetTypeSpecError();
2993 goto DoneWithDeclSpec;
2995 if (Tok.is(tok::coloncolon)) // ::new or ::delete
2996 goto DoneWithDeclSpec;
2999 case tok::annot_cxxscope: {
3000 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3001 goto DoneWithDeclSpec;
3004 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3005 Tok.getAnnotationRange(),
3008 // We are looking for a qualified typename.
3009 Token Next = NextToken();
3010 if (Next.is(tok::annot_template_id) &&
3011 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3012 ->Kind == TNK_Type_template) {
3013 // We have a qualified template-id, e.g., N::A<int>
3015 // If this would be a valid constructor declaration with template
3016 // arguments, we will reject the attempt to form an invalid type-id
3017 // referring to the injected-class-name when we annotate the token,
3018 // per C++ [class.qual]p2.
3020 // To improve diagnostics for this case, parse the declaration as a
3021 // constructor (and reject the extra template arguments later).
3022 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
3023 if ((DSContext == DeclSpecContext::DSC_top_level ||
3024 DSContext == DeclSpecContext::DSC_class) &&
3026 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3027 isConstructorDeclarator(/*Unqualified*/ false)) {
3028 // The user meant this to be an out-of-line constructor
3029 // definition, but template arguments are not allowed
3030 // there. Just allow this as a constructor; we'll
3031 // complain about it later.
3032 goto DoneWithDeclSpec;
3035 DS.getTypeSpecScope() = SS;
3036 ConsumeAnnotationToken(); // The C++ scope.
3037 assert(Tok.is(tok::annot_template_id) &&
3038 "ParseOptionalCXXScopeSpecifier not working");
3039 AnnotateTemplateIdTokenAsType();
3043 if (Next.is(tok::annot_typename)) {
3044 DS.getTypeSpecScope() = SS;
3045 ConsumeAnnotationToken(); // The C++ scope.
3046 if (Tok.getAnnotationValue()) {
3047 ParsedType T = getTypeAnnotation(Tok);
3048 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3049 Tok.getAnnotationEndLoc(),
3050 PrevSpec, DiagID, T, Policy);
3055 DS.SetTypeSpecError();
3056 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3057 ConsumeAnnotationToken(); // The typename
3060 if (Next.isNot(tok::identifier))
3061 goto DoneWithDeclSpec;
3063 // Check whether this is a constructor declaration. If we're in a
3064 // context where the identifier could be a class name, and it has the
3065 // shape of a constructor declaration, process it as one.
3066 if ((DSContext == DeclSpecContext::DSC_top_level ||
3067 DSContext == DeclSpecContext::DSC_class) &&
3068 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3070 isConstructorDeclarator(/*Unqualified*/ false))
3071 goto DoneWithDeclSpec;
3073 ParsedType TypeRep =
3074 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3075 getCurScope(), &SS, false, false, nullptr,
3076 /*IsCtorOrDtorName=*/false,
3077 /*WantNonTrivialSourceInfo=*/true,
3078 isClassTemplateDeductionContext(DSContext));
3080 // If the referenced identifier is not a type, then this declspec is
3081 // erroneous: We already checked about that it has no type specifier, and
3082 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3085 // Eat the scope spec so the identifier is current.
3086 ConsumeAnnotationToken();
3087 ParsedAttributesWithRange Attrs(AttrFactory);
3088 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3089 if (!Attrs.empty()) {
3090 AttrsLastTime = true;
3091 attrs.takeAllFrom(Attrs);
3095 goto DoneWithDeclSpec;
3098 DS.getTypeSpecScope() = SS;
3099 ConsumeAnnotationToken(); // The C++ scope.
3101 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3102 DiagID, TypeRep, Policy);
3106 DS.SetRangeEnd(Tok.getLocation());
3107 ConsumeToken(); // The typename.
3112 case tok::annot_typename: {
3113 // If we've previously seen a tag definition, we were almost surely
3114 // missing a semicolon after it.
3115 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3116 goto DoneWithDeclSpec;
3118 if (Tok.getAnnotationValue()) {
3119 ParsedType T = getTypeAnnotation(Tok);
3120 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3123 DS.SetTypeSpecError();
3128 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3129 ConsumeAnnotationToken(); // The typename
3134 case tok::kw___is_signed:
3135 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3136 // typically treats it as a trait. If we see __is_signed as it appears
3137 // in libstdc++, e.g.,
3139 // static const bool __is_signed;
3141 // then treat __is_signed as an identifier rather than as a keyword.
3142 if (DS.getTypeSpecType() == TST_bool &&
3143 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3144 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3145 TryKeywordIdentFallback(true);
3147 // We're done with the declaration-specifiers.
3148 goto DoneWithDeclSpec;
3151 case tok::kw___super:
3152 case tok::kw_decltype:
3153 case tok::identifier: {
3154 // This identifier can only be a typedef name if we haven't already seen
3155 // a type-specifier. Without this check we misparse:
3156 // typedef int X; struct Y { short X; }; as 'short int'.
3157 if (DS.hasTypeSpecifier())
3158 goto DoneWithDeclSpec;
3160 // If the token is an identifier named "__declspec" and Microsoft
3161 // extensions are not enabled, it is likely that there will be cascading
3162 // parse errors if this really is a __declspec attribute. Attempt to
3163 // recognize that scenario and recover gracefully.
3164 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3165 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3166 Diag(Loc, diag::err_ms_attributes_not_enabled);
3168 // The next token should be an open paren. If it is, eat the entire
3169 // attribute declaration and continue.
3170 if (NextToken().is(tok::l_paren)) {
3171 // Consume the __declspec identifier.
3174 // Eat the parens and everything between them.
3175 BalancedDelimiterTracker T(*this, tok::l_paren);
3176 if (T.consumeOpen()) {
3177 assert(false && "Not a left paren?");
3185 // In C++, check to see if this is a scope specifier like foo::bar::, if
3186 // so handle it as such. This is important for ctor parsing.
3187 if (getLangOpts().CPlusPlus) {
3188 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3189 DS.SetTypeSpecError();
3190 goto DoneWithDeclSpec;
3192 if (!Tok.is(tok::identifier))
3196 // Check for need to substitute AltiVec keyword tokens.
3197 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3200 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3201 // allow the use of a typedef name as a type specifier.
3202 if (DS.isTypeAltiVecVector())
3203 goto DoneWithDeclSpec;
3205 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3206 isObjCInstancetype()) {
3207 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3209 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3210 DiagID, TypeRep, Policy);
3214 DS.SetRangeEnd(Loc);
3219 ParsedType TypeRep = Actions.getTypeName(
3220 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3221 false, false, nullptr, false, false,
3222 isClassTemplateDeductionContext(DSContext));
3224 // If this is not a typedef name, don't parse it as part of the declspec,
3225 // it must be an implicit int or an error.
3227 ParsedAttributesWithRange Attrs(AttrFactory);
3228 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3229 if (!Attrs.empty()) {
3230 AttrsLastTime = true;
3231 attrs.takeAllFrom(Attrs);
3235 goto DoneWithDeclSpec;
3238 // If we're in a context where the identifier could be a class name,
3239 // check whether this is a constructor declaration.
3240 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3241 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3242 isConstructorDeclarator(/*Unqualified*/true))
3243 goto DoneWithDeclSpec;
3245 // Likewise, if this is a context where the identifier could be a template
3246 // name, check whether this is a deduction guide declaration.
3247 if (getLangOpts().CPlusPlus17 &&
3248 (DSContext == DeclSpecContext::DSC_class ||
3249 DSContext == DeclSpecContext::DSC_top_level) &&
3250 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3251 Tok.getLocation()) &&
3252 isConstructorDeclarator(/*Unqualified*/ true,
3253 /*DeductionGuide*/ true))
3254 goto DoneWithDeclSpec;
3256 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3257 DiagID, TypeRep, Policy);
3261 DS.SetRangeEnd(Tok.getLocation());
3262 ConsumeToken(); // The identifier
3264 // Objective-C supports type arguments and protocol references
3265 // following an Objective-C object or object pointer
3266 // type. Handle either one of them.
3267 if (Tok.is(tok::less) && getLangOpts().ObjC1) {
3268 SourceLocation NewEndLoc;
3269 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3270 Loc, TypeRep, /*consumeLastToken=*/true,
3272 if (NewTypeRep.isUsable()) {
3273 DS.UpdateTypeRep(NewTypeRep.get());
3274 DS.SetRangeEnd(NewEndLoc);
3278 // Need to support trailing type qualifiers (e.g. "id<p> const").
3279 // If a type specifier follows, it will be diagnosed elsewhere.
3284 case tok::annot_template_id: {
3285 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3286 if (TemplateId->Kind != TNK_Type_template) {
3287 // This template-id does not refer to a type name, so we're
3288 // done with the type-specifiers.
3289 goto DoneWithDeclSpec;
3292 // If we're in a context where the template-id could be a
3293 // constructor name or specialization, check whether this is a
3294 // constructor declaration.
3295 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3296 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3297 isConstructorDeclarator(TemplateId->SS.isEmpty()))
3298 goto DoneWithDeclSpec;
3300 // Turn the template-id annotation token into a type annotation
3301 // token, then try again to parse it as a type-specifier.
3302 AnnotateTemplateIdTokenAsType();
3306 // GNU attributes support.
3307 case tok::kw___attribute:
3308 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3311 // Microsoft declspec support.
3312 case tok::kw___declspec:
3313 ParseMicrosoftDeclSpecs(DS.getAttributes());
3316 // Microsoft single token adornments.
3317 case tok::kw___forceinline: {
3318 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3319 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3320 SourceLocation AttrNameLoc = Tok.getLocation();
3321 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3322 nullptr, 0, AttributeList::AS_Keyword);
3326 case tok::kw___unaligned:
3327 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3331 case tok::kw___sptr:
3332 case tok::kw___uptr:
3333 case tok::kw___ptr64:
3334 case tok::kw___ptr32:
3336 case tok::kw___cdecl:
3337 case tok::kw___stdcall:
3338 case tok::kw___fastcall:
3339 case tok::kw___thiscall:
3340 case tok::kw___regcall:
3341 case tok::kw___vectorcall:
3342 ParseMicrosoftTypeAttributes(DS.getAttributes());
3345 // Borland single token adornments.
3346 case tok::kw___pascal:
3347 ParseBorlandTypeAttributes(DS.getAttributes());
3350 // OpenCL single token adornments.
3351 case tok::kw___kernel:
3352 ParseOpenCLKernelAttributes(DS.getAttributes());
3355 // Nullability type specifiers.
3356 case tok::kw__Nonnull:
3357 case tok::kw__Nullable:
3358 case tok::kw__Null_unspecified:
3359 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3362 // Objective-C 'kindof' types.
3363 case tok::kw___kindof:
3364 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3365 nullptr, 0, AttributeList::AS_Keyword);
3366 (void)ConsumeToken();
3369 // storage-class-specifier
3370 case tok::kw_typedef:
3371 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3372 PrevSpec, DiagID, Policy);
3373 isStorageClass = true;
3375 case tok::kw_extern:
3376 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3377 Diag(Tok, diag::ext_thread_before) << "extern";
3378 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3379 PrevSpec, DiagID, Policy);
3380 isStorageClass = true;
3382 case tok::kw___private_extern__:
3383 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3384 Loc, PrevSpec, DiagID, Policy);
3385 isStorageClass = true;
3387 case tok::kw_static:
3388 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3389 Diag(Tok, diag::ext_thread_before) << "static";
3390 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3391 PrevSpec, DiagID, Policy);
3392 isStorageClass = true;
3395 if (getLangOpts().CPlusPlus11) {
3396 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3397 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3398 PrevSpec, DiagID, Policy);
3400 Diag(Tok, diag::ext_auto_storage_class)
3401 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3403 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3406 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3407 PrevSpec, DiagID, Policy);
3408 isStorageClass = true;
3410 case tok::kw___auto_type:
3411 Diag(Tok, diag::ext_auto_type);
3412 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3415 case tok::kw_register:
3416 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3417 PrevSpec, DiagID, Policy);
3418 isStorageClass = true;
3420 case tok::kw_mutable:
3421 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3422 PrevSpec, DiagID, Policy);
3423 isStorageClass = true;
3425 case tok::kw___thread:
3426 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3428 isStorageClass = true;
3430 case tok::kw_thread_local:
3431 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3434 case tok::kw__Thread_local:
3435 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3436 Loc, PrevSpec, DiagID);
3437 isStorageClass = true;
3440 // function-specifier
3441 case tok::kw_inline:
3442 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3444 case tok::kw_virtual:
3445 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3447 case tok::kw_explicit:
3448 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
3450 case tok::kw__Noreturn:
3451 if (!getLangOpts().C11)
3452 Diag(Loc, diag::ext_c11_noreturn);
3453 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3456 // alignment-specifier
3457 case tok::kw__Alignas:
3458 if (!getLangOpts().C11)
3459 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
3460 ParseAlignmentSpecifier(DS.getAttributes());
3464 case tok::kw_friend:
3465 if (DSContext == DeclSpecContext::DSC_class)
3466 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3468 PrevSpec = ""; // not actually used by the diagnostic
3469 DiagID = diag::err_friend_invalid_in_context;
3475 case tok::kw___module_private__:
3476 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3480 case tok::kw_constexpr:
3481 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3486 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3490 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
3491 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3494 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3497 case tok::kw___int64:
3498 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3501 case tok::kw_signed:
3502 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3505 case tok::kw_unsigned:
3506 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3509 case tok::kw__Complex:
3510 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3513 case tok::kw__Imaginary:
3514 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3518 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3522 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3526 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3529 case tok::kw___int128:
3530 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3534 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3538 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3541 case tok::kw_double:
3542 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3545 case tok::kw__Float16:
3546 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3549 case tok::kw___float128:
3550 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3553 case tok::kw_wchar_t:
3554 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3557 case tok::kw_char16_t:
3558 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3561 case tok::kw_char32_t:
3562 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3567 if (Tok.is(tok::kw_bool) &&
3568 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3569 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3570 PrevSpec = ""; // Not used by the diagnostic.
3571 DiagID = diag::err_bool_redeclaration;
3572 // For better error recovery.
3573 Tok.setKind(tok::identifier);
3576 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3580 case tok::kw__Decimal32:
3581 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3584 case tok::kw__Decimal64:
3585 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3588 case tok::kw__Decimal128:
3589 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3592 case tok::kw___vector:
3593 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3595 case tok::kw___pixel:
3596 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3598 case tok::kw___bool:
3599 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3602 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3603 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3604 // support the "pipe" word as identifier.
3605 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3606 goto DoneWithDeclSpec;
3608 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3610 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
3611 case tok::kw_##ImgType##_t: \
3612 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3615 #include "clang/Basic/OpenCLImageTypes.def"
3616 case tok::kw___unknown_anytype:
3617 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3618 PrevSpec, DiagID, Policy);
3623 case tok::kw_struct:
3624 case tok::kw___interface:
3625 case tok::kw_union: {
3626 tok::TokenKind Kind = Tok.getKind();
3629 // These are attributes following class specifiers.
3630 // To produce better diagnostic, we parse them when
3631 // parsing class specifier.
3632 ParsedAttributesWithRange Attributes(AttrFactory);
3633 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3634 EnteringContext, DSContext, Attributes);
3636 // If there are attributes following class specifier,
3637 // take them over and handle them here.
3638 if (!Attributes.empty()) {
3639 AttrsLastTime = true;
3640 attrs.takeAllFrom(Attributes);
3648 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3653 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3656 case tok::kw_volatile:
3657 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3660 case tok::kw_restrict:
3661 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3665 // C++ typename-specifier:
3666 case tok::kw_typename:
3667 if (TryAnnotateTypeOrScopeToken()) {
3668 DS.SetTypeSpecError();
3669 goto DoneWithDeclSpec;
3671 if (!Tok.is(tok::kw_typename))
3675 // GNU typeof support.
3676 case tok::kw_typeof:
3677 ParseTypeofSpecifier(DS);
3680 case tok::annot_decltype:
3681 ParseDecltypeSpecifier(DS);
3684 case tok::annot_pragma_pack:
3688 case tok::annot_pragma_ms_pragma:
3689 HandlePragmaMSPragma();
3692 case tok::annot_pragma_ms_vtordisp:
3693 HandlePragmaMSVtorDisp();
3696 case tok::annot_pragma_ms_pointers_to_members:
3697 HandlePragmaMSPointersToMembers();
3700 case tok::kw___underlying_type:
3701 ParseUnderlyingTypeSpecifier(DS);
3704 case tok::kw__Atomic:
3706 // If the _Atomic keyword is immediately followed by a left parenthesis,
3707 // it is interpreted as a type specifier (with a type name), not as a
3709 if (NextToken().is(tok::l_paren)) {
3710 ParseAtomicSpecifier(DS);
3713 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3717 // OpenCL qualifiers:
3718 case tok::kw___generic:
3719 // generic address space is introduced only in OpenCL v2.0
3720 // see OpenCL C Spec v2.0 s6.5.5
3721 if (Actions.getLangOpts().OpenCLVersion < 200) {
3722 DiagID = diag::err_opencl_unknown_type_specifier;
3723 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3728 case tok::kw___private:
3729 case tok::kw___global:
3730 case tok::kw___local:
3731 case tok::kw___constant:
3732 case tok::kw___read_only:
3733 case tok::kw___write_only:
3734 case tok::kw___read_write:
3735 ParseOpenCLQualifiers(DS.getAttributes());
3739 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3740 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3741 // but we support it.
3742 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
3743 goto DoneWithDeclSpec;
3745 SourceLocation StartLoc = Tok.getLocation();
3746 SourceLocation EndLoc;
3747 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3748 if (Type.isUsable()) {
3749 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3750 PrevSpec, DiagID, Type.get(),
3751 Actions.getASTContext().getPrintingPolicy()))
3752 Diag(StartLoc, DiagID) << PrevSpec;
3754 DS.SetRangeEnd(EndLoc);
3756 DS.SetTypeSpecError();
3759 // Need to support trailing type qualifiers (e.g. "id<p> const").
3760 // If a type specifier follows, it will be diagnosed elsewhere.
3763 // If the specifier wasn't legal, issue a diagnostic.
3765 assert(PrevSpec && "Method did not return previous specifier!");
3768 if (DiagID == diag::ext_duplicate_declspec)
3770 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
3771 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
3772 const int OpenCLVer = getLangOpts().OpenCLVersion;
3773 std::string VerSpec = llvm::to_string(OpenCLVer / 100) +
3775 llvm::to_string((OpenCLVer % 100) / 10);
3776 Diag(Tok, DiagID) << VerSpec << PrevSpec << isStorageClass;
3778 Diag(Tok, DiagID) << PrevSpec;
3781 DS.SetRangeEnd(Tok.getLocation());
3782 if (DiagID != diag::err_bool_redeclaration)
3785 AttrsLastTime = false;
3789 /// ParseStructDeclaration - Parse a struct declaration without the terminating
3792 /// struct-declaration:
3793 /// [C2x] attributes-specifier-seq[opt]
3794 /// specifier-qualifier-list struct-declarator-list
3795 /// [GNU] __extension__ struct-declaration
3796 /// [GNU] specifier-qualifier-list
3797 /// struct-declarator-list:
3798 /// struct-declarator
3799 /// struct-declarator-list ',' struct-declarator
3800 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3801 /// struct-declarator:
3803 /// [GNU] declarator attributes[opt]
3804 /// declarator[opt] ':' constant-expression
3805 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3807 void Parser::ParseStructDeclaration(
3808 ParsingDeclSpec &DS,
3809 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
3811 if (Tok.is(tok::kw___extension__)) {
3812 // __extension__ silences extension warnings in the subexpression.
3813 ExtensionRAIIObject O(Diags); // Use RAII to do this.
3815 return ParseStructDeclaration(DS, FieldsCallback);
3818 // Parse leading attributes.
3819 ParsedAttributesWithRange Attrs(AttrFactory);
3820 MaybeParseCXX11Attributes(Attrs);
3821 DS.takeAttributesFrom(Attrs);
3823 // Parse the common specifier-qualifiers-list piece.
3824 ParseSpecifierQualifierList(DS);
3826 // If there are no declarators, this is a free-standing declaration
3827 // specifier. Let the actions module cope with it.
3828 if (Tok.is(tok::semi)) {
3829 RecordDecl *AnonRecord = nullptr;
3830 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
3832 assert(!AnonRecord && "Did not expect anonymous struct or union here");
3833 DS.complete(TheDecl);
3837 // Read struct-declarators until we find the semicolon.
3838 bool FirstDeclarator = true;
3839 SourceLocation CommaLoc;
3841 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
3842 DeclaratorInfo.D.setCommaLoc(CommaLoc);
3844 // Attributes are only allowed here on successive declarators.
3845 if (!FirstDeclarator)
3846 MaybeParseGNUAttributes(DeclaratorInfo.D);
3848 /// struct-declarator: declarator
3849 /// struct-declarator: declarator[opt] ':' constant-expression
3850 if (Tok.isNot(tok::colon)) {
3851 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3852 ColonProtectionRAIIObject X(*this);
3853 ParseDeclarator(DeclaratorInfo.D);
3855 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
3857 if (TryConsumeToken(tok::colon)) {
3858 ExprResult Res(ParseConstantExpression());
3859 if (Res.isInvalid())
3860 SkipUntil(tok::semi, StopBeforeMatch);
3862 DeclaratorInfo.BitfieldSize = Res.get();
3865 // If attributes exist after the declarator, parse them.
3866 MaybeParseGNUAttributes(DeclaratorInfo.D);
3868 // We're done with this declarator; invoke the callback.
3869 FieldsCallback(DeclaratorInfo);
3871 // If we don't have a comma, it is either the end of the list (a ';')
3872 // or an error, bail out.
3873 if (!TryConsumeToken(tok::comma, CommaLoc))
3876 FirstDeclarator = false;
3880 /// ParseStructUnionBody
3881 /// struct-contents:
3882 /// struct-declaration-list
3884 /// [GNU] "struct-declaration-list" without terminatoring ';'
3885 /// struct-declaration-list:
3886 /// struct-declaration
3887 /// struct-declaration-list struct-declaration
3888 /// [OBC] '@' 'defs' '(' class-name ')'
3890 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
3891 unsigned TagType, Decl *TagDecl) {
3892 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3893 "parsing struct/union body");
3894 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
3896 BalancedDelimiterTracker T(*this, tok::l_brace);
3897 if (T.consumeOpen())
3900 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
3901 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3903 SmallVector<Decl *, 32> FieldDecls;
3905 // While we still have something to read, read the declarations in the struct.
3906 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3907 Tok.isNot(tok::eof)) {
3908 // Each iteration of this loop reads one struct-declaration.
3910 // Check for extraneous top-level semicolon.
3911 if (Tok.is(tok::semi)) {
3912 ConsumeExtraSemi(InsideStruct, TagType);
3916 // Parse _Static_assert declaration.
3917 if (Tok.is(tok::kw__Static_assert)) {
3918 SourceLocation DeclEnd;
3919 ParseStaticAssertDeclaration(DeclEnd);
3923 if (Tok.is(tok::annot_pragma_pack)) {
3928 if (Tok.is(tok::annot_pragma_align)) {
3929 HandlePragmaAlign();
3933 if (Tok.is(tok::annot_pragma_openmp)) {
3934 // Result can be ignored, because it must be always empty.
3935 AccessSpecifier AS = AS_none;
3936 ParsedAttributesWithRange Attrs(AttrFactory);
3937 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
3941 if (!Tok.is(tok::at)) {
3942 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
3943 // Install the declarator into the current TagDecl.
3945 Actions.ActOnField(getCurScope(), TagDecl,
3946 FD.D.getDeclSpec().getSourceRange().getBegin(),
3947 FD.D, FD.BitfieldSize);
3948 FieldDecls.push_back(Field);
3952 // Parse all the comma separated declarators.
3953 ParsingDeclSpec DS(*this);
3954 ParseStructDeclaration(DS, CFieldCallback);
3955 } else { // Handle @defs
3957 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
3958 Diag(Tok, diag::err_unexpected_at);
3959 SkipUntil(tok::semi);
3963 ExpectAndConsume(tok::l_paren);
3964 if (!Tok.is(tok::identifier)) {
3965 Diag(Tok, diag::err_expected) << tok::identifier;
3966 SkipUntil(tok::semi);
3969 SmallVector<Decl *, 16> Fields;
3970 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
3971 Tok.getIdentifierInfo(), Fields);
3972 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
3974 ExpectAndConsume(tok::r_paren);
3977 if (TryConsumeToken(tok::semi))
3980 if (Tok.is(tok::r_brace)) {
3981 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
3985 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
3986 // Skip to end of block or statement to avoid ext-warning on extra ';'.
3987 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
3988 // If we stopped at a ';', eat it.
3989 TryConsumeToken(tok::semi);
3994 ParsedAttributes attrs(AttrFactory);
3995 // If attributes exist after struct contents, parse them.
3996 MaybeParseGNUAttributes(attrs);
3998 Actions.ActOnFields(getCurScope(),
3999 RecordLoc, TagDecl, FieldDecls,
4000 T.getOpenLocation(), T.getCloseLocation(),
4003 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4006 /// ParseEnumSpecifier
4007 /// enum-specifier: [C99 6.7.2.2]
4008 /// 'enum' identifier[opt] '{' enumerator-list '}'
4009 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4010 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4011 /// '}' attributes[opt]
4012 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4014 /// 'enum' identifier
4015 /// [GNU] 'enum' attributes[opt] identifier
4017 /// [C++11] enum-head '{' enumerator-list[opt] '}'
4018 /// [C++11] enum-head '{' enumerator-list ',' '}'
4020 /// enum-head: [C++11]
4021 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4022 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
4023 /// identifier enum-base[opt]
4025 /// enum-key: [C++11]
4030 /// enum-base: [C++11]
4031 /// ':' type-specifier-seq
4033 /// [C++] elaborated-type-specifier:
4034 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4036 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4037 const ParsedTemplateInfo &TemplateInfo,
4038 AccessSpecifier AS, DeclSpecContext DSC) {
4039 // Parse the tag portion of this.
4040 if (Tok.is(tok::code_completion)) {
4041 // Code completion for an enum name.
4042 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
4043 return cutOffParsing();
4046 // If attributes exist after tag, parse them.
4047 ParsedAttributesWithRange attrs(AttrFactory);
4048 MaybeParseGNUAttributes(attrs);
4049 MaybeParseCXX11Attributes(attrs);
4050 MaybeParseMicrosoftDeclSpecs(attrs);
4052 SourceLocation ScopedEnumKWLoc;
4053 bool IsScopedUsingClassTag = false;
4055 // In C++11, recognize 'enum class' and 'enum struct'.
4056 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4057 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4058 : diag::ext_scoped_enum);
4059 IsScopedUsingClassTag = Tok.is(tok::kw_class);
4060 ScopedEnumKWLoc = ConsumeToken();
4062 // Attributes are not allowed between these keywords. Diagnose,
4063 // but then just treat them like they appeared in the right place.
4064 ProhibitAttributes(attrs);
4066 // They are allowed afterwards, though.
4067 MaybeParseGNUAttributes(attrs);
4068 MaybeParseCXX11Attributes(attrs);
4069 MaybeParseMicrosoftDeclSpecs(attrs);
4072 // C++11 [temp.explicit]p12:
4073 // The usual access controls do not apply to names used to specify
4074 // explicit instantiations.
4075 // We extend this to also cover explicit specializations. Note that
4076 // we don't suppress if this turns out to be an elaborated type
4078 bool shouldDelayDiagsInTag =
4079 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4080 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4081 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4083 // Enum definitions should not be parsed in a trailing-return-type.
4084 bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
4086 bool AllowFixedUnderlyingType = AllowDeclaration &&
4087 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
4088 getLangOpts().ObjC2);
4090 CXXScopeSpec &SS = DS.getTypeSpecScope();
4091 if (getLangOpts().CPlusPlus) {
4092 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4093 // if a fixed underlying type is allowed.
4094 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
4097 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
4098 /*EnteringContext=*/true))
4101 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4102 Diag(Tok, diag::err_expected) << tok::identifier;
4103 if (Tok.isNot(tok::l_brace)) {
4104 // Has no name and is not a definition.
4105 // Skip the rest of this declarator, up until the comma or semicolon.
4106 SkipUntil(tok::comma, StopAtSemi);
4114 // Must have either 'enum name' or 'enum {...}'.
4115 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4116 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
4117 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4119 // Skip the rest of this declarator, up until the comma or semicolon.
4120 SkipUntil(tok::comma, StopAtSemi);
4124 // If an identifier is present, consume and remember it.
4125 IdentifierInfo *Name = nullptr;
4126 SourceLocation NameLoc;
4127 if (Tok.is(tok::identifier)) {
4128 Name = Tok.getIdentifierInfo();
4129 NameLoc = ConsumeToken();
4132 if (!Name && ScopedEnumKWLoc.isValid()) {
4133 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4134 // declaration of a scoped enumeration.
4135 Diag(Tok, diag::err_scoped_enum_missing_identifier);
4136 ScopedEnumKWLoc = SourceLocation();
4137 IsScopedUsingClassTag = false;
4140 // Okay, end the suppression area. We'll decide whether to emit the
4141 // diagnostics in a second.
4142 if (shouldDelayDiagsInTag)
4143 diagsFromTag.done();
4145 TypeResult BaseType;
4147 // Parse the fixed underlying type.
4148 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4149 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
4150 bool PossibleBitfield = false;
4151 if (CanBeBitfield) {
4152 // If we're in class scope, this can either be an enum declaration with
4153 // an underlying type, or a declaration of a bitfield member. We try to
4154 // use a simple disambiguation scheme first to catch the common cases
4155 // (integer literal, sizeof); if it's still ambiguous, we then consider
4156 // anything that's a simple-type-specifier followed by '(' as an
4157 // expression. This suffices because function types are not valid
4158 // underlying types anyway.
4159 EnterExpressionEvaluationContext Unevaluated(
4160 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4161 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
4162 // If the next token starts an expression, we know we're parsing a
4163 // bit-field. This is the common case.
4164 if (TPR == TPResult::True)
4165 PossibleBitfield = true;
4166 // If the next token starts a type-specifier-seq, it may be either a
4167 // a fixed underlying type or the start of a function-style cast in C++;
4168 // lookahead one more token to see if it's obvious that we have a
4169 // fixed underlying type.
4170 else if (TPR == TPResult::False &&
4171 GetLookAheadToken(2).getKind() == tok::semi) {
4175 // We have the start of a type-specifier-seq, so we have to perform
4176 // tentative parsing to determine whether we have an expression or a
4178 TentativeParsingAction TPA(*this);
4183 // If we see a type specifier followed by an open-brace, we have an
4184 // ambiguity between an underlying type and a C++11 braced
4185 // function-style cast. Resolve this by always treating it as an
4187 // FIXME: The standard is not entirely clear on how to disambiguate in
4189 if ((getLangOpts().CPlusPlus &&
4190 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
4191 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
4192 // We'll parse this as a bitfield later.
4193 PossibleBitfield = true;
4196 // We have a type-specifier-seq.
4205 if (!PossibleBitfield) {
4207 BaseType = ParseTypeName(&Range);
4209 if (getLangOpts().CPlusPlus11) {
4210 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4211 } else if (!getLangOpts().ObjC2) {
4212 if (getLangOpts().CPlusPlus)
4213 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
4215 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
4220 // There are four options here. If we have 'friend enum foo;' then this is a
4221 // friend declaration, and cannot have an accompanying definition. If we have
4222 // 'enum foo;', then this is a forward declaration. If we have
4223 // 'enum foo {...' then this is a definition. Otherwise we have something
4224 // like 'enum foo xyz', a reference.
4226 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4227 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4228 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4230 Sema::TagUseKind TUK;
4231 if (!AllowDeclaration) {
4232 TUK = Sema::TUK_Reference;
4233 } else if (Tok.is(tok::l_brace)) {
4234 if (DS.isFriendSpecified()) {
4235 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4236 << SourceRange(DS.getFriendSpecLoc());
4238 SkipUntil(tok::r_brace, StopAtSemi);
4239 TUK = Sema::TUK_Friend;
4241 TUK = Sema::TUK_Definition;
4243 } else if (!isTypeSpecifier(DSC) &&
4244 (Tok.is(tok::semi) ||
4245 (Tok.isAtStartOfLine() &&
4246 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4247 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4248 if (Tok.isNot(tok::semi)) {
4249 // A semicolon was missing after this declaration. Diagnose and recover.
4250 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4252 Tok.setKind(tok::semi);
4255 TUK = Sema::TUK_Reference;
4258 // If this is an elaborated type specifier, and we delayed
4259 // diagnostics before, just merge them into the current pool.
4260 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4261 diagsFromTag.redelay();
4264 MultiTemplateParamsArg TParams;
4265 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4266 TUK != Sema::TUK_Reference) {
4267 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4268 // Skip the rest of this declarator, up until the comma or semicolon.
4269 Diag(Tok, diag::err_enum_template);
4270 SkipUntil(tok::comma, StopAtSemi);
4274 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4275 // Enumerations can't be explicitly instantiated.
4276 DS.SetTypeSpecError();
4277 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4281 assert(TemplateInfo.TemplateParams && "no template parameters");
4282 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4283 TemplateInfo.TemplateParams->size());
4286 if (TUK == Sema::TUK_Reference)
4287 ProhibitAttributes(attrs);
4289 if (!Name && TUK != Sema::TUK_Definition) {
4290 Diag(Tok, diag::err_enumerator_unnamed_no_def);
4292 // Skip the rest of this declarator, up until the comma or semicolon.
4293 SkipUntil(tok::comma, StopAtSemi);
4297 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4299 Sema::SkipBodyInfo SkipBody;
4300 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4301 NextToken().is(tok::identifier))
4302 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4303 NextToken().getIdentifierInfo(),
4304 NextToken().getLocation());
4307 bool IsDependent = false;
4308 const char *PrevSpec = nullptr;
4310 Decl *TagDecl = Actions.ActOnTag(
4311 getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
4312 attrs.getList(), AS, DS.getModulePrivateSpecLoc(), TParams, Owned,
4313 IsDependent, ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
4314 DSC == DeclSpecContext::DSC_type_specifier,
4315 DSC == DeclSpecContext::DSC_template_param ||
4316 DSC == DeclSpecContext::DSC_template_type_arg,
4319 if (SkipBody.ShouldSkip) {
4320 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4322 BalancedDelimiterTracker T(*this, tok::l_brace);
4326 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4327 NameLoc.isValid() ? NameLoc : StartLoc,
4328 PrevSpec, DiagID, TagDecl, Owned,
4329 Actions.getASTContext().getPrintingPolicy()))
4330 Diag(StartLoc, DiagID) << PrevSpec;
4335 // This enum has a dependent nested-name-specifier. Handle it as a
4338 DS.SetTypeSpecError();
4339 Diag(Tok, diag::err_expected_type_name_after_typename);
4343 TypeResult Type = Actions.ActOnDependentTag(
4344 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4345 if (Type.isInvalid()) {
4346 DS.SetTypeSpecError();
4350 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4351 NameLoc.isValid() ? NameLoc : StartLoc,
4352 PrevSpec, DiagID, Type.get(),
4353 Actions.getASTContext().getPrintingPolicy()))
4354 Diag(StartLoc, DiagID) << PrevSpec;
4360 // The action failed to produce an enumeration tag. If this is a
4361 // definition, consume the entire definition.
4362 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4364 SkipUntil(tok::r_brace, StopAtSemi);
4367 DS.SetTypeSpecError();
4371 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4372 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4373 ParseEnumBody(StartLoc, D);
4374 if (SkipBody.CheckSameAsPrevious &&
4375 !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4376 DS.SetTypeSpecError();
4381 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4382 NameLoc.isValid() ? NameLoc : StartLoc,
4383 PrevSpec, DiagID, TagDecl, Owned,
4384 Actions.getASTContext().getPrintingPolicy()))
4385 Diag(StartLoc, DiagID) << PrevSpec;
4388 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4389 /// enumerator-list:
4391 /// enumerator-list ',' enumerator
4393 /// enumeration-constant attributes[opt]
4394 /// enumeration-constant attributes[opt] '=' constant-expression
4395 /// enumeration-constant:
4398 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4399 // Enter the scope of the enum body and start the definition.
4400 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4401 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4403 BalancedDelimiterTracker T(*this, tok::l_brace);
4406 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4407 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4408 Diag(Tok, diag::err_empty_enum);
4410 SmallVector<Decl *, 32> EnumConstantDecls;
4411 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4413 Decl *LastEnumConstDecl = nullptr;
4415 // Parse the enumerator-list.
4416 while (Tok.isNot(tok::r_brace)) {
4417 // Parse enumerator. If failed, try skipping till the start of the next
4418 // enumerator definition.
4419 if (Tok.isNot(tok::identifier)) {
4420 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4421 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4422 TryConsumeToken(tok::comma))
4426 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4427 SourceLocation IdentLoc = ConsumeToken();
4429 // If attributes exist after the enumerator, parse them.
4430 ParsedAttributesWithRange attrs(AttrFactory);
4431 MaybeParseGNUAttributes(attrs);
4432 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4433 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4434 if (getLangOpts().CPlusPlus)
4435 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4436 ? diag::warn_cxx14_compat_ns_enum_attribute
4437 : diag::ext_ns_enum_attribute)
4438 << 1 /*enumerator*/;
4439 ParseCXX11Attributes(attrs);
4442 SourceLocation EqualLoc;
4443 ExprResult AssignedVal;
4444 EnumAvailabilityDiags.emplace_back(*this);
4446 if (TryConsumeToken(tok::equal, EqualLoc)) {
4447 AssignedVal = ParseConstantExpression();
4448 if (AssignedVal.isInvalid())
4449 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4452 // Install the enumerator constant into EnumDecl.
4453 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
4454 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident,
4455 attrs.getList(), EqualLoc, AssignedVal.get());
4456 EnumAvailabilityDiags.back().done();
4458 EnumConstantDecls.push_back(EnumConstDecl);
4459 LastEnumConstDecl = EnumConstDecl;
4461 if (Tok.is(tok::identifier)) {
4462 // We're missing a comma between enumerators.
4463 SourceLocation Loc = getEndOfPreviousToken();
4464 Diag(Loc, diag::err_enumerator_list_missing_comma)
4465 << FixItHint::CreateInsertion(Loc, ", ");
4469 // Emumerator definition must be finished, only comma or r_brace are
4471 SourceLocation CommaLoc;
4472 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4473 if (EqualLoc.isValid())
4474 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4477 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4478 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4479 if (TryConsumeToken(tok::comma, CommaLoc))
4486 // If comma is followed by r_brace, emit appropriate warning.
4487 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4488 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4489 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4490 diag::ext_enumerator_list_comma_cxx :
4491 diag::ext_enumerator_list_comma_c)
4492 << FixItHint::CreateRemoval(CommaLoc);
4493 else if (getLangOpts().CPlusPlus11)
4494 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4495 << FixItHint::CreateRemoval(CommaLoc);
4503 // If attributes exist after the identifier list, parse them.
4504 ParsedAttributes attrs(AttrFactory);
4505 MaybeParseGNUAttributes(attrs);
4507 Actions.ActOnEnumBody(StartLoc, T.getRange(),
4508 EnumDecl, EnumConstantDecls,
4512 // Now handle enum constant availability diagnostics.
4513 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4514 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4515 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4516 EnumAvailabilityDiags[i].redelay();
4517 PD.complete(EnumConstantDecls[i]);
4521 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4523 // The next token must be valid after an enum definition. If not, a ';'
4524 // was probably forgotten.
4525 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4526 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4527 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4528 // Push this token back into the preprocessor and change our current token
4529 // to ';' so that the rest of the code recovers as though there were an
4530 // ';' after the definition.
4532 Tok.setKind(tok::semi);
4536 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4537 /// is definitely a type-specifier. Return false if it isn't part of a type
4538 /// specifier or if we're not sure.
4539 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4540 switch (Tok.getKind()) {
4541 default: return false;
4545 case tok::kw___int64:
4546 case tok::kw___int128:
4547 case tok::kw_signed:
4548 case tok::kw_unsigned:
4549 case tok::kw__Complex:
4550 case tok::kw__Imaginary:
4553 case tok::kw_wchar_t:
4554 case tok::kw_char16_t:
4555 case tok::kw_char32_t:
4559 case tok::kw_double:
4560 case tok::kw__Float16:
4561 case tok::kw___float128:
4564 case tok::kw__Decimal32:
4565 case tok::kw__Decimal64:
4566 case tok::kw__Decimal128:
4567 case tok::kw___vector:
4568 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4569 #include "clang/Basic/OpenCLImageTypes.def"
4571 // struct-or-union-specifier (C99) or class-specifier (C++)
4573 case tok::kw_struct:
4574 case tok::kw___interface:
4580 case tok::annot_typename:
4585 /// isTypeSpecifierQualifier - Return true if the current token could be the
4586 /// start of a specifier-qualifier-list.
4587 bool Parser::isTypeSpecifierQualifier() {
4588 switch (Tok.getKind()) {
4589 default: return false;
4591 case tok::identifier: // foo::bar
4592 if (TryAltiVecVectorToken())
4595 case tok::kw_typename: // typename T::type
4596 // Annotate typenames and C++ scope specifiers. If we get one, just
4597 // recurse to handle whatever we get.
4598 if (TryAnnotateTypeOrScopeToken())
4600 if (Tok.is(tok::identifier))
4602 return isTypeSpecifierQualifier();
4604 case tok::coloncolon: // ::foo::bar
4605 if (NextToken().is(tok::kw_new) || // ::new
4606 NextToken().is(tok::kw_delete)) // ::delete
4609 if (TryAnnotateTypeOrScopeToken())
4611 return isTypeSpecifierQualifier();
4613 // GNU attributes support.
4614 case tok::kw___attribute:
4615 // GNU typeof support.
4616 case tok::kw_typeof:
4621 case tok::kw___int64:
4622 case tok::kw___int128:
4623 case tok::kw_signed:
4624 case tok::kw_unsigned:
4625 case tok::kw__Complex:
4626 case tok::kw__Imaginary:
4629 case tok::kw_wchar_t:
4630 case tok::kw_char16_t:
4631 case tok::kw_char32_t:
4635 case tok::kw_double:
4636 case tok::kw__Float16:
4637 case tok::kw___float128:
4640 case tok::kw__Decimal32:
4641 case tok::kw__Decimal64:
4642 case tok::kw__Decimal128:
4643 case tok::kw___vector:
4644 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4645 #include "clang/Basic/OpenCLImageTypes.def"
4647 // struct-or-union-specifier (C99) or class-specifier (C++)
4649 case tok::kw_struct:
4650 case tok::kw___interface:
4657 case tok::kw_volatile:
4658 case tok::kw_restrict:
4660 // Debugger support.
4661 case tok::kw___unknown_anytype:
4664 case tok::annot_typename:
4667 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4669 return getLangOpts().ObjC1;
4671 case tok::kw___cdecl:
4672 case tok::kw___stdcall:
4673 case tok::kw___fastcall:
4674 case tok::kw___thiscall:
4675 case tok::kw___regcall:
4676 case tok::kw___vectorcall:
4678 case tok::kw___ptr64:
4679 case tok::kw___ptr32:
4680 case tok::kw___pascal:
4681 case tok::kw___unaligned:
4683 case tok::kw__Nonnull:
4684 case tok::kw__Nullable:
4685 case tok::kw__Null_unspecified:
4687 case tok::kw___kindof:
4689 case tok::kw___private:
4690 case tok::kw___local:
4691 case tok::kw___global:
4692 case tok::kw___constant:
4693 case tok::kw___generic:
4694 case tok::kw___read_only:
4695 case tok::kw___read_write:
4696 case tok::kw___write_only:
4701 case tok::kw__Atomic:
4706 /// isDeclarationSpecifier() - Return true if the current token is part of a
4707 /// declaration specifier.
4709 /// \param DisambiguatingWithExpression True to indicate that the purpose of
4710 /// this check is to disambiguate between an expression and a declaration.
4711 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4712 switch (Tok.getKind()) {
4713 default: return false;
4716 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4718 case tok::identifier: // foo::bar
4719 // Unfortunate hack to support "Class.factoryMethod" notation.
4720 if (getLangOpts().ObjC1 && NextToken().is(tok::period))
4722 if (TryAltiVecVectorToken())
4725 case tok::kw_decltype: // decltype(T())::type
4726 case tok::kw_typename: // typename T::type
4727 // Annotate typenames and C++ scope specifiers. If we get one, just
4728 // recurse to handle whatever we get.
4729 if (TryAnnotateTypeOrScopeToken())
4731 if (Tok.is(tok::identifier))
4734 // If we're in Objective-C and we have an Objective-C class type followed
4735 // by an identifier and then either ':' or ']', in a place where an
4736 // expression is permitted, then this is probably a class message send
4737 // missing the initial '['. In this case, we won't consider this to be
4738 // the start of a declaration.
4739 if (DisambiguatingWithExpression &&
4740 isStartOfObjCClassMessageMissingOpenBracket())
4743 return isDeclarationSpecifier();
4745 case tok::coloncolon: // ::foo::bar
4746 if (NextToken().is(tok::kw_new) || // ::new
4747 NextToken().is(tok::kw_delete)) // ::delete
4750 // Annotate typenames and C++ scope specifiers. If we get one, just
4751 // recurse to handle whatever we get.
4752 if (TryAnnotateTypeOrScopeToken())
4754 return isDeclarationSpecifier();
4756 // storage-class-specifier
4757 case tok::kw_typedef:
4758 case tok::kw_extern:
4759 case tok::kw___private_extern__:
4760 case tok::kw_static:
4762 case tok::kw___auto_type:
4763 case tok::kw_register:
4764 case tok::kw___thread:
4765 case tok::kw_thread_local:
4766 case tok::kw__Thread_local:
4769 case tok::kw___module_private__:
4772 case tok::kw___unknown_anytype:
4777 case tok::kw___int64:
4778 case tok::kw___int128:
4779 case tok::kw_signed:
4780 case tok::kw_unsigned:
4781 case tok::kw__Complex:
4782 case tok::kw__Imaginary:
4785 case tok::kw_wchar_t:
4786 case tok::kw_char16_t:
4787 case tok::kw_char32_t:
4792 case tok::kw_double:
4793 case tok::kw__Float16:
4794 case tok::kw___float128:
4797 case tok::kw__Decimal32:
4798 case tok::kw__Decimal64:
4799 case tok::kw__Decimal128:
4800 case tok::kw___vector:
4802 // struct-or-union-specifier (C99) or class-specifier (C++)
4804 case tok::kw_struct:
4806 case tok::kw___interface:
4812 case tok::kw_volatile:
4813 case tok::kw_restrict:
4815 // function-specifier
4816 case tok::kw_inline:
4817 case tok::kw_virtual:
4818 case tok::kw_explicit:
4819 case tok::kw__Noreturn:
4821 // alignment-specifier
4822 case tok::kw__Alignas:
4825 case tok::kw_friend:
4827 // static_assert-declaration
4828 case tok::kw__Static_assert:
4830 // GNU typeof support.
4831 case tok::kw_typeof:
4834 case tok::kw___attribute:
4836 // C++11 decltype and constexpr.
4837 case tok::annot_decltype:
4838 case tok::kw_constexpr:
4841 case tok::kw__Atomic:
4844 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4846 return getLangOpts().ObjC1;
4849 case tok::annot_typename:
4850 return !DisambiguatingWithExpression ||
4851 !isStartOfObjCClassMessageMissingOpenBracket();
4853 case tok::kw___declspec:
4854 case tok::kw___cdecl:
4855 case tok::kw___stdcall:
4856 case tok::kw___fastcall:
4857 case tok::kw___thiscall:
4858 case tok::kw___regcall:
4859 case tok::kw___vectorcall:
4861 case tok::kw___sptr:
4862 case tok::kw___uptr:
4863 case tok::kw___ptr64:
4864 case tok::kw___ptr32:
4865 case tok::kw___forceinline:
4866 case tok::kw___pascal:
4867 case tok::kw___unaligned:
4869 case tok::kw__Nonnull:
4870 case tok::kw__Nullable:
4871 case tok::kw__Null_unspecified:
4873 case tok::kw___kindof:
4875 case tok::kw___private:
4876 case tok::kw___local:
4877 case tok::kw___global:
4878 case tok::kw___constant:
4879 case tok::kw___generic:
4880 case tok::kw___read_only:
4881 case tok::kw___read_write:
4882 case tok::kw___write_only:
4883 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4884 #include "clang/Basic/OpenCLImageTypes.def"
4890 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
4891 TentativeParsingAction TPA(*this);
4893 // Parse the C++ scope specifier.
4895 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
4896 /*EnteringContext=*/true)) {
4901 // Parse the constructor name.
4902 if (Tok.is(tok::identifier)) {
4903 // We already know that we have a constructor name; just consume
4906 } else if (Tok.is(tok::annot_template_id)) {
4907 ConsumeAnnotationToken();
4913 // There may be attributes here, appertaining to the constructor name or type
4914 // we just stepped past.
4915 SkipCXX11Attributes();
4917 // Current class name must be followed by a left parenthesis.
4918 if (Tok.isNot(tok::l_paren)) {
4924 // A right parenthesis, or ellipsis followed by a right parenthesis signals
4925 // that we have a constructor.
4926 if (Tok.is(tok::r_paren) ||
4927 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
4932 // A C++11 attribute here signals that we have a constructor, and is an
4933 // attribute on the first constructor parameter.
4934 if (getLangOpts().CPlusPlus11 &&
4935 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
4936 /*OuterMightBeMessageSend*/ true)) {
4941 // If we need to, enter the specified scope.
4942 DeclaratorScopeObj DeclScopeObj(*this, SS);
4943 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
4944 DeclScopeObj.EnterDeclaratorScope();
4946 // Optionally skip Microsoft attributes.
4947 ParsedAttributes Attrs(AttrFactory);
4948 MaybeParseMicrosoftAttributes(Attrs);
4950 // Check whether the next token(s) are part of a declaration
4951 // specifier, in which case we have the start of a parameter and,
4952 // therefore, we know that this is a constructor.
4953 bool IsConstructor = false;
4954 if (isDeclarationSpecifier())
4955 IsConstructor = true;
4956 else if (Tok.is(tok::identifier) ||
4957 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
4958 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
4959 // This might be a parenthesized member name, but is more likely to
4960 // be a constructor declaration with an invalid argument type. Keep
4962 if (Tok.is(tok::annot_cxxscope))
4963 ConsumeAnnotationToken();
4966 // If this is not a constructor, we must be parsing a declarator,
4967 // which must have one of the following syntactic forms (see the
4968 // grammar extract at the start of ParseDirectDeclarator):
4969 switch (Tok.getKind()) {
4974 // C(X [ [attribute]]);
4975 case tok::coloncolon:
4978 // Assume this isn't a constructor, rather than assuming it's a
4979 // constructor with an unnamed parameter of an ill-formed type.
4985 // Skip past the right-paren and any following attributes to get to
4986 // the function body or trailing-return-type.
4988 SkipCXX11Attributes();
4990 if (DeductionGuide) {
4991 // C(X) -> ... is a deduction guide.
4992 IsConstructor = Tok.is(tok::arrow);
4995 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
4996 // Assume these were meant to be constructors:
4997 // C(X) : (the name of a bit-field cannot be parenthesized).
4998 // C(X) try (this is otherwise ill-formed).
4999 IsConstructor = true;
5001 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
5002 // If we have a constructor name within the class definition,
5003 // assume these were meant to be constructors:
5006 // ... because otherwise we would be declaring a non-static data
5007 // member that is ill-formed because it's of the same type as its
5008 // surrounding class.
5010 // FIXME: We can actually do this whether or not the name is qualified,
5011 // because if it is qualified in this context it must be being used as
5012 // a constructor name.
5013 // currently, so we're somewhat conservative here.
5014 IsConstructor = IsUnqualified;
5019 IsConstructor = true;
5025 return IsConstructor;
5028 /// ParseTypeQualifierListOpt
5029 /// type-qualifier-list: [C99 6.7.5]
5031 /// [vendor] attributes
5032 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5033 /// type-qualifier-list type-qualifier
5034 /// [vendor] type-qualifier-list attributes
5035 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5036 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
5037 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
5038 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5039 /// AttrRequirements bitmask values.
5040 void Parser::ParseTypeQualifierListOpt(
5041 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5042 bool IdentifierRequired,
5043 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
5044 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
5045 isCXX11AttributeSpecifier()) {
5046 ParsedAttributesWithRange attrs(AttrFactory);
5047 ParseCXX11Attributes(attrs);
5048 DS.takeAttributesFrom(attrs);
5051 SourceLocation EndLoc;
5054 bool isInvalid = false;
5055 const char *PrevSpec = nullptr;
5056 unsigned DiagID = 0;
5057 SourceLocation Loc = Tok.getLocation();
5059 switch (Tok.getKind()) {
5060 case tok::code_completion:
5061 if (CodeCompletionHandler)
5062 (*CodeCompletionHandler)();
5064 Actions.CodeCompleteTypeQualifiers(DS);
5065 return cutOffParsing();
5068 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
5071 case tok::kw_volatile:
5072 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5075 case tok::kw_restrict:
5076 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5079 case tok::kw__Atomic:
5081 goto DoneWithTypeQuals;
5082 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5086 // OpenCL qualifiers:
5087 case tok::kw___private:
5088 case tok::kw___global:
5089 case tok::kw___local:
5090 case tok::kw___constant:
5091 case tok::kw___generic:
5092 case tok::kw___read_only:
5093 case tok::kw___write_only:
5094 case tok::kw___read_write:
5095 ParseOpenCLQualifiers(DS.getAttributes());
5098 case tok::kw___unaligned:
5099 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5102 case tok::kw___uptr:
5103 // GNU libc headers in C mode use '__uptr' as an identifer which conflicts
5104 // with the MS modifier keyword.
5105 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
5106 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5107 if (TryKeywordIdentFallback(false))
5111 case tok::kw___sptr:
5113 case tok::kw___ptr64:
5114 case tok::kw___ptr32:
5115 case tok::kw___cdecl:
5116 case tok::kw___stdcall:
5117 case tok::kw___fastcall:
5118 case tok::kw___thiscall:
5119 case tok::kw___regcall:
5120 case tok::kw___vectorcall:
5121 if (AttrReqs & AR_DeclspecAttributesParsed) {
5122 ParseMicrosoftTypeAttributes(DS.getAttributes());
5125 goto DoneWithTypeQuals;
5126 case tok::kw___pascal:
5127 if (AttrReqs & AR_VendorAttributesParsed) {
5128 ParseBorlandTypeAttributes(DS.getAttributes());
5131 goto DoneWithTypeQuals;
5133 // Nullability type specifiers.
5134 case tok::kw__Nonnull:
5135 case tok::kw__Nullable:
5136 case tok::kw__Null_unspecified:
5137 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5140 // Objective-C 'kindof' types.
5141 case tok::kw___kindof:
5142 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
5143 nullptr, 0, AttributeList::AS_Keyword);
5144 (void)ConsumeToken();
5147 case tok::kw___attribute:
5148 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5149 // When GNU attributes are expressly forbidden, diagnose their usage.
5150 Diag(Tok, diag::err_attributes_not_allowed);
5152 // Parse the attributes even if they are rejected to ensure that error
5153 // recovery is graceful.
5154 if (AttrReqs & AR_GNUAttributesParsed ||
5155 AttrReqs & AR_GNUAttributesParsedAndRejected) {
5156 ParseGNUAttributes(DS.getAttributes());
5157 continue; // do *not* consume the next token!
5159 // otherwise, FALL THROUGH!
5163 // If this is not a type-qualifier token, we're done reading type
5164 // qualifiers. First verify that DeclSpec's are consistent.
5165 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
5166 if (EndLoc.isValid())
5167 DS.SetRangeEnd(EndLoc);
5171 // If the specifier combination wasn't legal, issue a diagnostic.
5173 assert(PrevSpec && "Method did not return previous specifier!");
5174 Diag(Tok, DiagID) << PrevSpec;
5176 EndLoc = ConsumeToken();
5180 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
5182 void Parser::ParseDeclarator(Declarator &D) {
5183 /// This implements the 'declarator' production in the C grammar, then checks
5184 /// for well-formedness and issues diagnostics.
5185 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5188 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
5189 DeclaratorContext TheContext) {
5190 if (Kind == tok::star || Kind == tok::caret)
5193 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
5196 if (!Lang.CPlusPlus)
5199 if (Kind == tok::amp)
5202 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5203 // But we must not parse them in conversion-type-ids and new-type-ids, since
5204 // those can be legitimately followed by a && operator.
5205 // (The same thing can in theory happen after a trailing-return-type, but
5206 // since those are a C++11 feature, there is no rejects-valid issue there.)
5207 if (Kind == tok::ampamp)
5208 return Lang.CPlusPlus11 ||
5209 (TheContext != DeclaratorContext::ConversionIdContext &&
5210 TheContext != DeclaratorContext::CXXNewContext);
5215 // Indicates whether the given declarator is a pipe declarator.
5216 static bool isPipeDeclerator(const Declarator &D) {
5217 const unsigned NumTypes = D.getNumTypeObjects();
5219 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5220 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5226 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5227 /// is parsed by the function passed to it. Pass null, and the direct-declarator
5228 /// isn't parsed at all, making this function effectively parse the C++
5229 /// ptr-operator production.
5231 /// If the grammar of this construct is extended, matching changes must also be
5232 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5233 /// isConstructorDeclarator.
5235 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5236 /// [C] pointer[opt] direct-declarator
5237 /// [C++] direct-declarator
5238 /// [C++] ptr-operator declarator
5240 /// pointer: [C99 6.7.5]
5241 /// '*' type-qualifier-list[opt]
5242 /// '*' type-qualifier-list[opt] pointer
5245 /// '*' cv-qualifier-seq[opt]
5248 /// [GNU] '&' restrict[opt] attributes[opt]
5249 /// [GNU?] '&&' restrict[opt] attributes[opt]
5250 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
5251 void Parser::ParseDeclaratorInternal(Declarator &D,
5252 DirectDeclParseFunction DirectDeclParser) {
5253 if (Diags.hasAllExtensionsSilenced())
5256 // C++ member pointers start with a '::' or a nested-name.
5257 // Member pointers get special handling, since there's no place for the
5258 // scope spec in the generic path below.
5259 if (getLangOpts().CPlusPlus &&
5260 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
5261 (Tok.is(tok::identifier) &&
5262 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
5263 Tok.is(tok::annot_cxxscope))) {
5264 bool EnteringContext =
5265 D.getContext() == DeclaratorContext::FileContext ||
5266 D.getContext() == DeclaratorContext::MemberContext;
5268 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
5270 if (SS.isNotEmpty()) {
5271 if (Tok.isNot(tok::star)) {
5272 // The scope spec really belongs to the direct-declarator.
5273 if (D.mayHaveIdentifier())
5274 D.getCXXScopeSpec() = SS;
5276 AnnotateScopeToken(SS, true);
5278 if (DirectDeclParser)
5279 (this->*DirectDeclParser)(D);
5283 SourceLocation Loc = ConsumeToken();
5285 DeclSpec DS(AttrFactory);
5286 ParseTypeQualifierListOpt(DS);
5287 D.ExtendWithDeclSpec(DS);
5289 // Recurse to parse whatever is left.
5290 ParseDeclaratorInternal(D, DirectDeclParser);
5292 // Sema will have to catch (syntactically invalid) pointers into global
5293 // scope. It has to catch pointers into namespace scope anyway.
5294 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
5297 /* Don't replace range end. */SourceLocation());
5302 tok::TokenKind Kind = Tok.getKind();
5304 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
5305 DeclSpec DS(AttrFactory);
5306 ParseTypeQualifierListOpt(DS);
5309 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
5310 DS.getAttributes(), SourceLocation());
5313 // Not a pointer, C++ reference, or block.
5314 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
5315 if (DirectDeclParser)
5316 (this->*DirectDeclParser)(D);
5320 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5321 // '&&' -> rvalue reference
5322 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
5325 if (Kind == tok::star || Kind == tok::caret) {
5327 DeclSpec DS(AttrFactory);
5329 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5330 // C++11 attributes are allowed.
5331 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
5332 ((D.getContext() != DeclaratorContext::CXXNewContext)
5333 ? AR_GNUAttributesParsed
5334 : AR_GNUAttributesParsedAndRejected);
5335 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
5336 D.ExtendWithDeclSpec(DS);
5338 // Recursively parse the declarator.
5339 ParseDeclaratorInternal(D, DirectDeclParser);
5340 if (Kind == tok::star)
5341 // Remember that we parsed a pointer type, and remember the type-quals.
5342 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
5343 DS.getConstSpecLoc(),
5344 DS.getVolatileSpecLoc(),
5345 DS.getRestrictSpecLoc(),
5346 DS.getAtomicSpecLoc(),
5347 DS.getUnalignedSpecLoc()),
5351 // Remember that we parsed a Block type, and remember the type-quals.
5352 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
5358 DeclSpec DS(AttrFactory);
5360 // Complain about rvalue references in C++03, but then go on and build
5362 if (Kind == tok::ampamp)
5363 Diag(Loc, getLangOpts().CPlusPlus11 ?
5364 diag::warn_cxx98_compat_rvalue_reference :
5365 diag::ext_rvalue_reference);
5367 // GNU-style and C++11 attributes are allowed here, as is restrict.
5368 ParseTypeQualifierListOpt(DS);
5369 D.ExtendWithDeclSpec(DS);
5371 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5372 // cv-qualifiers are introduced through the use of a typedef or of a
5373 // template type argument, in which case the cv-qualifiers are ignored.
5374 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5375 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5376 Diag(DS.getConstSpecLoc(),
5377 diag::err_invalid_reference_qualifier_application) << "const";
5378 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5379 Diag(DS.getVolatileSpecLoc(),
5380 diag::err_invalid_reference_qualifier_application) << "volatile";
5381 // 'restrict' is permitted as an extension.
5382 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5383 Diag(DS.getAtomicSpecLoc(),
5384 diag::err_invalid_reference_qualifier_application) << "_Atomic";
5387 // Recursively parse the declarator.
5388 ParseDeclaratorInternal(D, DirectDeclParser);
5390 if (D.getNumTypeObjects() > 0) {
5391 // C++ [dcl.ref]p4: There shall be no references to references.
5392 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5393 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5394 if (const IdentifierInfo *II = D.getIdentifier())
5395 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5398 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5401 // Once we've complained about the reference-to-reference, we
5402 // can go ahead and build the (technically ill-formed)
5403 // declarator: reference collapsing will take care of it.
5407 // Remember that we parsed a reference type.
5408 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
5415 // When correcting from misplaced brackets before the identifier, the location
5416 // is saved inside the declarator so that other diagnostic messages can use
5417 // them. This extracts and returns that location, or returns the provided
5418 // location if a stored location does not exist.
5419 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5420 SourceLocation Loc) {
5421 if (D.getName().StartLocation.isInvalid() &&
5422 D.getName().EndLocation.isValid())
5423 return D.getName().EndLocation;
5428 /// ParseDirectDeclarator
5429 /// direct-declarator: [C99 6.7.5]
5430 /// [C99] identifier
5431 /// '(' declarator ')'
5432 /// [GNU] '(' attributes declarator ')'
5433 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5434 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5435 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5436 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5437 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5438 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5439 /// attribute-specifier-seq[opt]
5440 /// direct-declarator '(' parameter-type-list ')'
5441 /// direct-declarator '(' identifier-list[opt] ')'
5442 /// [GNU] direct-declarator '(' parameter-forward-declarations
5443 /// parameter-type-list[opt] ')'
5444 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
5445 /// cv-qualifier-seq[opt] exception-specification[opt]
5446 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5447 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5448 /// ref-qualifier[opt] exception-specification[opt]
5449 /// [C++] declarator-id
5450 /// [C++11] declarator-id attribute-specifier-seq[opt]
5452 /// declarator-id: [C++ 8]
5453 /// '...'[opt] id-expression
5454 /// '::'[opt] nested-name-specifier[opt] type-name
5456 /// id-expression: [C++ 5.1]
5460 /// unqualified-id: [C++ 5.1]
5462 /// operator-function-id
5463 /// conversion-function-id
5467 /// C++17 adds the following, which we also handle here:
5469 /// simple-declaration:
5470 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5472 /// Note, any additional constructs added here may need corresponding changes
5473 /// in isConstructorDeclarator.
5474 void Parser::ParseDirectDeclarator(Declarator &D) {
5475 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
5477 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
5478 // This might be a C++17 structured binding.
5479 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5480 D.getCXXScopeSpec().isEmpty())
5481 return ParseDecompositionDeclarator(D);
5483 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5484 // this context it is a bitfield. Also in range-based for statement colon
5485 // may delimit for-range-declaration.
5486 ColonProtectionRAIIObject X(
5487 *this, D.getContext() == DeclaratorContext::MemberContext ||
5488 (D.getContext() == DeclaratorContext::ForContext &&
5489 getLangOpts().CPlusPlus11));
5491 // ParseDeclaratorInternal might already have parsed the scope.
5492 if (D.getCXXScopeSpec().isEmpty()) {
5493 bool EnteringContext =
5494 D.getContext() == DeclaratorContext::FileContext ||
5495 D.getContext() == DeclaratorContext::MemberContext;
5496 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
5500 if (D.getCXXScopeSpec().isValid()) {
5501 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5502 D.getCXXScopeSpec()))
5503 // Change the declaration context for name lookup, until this function
5504 // is exited (and the declarator has been parsed).
5505 DeclScopeObj.EnterDeclaratorScope();
5506 else if (getObjCDeclContext()) {
5507 // Ensure that we don't interpret the next token as an identifier when
5508 // dealing with declarations in an Objective-C container.
5509 D.SetIdentifier(nullptr, Tok.getLocation());
5510 D.setInvalidType(true);
5512 goto PastIdentifier;
5516 // C++0x [dcl.fct]p14:
5517 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5518 // parameter-declaration-clause without a preceding comma. In this case,
5519 // the ellipsis is parsed as part of the abstract-declarator if the type
5520 // of the parameter either names a template parameter pack that has not
5521 // been expanded or contains auto; otherwise, it is parsed as part of the
5522 // parameter-declaration-clause.
5523 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
5524 !((D.getContext() == DeclaratorContext::PrototypeContext ||
5525 D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5526 D.getContext() == DeclaratorContext::BlockLiteralContext) &&
5527 NextToken().is(tok::r_paren) &&
5528 !D.hasGroupingParens() &&
5529 !Actions.containsUnexpandedParameterPacks(D) &&
5530 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
5531 SourceLocation EllipsisLoc = ConsumeToken();
5532 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
5533 // The ellipsis was put in the wrong place. Recover, and explain to
5534 // the user what they should have done.
5536 if (EllipsisLoc.isValid())
5537 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5540 D.setEllipsisLoc(EllipsisLoc);
5542 // The ellipsis can't be followed by a parenthesized declarator. We
5543 // check for that in ParseParenDeclarator, after we have disambiguated
5544 // the l_paren token.
5547 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5549 // We found something that indicates the start of an unqualified-id.
5550 // Parse that unqualified-id.
5551 bool AllowConstructorName;
5552 bool AllowDeductionGuide;
5553 if (D.getDeclSpec().hasTypeSpecifier()) {
5554 AllowConstructorName = false;
5555 AllowDeductionGuide = false;
5556 } else if (D.getCXXScopeSpec().isSet()) {
5557 AllowConstructorName =
5558 (D.getContext() == DeclaratorContext::FileContext ||
5559 D.getContext() == DeclaratorContext::MemberContext);
5560 AllowDeductionGuide = false;
5562 AllowConstructorName =
5563 (D.getContext() == DeclaratorContext::MemberContext);
5564 AllowDeductionGuide =
5565 (D.getContext() == DeclaratorContext::FileContext ||
5566 D.getContext() == DeclaratorContext::MemberContext);
5569 SourceLocation TemplateKWLoc;
5570 bool HadScope = D.getCXXScopeSpec().isValid();
5571 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5572 /*EnteringContext=*/true,
5573 /*AllowDestructorName=*/true, AllowConstructorName,
5574 AllowDeductionGuide, nullptr, TemplateKWLoc,
5576 // Once we're past the identifier, if the scope was bad, mark the
5577 // whole declarator bad.
5578 D.getCXXScopeSpec().isInvalid()) {
5579 D.SetIdentifier(nullptr, Tok.getLocation());
5580 D.setInvalidType(true);
5582 // ParseUnqualifiedId might have parsed a scope specifier during error
5583 // recovery. If it did so, enter that scope.
5584 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5585 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5586 D.getCXXScopeSpec()))
5587 DeclScopeObj.EnterDeclaratorScope();
5589 // Parsed the unqualified-id; update range information and move along.
5590 if (D.getSourceRange().getBegin().isInvalid())
5591 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5592 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
5594 goto PastIdentifier;
5597 if (D.getCXXScopeSpec().isNotEmpty()) {
5598 // We have a scope specifier but no following unqualified-id.
5599 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5600 diag::err_expected_unqualified_id)
5602 D.SetIdentifier(nullptr, Tok.getLocation());
5603 goto PastIdentifier;
5605 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
5606 assert(!getLangOpts().CPlusPlus &&
5607 "There's a C++-specific check for tok::identifier above");
5608 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5609 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5610 D.SetRangeEnd(Tok.getLocation());
5612 goto PastIdentifier;
5613 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5614 // We're not allowed an identifier here, but we got one. Try to figure out
5615 // if the user was trying to attach a name to the type, or whether the name
5616 // is some unrelated trailing syntax.
5617 bool DiagnoseIdentifier = false;
5618 if (D.hasGroupingParens())
5619 // An identifier within parens is unlikely to be intended to be anything
5620 // other than a name being "declared".
5621 DiagnoseIdentifier = true;
5622 else if (D.getContext() == DeclaratorContext::TemplateTypeArgContext)
5623 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5624 DiagnoseIdentifier =
5625 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
5626 else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5627 D.getContext() == DeclaratorContext::AliasTemplateContext)
5628 // The most likely error is that the ';' was forgotten.
5629 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
5630 else if (D.getContext() == DeclaratorContext::TrailingReturnContext &&
5631 !isCXX11VirtSpecifier(Tok))
5632 DiagnoseIdentifier = NextToken().isOneOf(
5633 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5634 if (DiagnoseIdentifier) {
5635 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5636 << FixItHint::CreateRemoval(Tok.getLocation());
5637 D.SetIdentifier(nullptr, Tok.getLocation());
5639 goto PastIdentifier;
5643 if (Tok.is(tok::l_paren)) {
5644 // direct-declarator: '(' declarator ')'
5645 // direct-declarator: '(' attributes declarator ')'
5646 // Example: 'char (*X)' or 'int (*XX)(void)'
5647 ParseParenDeclarator(D);
5649 // If the declarator was parenthesized, we entered the declarator
5650 // scope when parsing the parenthesized declarator, then exited
5651 // the scope already. Re-enter the scope, if we need to.
5652 if (D.getCXXScopeSpec().isSet()) {
5653 // If there was an error parsing parenthesized declarator, declarator
5654 // scope may have been entered before. Don't do it again.
5655 if (!D.isInvalidType() &&
5656 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5657 D.getCXXScopeSpec()))
5658 // Change the declaration context for name lookup, until this function
5659 // is exited (and the declarator has been parsed).
5660 DeclScopeObj.EnterDeclaratorScope();
5662 } else if (D.mayOmitIdentifier()) {
5663 // This could be something simple like "int" (in which case the declarator
5664 // portion is empty), if an abstract-declarator is allowed.
5665 D.SetIdentifier(nullptr, Tok.getLocation());
5667 // The grammar for abstract-pack-declarator does not allow grouping parens.
5668 // FIXME: Revisit this once core issue 1488 is resolved.
5669 if (D.hasEllipsis() && D.hasGroupingParens())
5670 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5671 diag::ext_abstract_pack_declarator_parens);
5673 if (Tok.getKind() == tok::annot_pragma_parser_crash)
5675 if (Tok.is(tok::l_square))
5676 return ParseMisplacedBracketDeclarator(D);
5677 if (D.getContext() == DeclaratorContext::MemberContext) {
5678 // Objective-C++: Detect C++ keywords and try to prevent further errors by
5679 // treating these keyword as valid member names.
5680 if (getLangOpts().ObjC1 && getLangOpts().CPlusPlus &&
5681 Tok.getIdentifierInfo() &&
5682 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5683 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5684 diag::err_expected_member_name_or_semi_objcxx_keyword)
5685 << Tok.getIdentifierInfo()
5686 << (D.getDeclSpec().isEmpty() ? SourceRange()
5687 : D.getDeclSpec().getSourceRange());
5688 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5689 D.SetRangeEnd(Tok.getLocation());
5691 goto PastIdentifier;
5693 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5694 diag::err_expected_member_name_or_semi)
5695 << (D.getDeclSpec().isEmpty() ? SourceRange()
5696 : D.getDeclSpec().getSourceRange());
5697 } else if (getLangOpts().CPlusPlus) {
5698 if (Tok.isOneOf(tok::period, tok::arrow))
5699 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
5701 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5702 if (Tok.isAtStartOfLine() && Loc.isValid())
5703 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5704 << getLangOpts().CPlusPlus;
5706 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5707 diag::err_expected_unqualified_id)
5708 << getLangOpts().CPlusPlus;
5711 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5712 diag::err_expected_either)
5713 << tok::identifier << tok::l_paren;
5715 D.SetIdentifier(nullptr, Tok.getLocation());
5716 D.setInvalidType(true);
5720 assert(D.isPastIdentifier() &&
5721 "Haven't past the location of the identifier yet?");
5723 // Don't parse attributes unless we have parsed an unparenthesized name.
5724 if (D.hasName() && !D.getNumTypeObjects())
5725 MaybeParseCXX11Attributes(D);
5728 if (Tok.is(tok::l_paren)) {
5729 // Enter function-declaration scope, limiting any declarators to the
5730 // function prototype scope, including parameter declarators.
5731 ParseScope PrototypeScope(this,
5732 Scope::FunctionPrototypeScope|Scope::DeclScope|
5733 (D.isFunctionDeclaratorAFunctionDeclaration()
5734 ? Scope::FunctionDeclarationScope : 0));
5736 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5737 // In such a case, check if we actually have a function declarator; if it
5738 // is not, the declarator has been fully parsed.
5739 bool IsAmbiguous = false;
5740 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5741 // The name of the declarator, if any, is tentatively declared within
5742 // a possible direct initializer.
5743 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5744 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5745 TentativelyDeclaredIdentifiers.pop_back();
5746 if (!IsFunctionDecl)
5749 ParsedAttributes attrs(AttrFactory);
5750 BalancedDelimiterTracker T(*this, tok::l_paren);
5752 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
5753 PrototypeScope.Exit();
5754 } else if (Tok.is(tok::l_square)) {
5755 ParseBracketDeclarator(D);
5762 void Parser::ParseDecompositionDeclarator(Declarator &D) {
5763 assert(Tok.is(tok::l_square));
5765 // If this doesn't look like a structured binding, maybe it's a misplaced
5766 // array declarator.
5767 // FIXME: Consume the l_square first so we don't need extra lookahead for
5769 if (!(NextToken().is(tok::identifier) &&
5770 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5771 !(NextToken().is(tok::r_square) &&
5772 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5773 return ParseMisplacedBracketDeclarator(D);
5775 BalancedDelimiterTracker T(*this, tok::l_square);
5778 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5779 while (Tok.isNot(tok::r_square)) {
5780 if (!Bindings.empty()) {
5781 if (Tok.is(tok::comma))
5784 if (Tok.is(tok::identifier)) {
5785 SourceLocation EndLoc = getEndOfPreviousToken();
5786 Diag(EndLoc, diag::err_expected)
5787 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
5789 Diag(Tok, diag::err_expected_comma_or_rsquare);
5792 SkipUntil(tok::r_square, tok::comma, tok::identifier,
5793 StopAtSemi | StopBeforeMatch);
5794 if (Tok.is(tok::comma))
5796 else if (Tok.isNot(tok::identifier))
5801 if (Tok.isNot(tok::identifier)) {
5802 Diag(Tok, diag::err_expected) << tok::identifier;
5806 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
5810 if (Tok.isNot(tok::r_square))
5811 // We've already diagnosed a problem here.
5814 // C++17 does not allow the identifier-list in a structured binding
5816 if (Bindings.empty())
5817 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
5822 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
5823 T.getCloseLocation());
5826 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
5827 /// only called before the identifier, so these are most likely just grouping
5828 /// parens for precedence. If we find that these are actually function
5829 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5831 /// direct-declarator:
5832 /// '(' declarator ')'
5833 /// [GNU] '(' attributes declarator ')'
5834 /// direct-declarator '(' parameter-type-list ')'
5835 /// direct-declarator '(' identifier-list[opt] ')'
5836 /// [GNU] direct-declarator '(' parameter-forward-declarations
5837 /// parameter-type-list[opt] ')'
5839 void Parser::ParseParenDeclarator(Declarator &D) {
5840 BalancedDelimiterTracker T(*this, tok::l_paren);
5843 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
5845 // Eat any attributes before we look at whether this is a grouping or function
5846 // declarator paren. If this is a grouping paren, the attribute applies to
5847 // the type being built up, for example:
5848 // int (__attribute__(()) *x)(long y)
5849 // If this ends up not being a grouping paren, the attribute applies to the
5850 // first argument, for example:
5851 // int (__attribute__(()) int x)
5852 // In either case, we need to eat any attributes to be able to determine what
5853 // sort of paren this is.
5855 ParsedAttributes attrs(AttrFactory);
5856 bool RequiresArg = false;
5857 if (Tok.is(tok::kw___attribute)) {
5858 ParseGNUAttributes(attrs);
5860 // We require that the argument list (if this is a non-grouping paren) be
5861 // present even if the attribute list was empty.
5865 // Eat any Microsoft extensions.
5866 ParseMicrosoftTypeAttributes(attrs);
5868 // Eat any Borland extensions.
5869 if (Tok.is(tok::kw___pascal))
5870 ParseBorlandTypeAttributes(attrs);
5872 // If we haven't past the identifier yet (or where the identifier would be
5873 // stored, if this is an abstract declarator), then this is probably just
5874 // grouping parens. However, if this could be an abstract-declarator, then
5875 // this could also be the start of function arguments (consider 'void()').
5878 if (!D.mayOmitIdentifier()) {
5879 // If this can't be an abstract-declarator, this *must* be a grouping
5880 // paren, because we haven't seen the identifier yet.
5882 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
5883 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
5884 NextToken().is(tok::r_paren)) || // C++ int(...)
5885 isDeclarationSpecifier() || // 'int(int)' is a function.
5886 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
5887 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
5888 // considered to be a type, not a K&R identifier-list.
5891 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
5895 // If this is a grouping paren, handle:
5896 // direct-declarator: '(' declarator ')'
5897 // direct-declarator: '(' attributes declarator ')'
5899 SourceLocation EllipsisLoc = D.getEllipsisLoc();
5900 D.setEllipsisLoc(SourceLocation());
5902 bool hadGroupingParens = D.hasGroupingParens();
5903 D.setGroupingParens(true);
5904 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5907 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
5908 T.getCloseLocation()),
5909 attrs, T.getCloseLocation());
5911 D.setGroupingParens(hadGroupingParens);
5913 // An ellipsis cannot be placed outside parentheses.
5914 if (EllipsisLoc.isValid())
5915 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5920 // Okay, if this wasn't a grouping paren, it must be the start of a function
5921 // argument list. Recognize that this declarator will never have an
5922 // identifier (and remember where it would have been), then call into
5923 // ParseFunctionDeclarator to handle of argument list.
5924 D.SetIdentifier(nullptr, Tok.getLocation());
5926 // Enter function-declaration scope, limiting any declarators to the
5927 // function prototype scope, including parameter declarators.
5928 ParseScope PrototypeScope(this,
5929 Scope::FunctionPrototypeScope | Scope::DeclScope |
5930 (D.isFunctionDeclaratorAFunctionDeclaration()
5931 ? Scope::FunctionDeclarationScope : 0));
5932 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
5933 PrototypeScope.Exit();
5936 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
5937 /// declarator D up to a paren, which indicates that we are parsing function
5940 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
5941 /// immediately after the open paren - they should be considered to be the
5942 /// first argument of a parameter.
5944 /// If RequiresArg is true, then the first argument of the function is required
5945 /// to be present and required to not be an identifier list.
5947 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
5948 /// (C++11) ref-qualifier[opt], exception-specification[opt],
5949 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
5951 /// [C++11] exception-specification:
5952 /// dynamic-exception-specification
5953 /// noexcept-specification
5955 void Parser::ParseFunctionDeclarator(Declarator &D,
5956 ParsedAttributes &FirstArgAttrs,
5957 BalancedDelimiterTracker &Tracker,
5960 assert(getCurScope()->isFunctionPrototypeScope() &&
5961 "Should call from a Function scope");
5962 // lparen is already consumed!
5963 assert(D.isPastIdentifier() && "Should not call before identifier!");
5965 // This should be true when the function has typed arguments.
5966 // Otherwise, it is treated as a K&R-style function.
5967 bool HasProto = false;
5968 // Build up an array of information about the parsed arguments.
5969 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
5970 // Remember where we see an ellipsis, if any.
5971 SourceLocation EllipsisLoc;
5973 DeclSpec DS(AttrFactory);
5974 bool RefQualifierIsLValueRef = true;
5975 SourceLocation RefQualifierLoc;
5976 SourceLocation ConstQualifierLoc;
5977 SourceLocation VolatileQualifierLoc;
5978 SourceLocation RestrictQualifierLoc;
5979 ExceptionSpecificationType ESpecType = EST_None;
5980 SourceRange ESpecRange;
5981 SmallVector<ParsedType, 2> DynamicExceptions;
5982 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5983 ExprResult NoexceptExpr;
5984 CachedTokens *ExceptionSpecTokens = nullptr;
5985 ParsedAttributesWithRange FnAttrs(AttrFactory);
5986 TypeResult TrailingReturnType;
5988 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
5989 EndLoc is the end location for the function declarator.
5990 They differ for trailing return types. */
5991 SourceLocation StartLoc, LocalEndLoc, EndLoc;
5992 SourceLocation LParenLoc, RParenLoc;
5993 LParenLoc = Tracker.getOpenLocation();
5994 StartLoc = LParenLoc;
5996 if (isFunctionDeclaratorIdentifierList()) {
5998 Diag(Tok, diag::err_argument_required_after_attribute);
6000 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6002 Tracker.consumeClose();
6003 RParenLoc = Tracker.getCloseLocation();
6004 LocalEndLoc = RParenLoc;
6007 // If there are attributes following the identifier list, parse them and
6009 MaybeParseCXX11Attributes(FnAttrs);
6010 ProhibitAttributes(FnAttrs);
6012 if (Tok.isNot(tok::r_paren))
6013 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
6015 else if (RequiresArg)
6016 Diag(Tok, diag::err_argument_required_after_attribute);
6018 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6019 || getLangOpts().OpenCL;
6021 // If we have the closing ')', eat it.
6022 Tracker.consumeClose();
6023 RParenLoc = Tracker.getCloseLocation();
6024 LocalEndLoc = RParenLoc;
6027 if (getLangOpts().CPlusPlus) {
6028 // FIXME: Accept these components in any order, and produce fixits to
6029 // correct the order if the user gets it wrong. Ideally we should deal
6030 // with the pure-specifier in the same way.
6032 // Parse cv-qualifier-seq[opt].
6033 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
6034 /*AtomicAllowed*/ false,
6035 /*IdentifierRequired=*/false,
6036 llvm::function_ref<void()>([&]() {
6037 Actions.CodeCompleteFunctionQualifiers(DS, D);
6039 if (!DS.getSourceRange().getEnd().isInvalid()) {
6040 EndLoc = DS.getSourceRange().getEnd();
6041 ConstQualifierLoc = DS.getConstSpecLoc();
6042 VolatileQualifierLoc = DS.getVolatileSpecLoc();
6043 RestrictQualifierLoc = DS.getRestrictSpecLoc();
6046 // Parse ref-qualifier[opt].
6047 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
6048 EndLoc = RefQualifierLoc;
6050 // C++11 [expr.prim.general]p3:
6051 // If a declaration declares a member function or member function
6052 // template of a class X, the expression this is a prvalue of type
6053 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6054 // and the end of the function-definition, member-declarator, or
6056 // FIXME: currently, "static" case isn't handled correctly.
6057 bool IsCXX11MemberFunction =
6058 getLangOpts().CPlusPlus11 &&
6059 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6060 (D.getContext() == DeclaratorContext::MemberContext
6061 ? !D.getDeclSpec().isFriendSpecified()
6062 : D.getContext() == DeclaratorContext::FileContext &&
6063 D.getCXXScopeSpec().isValid() &&
6064 Actions.CurContext->isRecord());
6065 Sema::CXXThisScopeRAII ThisScope(Actions,
6066 dyn_cast<CXXRecordDecl>(Actions.CurContext),
6067 DS.getTypeQualifiers() |
6068 (D.getDeclSpec().isConstexprSpecified() &&
6069 !getLangOpts().CPlusPlus14
6070 ? Qualifiers::Const : 0),
6071 IsCXX11MemberFunction);
6073 // Parse exception-specification[opt].
6074 bool Delayed = D.isFirstDeclarationOfMember() &&
6075 D.isFunctionDeclaratorAFunctionDeclaration();
6076 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6077 GetLookAheadToken(0).is(tok::kw_noexcept) &&
6078 GetLookAheadToken(1).is(tok::l_paren) &&
6079 GetLookAheadToken(2).is(tok::kw_noexcept) &&
6080 GetLookAheadToken(3).is(tok::l_paren) &&
6081 GetLookAheadToken(4).is(tok::identifier) &&
6082 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6083 // HACK: We've got an exception-specification
6084 // noexcept(noexcept(swap(...)))
6086 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6087 // on a 'swap' member function. This is a libstdc++ bug; the lookup
6088 // for 'swap' will only find the function we're currently declaring,
6089 // whereas it expects to find a non-member swap through ADL. Turn off
6090 // delayed parsing to give it a chance to find what it expects.
6093 ESpecType = tryParseExceptionSpecification(Delayed,
6096 DynamicExceptionRanges,
6098 ExceptionSpecTokens);
6099 if (ESpecType != EST_None)
6100 EndLoc = ESpecRange.getEnd();
6102 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6103 // after the exception-specification.
6104 MaybeParseCXX11Attributes(FnAttrs);
6106 // Parse trailing-return-type[opt].
6107 LocalEndLoc = EndLoc;
6108 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
6109 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
6110 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
6111 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
6112 LocalEndLoc = Tok.getLocation();
6114 TrailingReturnType = ParseTrailingReturnType(Range);
6115 EndLoc = Range.getEnd();
6117 } else if (standardAttributesAllowed()) {
6118 MaybeParseCXX11Attributes(FnAttrs);
6122 // Collect non-parameter declarations from the prototype if this is a function
6123 // declaration. They will be moved into the scope of the function. Only do
6124 // this in C and not C++, where the decls will continue to live in the
6125 // surrounding context.
6126 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6127 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6128 !getLangOpts().CPlusPlus) {
6129 for (Decl *D : getCurScope()->decls()) {
6130 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6131 if (!ND || isa<ParmVarDecl>(ND))
6133 DeclsInPrototype.push_back(ND);
6137 // Remember that we parsed a function type, and remember the attributes.
6138 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
6141 ParamInfo.data(), ParamInfo.size(),
6142 EllipsisLoc, RParenLoc,
6143 DS.getTypeQualifiers(),
6144 RefQualifierIsLValueRef,
6145 RefQualifierLoc, ConstQualifierLoc,
6146 VolatileQualifierLoc,
6147 RestrictQualifierLoc,
6148 /*MutableLoc=*/SourceLocation(),
6149 ESpecType, ESpecRange,
6150 DynamicExceptions.data(),
6151 DynamicExceptionRanges.data(),
6152 DynamicExceptions.size(),
6153 NoexceptExpr.isUsable() ?
6154 NoexceptExpr.get() : nullptr,
6155 ExceptionSpecTokens,
6157 StartLoc, LocalEndLoc, D,
6158 TrailingReturnType),
6162 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6163 /// true if a ref-qualifier is found.
6164 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6165 SourceLocation &RefQualifierLoc) {
6166 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
6167 Diag(Tok, getLangOpts().CPlusPlus11 ?
6168 diag::warn_cxx98_compat_ref_qualifier :
6169 diag::ext_ref_qualifier);
6171 RefQualifierIsLValueRef = Tok.is(tok::amp);
6172 RefQualifierLoc = ConsumeToken();
6178 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
6179 /// identifier list form for a K&R-style function: void foo(a,b,c)
6181 /// Note that identifier-lists are only allowed for normal declarators, not for
6182 /// abstract-declarators.
6183 bool Parser::isFunctionDeclaratorIdentifierList() {
6184 return !getLangOpts().CPlusPlus
6185 && Tok.is(tok::identifier)
6186 && !TryAltiVecVectorToken()
6187 // K&R identifier lists can't have typedefs as identifiers, per C99
6189 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6190 // Identifier lists follow a really simple grammar: the identifiers can
6191 // be followed *only* by a ", identifier" or ")". However, K&R
6192 // identifier lists are really rare in the brave new modern world, and
6193 // it is very common for someone to typo a type in a non-K&R style
6194 // list. If we are presented with something like: "void foo(intptr x,
6195 // float y)", we don't want to start parsing the function declarator as
6196 // though it is a K&R style declarator just because intptr is an
6199 // To handle this, we check to see if the token after the first
6200 // identifier is a "," or ")". Only then do we parse it as an
6202 && (!Tok.is(tok::eof) &&
6203 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
6206 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6207 /// we found a K&R-style identifier list instead of a typed parameter list.
6209 /// After returning, ParamInfo will hold the parsed parameters.
6211 /// identifier-list: [C99 6.7.5]
6213 /// identifier-list ',' identifier
6215 void Parser::ParseFunctionDeclaratorIdentifierList(
6217 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
6218 // If there was no identifier specified for the declarator, either we are in
6219 // an abstract-declarator, or we are in a parameter declarator which was found
6220 // to be abstract. In abstract-declarators, identifier lists are not valid:
6222 if (!D.getIdentifier())
6223 Diag(Tok, diag::ext_ident_list_in_param);
6225 // Maintain an efficient lookup of params we have seen so far.
6226 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6229 // If this isn't an identifier, report the error and skip until ')'.
6230 if (Tok.isNot(tok::identifier)) {
6231 Diag(Tok, diag::err_expected) << tok::identifier;
6232 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
6233 // Forget we parsed anything.
6238 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6240 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6241 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6242 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6244 // Verify that the argument identifier has not already been mentioned.
6245 if (!ParamsSoFar.insert(ParmII).second) {
6246 Diag(Tok, diag::err_param_redefinition) << ParmII;
6248 // Remember this identifier in ParamInfo.
6249 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6254 // Eat the identifier.
6256 // The list continues if we see a comma.
6257 } while (TryConsumeToken(tok::comma));
6260 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6261 /// after the opening parenthesis. This function will not parse a K&R-style
6262 /// identifier list.
6264 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
6265 /// caller parsed those arguments immediately after the open paren - they should
6266 /// be considered to be part of the first parameter.
6268 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6269 /// be the location of the ellipsis, if any was parsed.
6271 /// parameter-type-list: [C99 6.7.5]
6273 /// parameter-list ',' '...'
6274 /// [C++] parameter-list '...'
6276 /// parameter-list: [C99 6.7.5]
6277 /// parameter-declaration
6278 /// parameter-list ',' parameter-declaration
6280 /// parameter-declaration: [C99 6.7.5]
6281 /// declaration-specifiers declarator
6282 /// [C++] declaration-specifiers declarator '=' assignment-expression
6283 /// [C++11] initializer-clause
6284 /// [GNU] declaration-specifiers declarator attributes
6285 /// declaration-specifiers abstract-declarator[opt]
6286 /// [C++] declaration-specifiers abstract-declarator[opt]
6287 /// '=' assignment-expression
6288 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
6289 /// [C++11] attribute-specifier-seq parameter-declaration
6291 void Parser::ParseParameterDeclarationClause(
6293 ParsedAttributes &FirstArgAttrs,
6294 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
6295 SourceLocation &EllipsisLoc) {
6297 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6298 // before deciding this was a parameter-declaration-clause.
6299 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
6302 // Parse the declaration-specifiers.
6303 // Just use the ParsingDeclaration "scope" of the declarator.
6304 DeclSpec DS(AttrFactory);
6306 // Parse any C++11 attributes.
6307 MaybeParseCXX11Attributes(DS.getAttributes());
6309 // Skip any Microsoft attributes before a param.
6310 MaybeParseMicrosoftAttributes(DS.getAttributes());
6312 SourceLocation DSStart = Tok.getLocation();
6314 // If the caller parsed attributes for the first argument, add them now.
6315 // Take them so that we only apply the attributes to the first parameter.
6316 // FIXME: If we can leave the attributes in the token stream somehow, we can
6317 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6319 DS.takeAttributesFrom(FirstArgAttrs);
6321 ParseDeclarationSpecifiers(DS);
6324 // Parse the declarator. This is "PrototypeContext" or
6325 // "LambdaExprParameterContext", because we must accept either
6326 // 'declarator' or 'abstract-declarator' here.
6327 Declarator ParmDeclarator(
6328 DS, D.getContext() == DeclaratorContext::LambdaExprContext
6329 ? DeclaratorContext::LambdaExprParameterContext
6330 : DeclaratorContext::PrototypeContext);
6331 ParseDeclarator(ParmDeclarator);
6333 // Parse GNU attributes, if present.
6334 MaybeParseGNUAttributes(ParmDeclarator);
6336 // Remember this parsed parameter in ParamInfo.
6337 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
6339 // DefArgToks is used when the parsing of default arguments needs
6341 std::unique_ptr<CachedTokens> DefArgToks;
6343 // If no parameter was specified, verify that *something* was specified,
6344 // otherwise we have a missing type and identifier.
6345 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
6346 ParmDeclarator.getNumTypeObjects() == 0) {
6347 // Completely missing, emit error.
6348 Diag(DSStart, diag::err_missing_param);
6350 // Otherwise, we have something. Add it and let semantic analysis try
6351 // to grok it and add the result to the ParamInfo we are building.
6353 // Last chance to recover from a misplaced ellipsis in an attempted
6354 // parameter pack declaration.
6355 if (Tok.is(tok::ellipsis) &&
6356 (NextToken().isNot(tok::r_paren) ||
6357 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6358 !Actions.isUnexpandedParameterPackPermitted())) &&
6359 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6360 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6362 // Inform the actions module about the parameter declarator, so it gets
6363 // added to the current scope.
6364 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
6365 // Parse the default argument, if any. We parse the default
6366 // arguments in all dialects; the semantic analysis in
6367 // ActOnParamDefaultArgument will reject the default argument in
6369 if (Tok.is(tok::equal)) {
6370 SourceLocation EqualLoc = Tok.getLocation();
6372 // Parse the default argument
6373 if (D.getContext() == DeclaratorContext::MemberContext) {
6374 // If we're inside a class definition, cache the tokens
6375 // corresponding to the default argument. We'll actually parse
6376 // them when we see the end of the class definition.
6377 DefArgToks.reset(new CachedTokens);
6379 SourceLocation ArgStartLoc = NextToken().getLocation();
6380 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
6382 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6384 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
6391 // The argument isn't actually potentially evaluated unless it is
6393 EnterExpressionEvaluationContext Eval(
6395 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6398 ExprResult DefArgResult;
6399 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
6400 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
6401 DefArgResult = ParseBraceInitializer();
6403 DefArgResult = ParseAssignmentExpression();
6404 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
6405 if (DefArgResult.isInvalid()) {
6406 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6407 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
6409 // Inform the actions module about the default argument
6410 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
6411 DefArgResult.get());
6416 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6417 ParmDeclarator.getIdentifierLoc(),
6418 Param, std::move(DefArgToks)));
6421 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6422 if (!getLangOpts().CPlusPlus) {
6423 // We have ellipsis without a preceding ',', which is ill-formed
6424 // in C. Complain and provide the fix.
6425 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6426 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6427 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6428 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6429 // It looks like this was supposed to be a parameter pack. Warn and
6430 // point out where the ellipsis should have gone.
6431 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6432 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6433 << ParmEllipsis.isValid() << ParmEllipsis;
6434 if (ParmEllipsis.isValid()) {
6436 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6438 Diag(ParmDeclarator.getIdentifierLoc(),
6439 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6440 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6442 << !ParmDeclarator.hasName();
6444 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
6445 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6448 // We can't have any more parameters after an ellipsis.
6452 // If the next token is a comma, consume it and keep reading arguments.
6453 } while (TryConsumeToken(tok::comma));
6456 /// [C90] direct-declarator '[' constant-expression[opt] ']'
6457 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6458 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6459 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6460 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
6461 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
6462 /// attribute-specifier-seq[opt]
6463 void Parser::ParseBracketDeclarator(Declarator &D) {
6464 if (CheckProhibitedCXX11Attribute())
6467 BalancedDelimiterTracker T(*this, tok::l_square);
6470 // C array syntax has many features, but by-far the most common is [] and [4].
6471 // This code does a fast path to handle some of the most obvious cases.
6472 if (Tok.getKind() == tok::r_square) {
6474 ParsedAttributes attrs(AttrFactory);
6475 MaybeParseCXX11Attributes(attrs);
6477 // Remember that we parsed the empty array type.
6478 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
6479 T.getOpenLocation(),
6480 T.getCloseLocation()),
6481 attrs, T.getCloseLocation());
6483 } else if (Tok.getKind() == tok::numeric_constant &&
6484 GetLookAheadToken(1).is(tok::r_square)) {
6485 // [4] is very common. Parse the numeric constant expression.
6486 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
6490 ParsedAttributes attrs(AttrFactory);
6491 MaybeParseCXX11Attributes(attrs);
6493 // Remember that we parsed a array type, and remember its features.
6494 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false,
6496 T.getOpenLocation(),
6497 T.getCloseLocation()),
6498 attrs, T.getCloseLocation());
6500 } else if (Tok.getKind() == tok::code_completion) {
6501 Actions.CodeCompleteBracketDeclarator(getCurScope());
6502 return cutOffParsing();
6505 // If valid, this location is the position where we read the 'static' keyword.
6506 SourceLocation StaticLoc;
6507 TryConsumeToken(tok::kw_static, StaticLoc);
6509 // If there is a type-qualifier-list, read it now.
6510 // Type qualifiers in an array subscript are a C99 feature.
6511 DeclSpec DS(AttrFactory);
6512 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
6514 // If we haven't already read 'static', check to see if there is one after the
6515 // type-qualifier-list.
6516 if (!StaticLoc.isValid())
6517 TryConsumeToken(tok::kw_static, StaticLoc);
6519 // Handle "direct-declarator [ type-qual-list[opt] * ]".
6520 bool isStar = false;
6521 ExprResult NumElements;
6523 // Handle the case where we have '[*]' as the array size. However, a leading
6524 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
6525 // the token after the star is a ']'. Since stars in arrays are
6526 // infrequent, use of lookahead is not costly here.
6527 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
6528 ConsumeToken(); // Eat the '*'.
6530 if (StaticLoc.isValid()) {
6531 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
6532 StaticLoc = SourceLocation(); // Drop the static.
6535 } else if (Tok.isNot(tok::r_square)) {
6536 // Note, in C89, this production uses the constant-expr production instead
6537 // of assignment-expr. The only difference is that assignment-expr allows
6538 // things like '=' and '*='. Sema rejects these in C89 mode because they
6539 // are not i-c-e's, so we don't need to distinguish between the two here.
6541 // Parse the constant-expression or assignment-expression now (depending
6543 if (getLangOpts().CPlusPlus) {
6544 NumElements = ParseConstantExpression();
6546 EnterExpressionEvaluationContext Unevaluated(
6547 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6549 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
6552 if (StaticLoc.isValid()) {
6553 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6554 StaticLoc = SourceLocation(); // Drop the static.
6558 // If there was an error parsing the assignment-expression, recover.
6559 if (NumElements.isInvalid()) {
6560 D.setInvalidType(true);
6561 // If the expression was invalid, skip it.
6562 SkipUntil(tok::r_square, StopAtSemi);
6568 MaybeParseCXX11Attributes(DS.getAttributes());
6570 // Remember that we parsed a array type, and remember its features.
6571 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
6572 StaticLoc.isValid(), isStar,
6574 T.getOpenLocation(),
6575 T.getCloseLocation()),
6576 DS.getAttributes(), T.getCloseLocation());
6579 /// Diagnose brackets before an identifier.
6580 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6581 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6582 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6584 SourceLocation StartBracketLoc = Tok.getLocation();
6585 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6587 while (Tok.is(tok::l_square)) {
6588 ParseBracketDeclarator(TempDeclarator);
6591 // Stuff the location of the start of the brackets into the Declarator.
6592 // The diagnostics from ParseDirectDeclarator will make more sense if
6593 // they use this location instead.
6594 if (Tok.is(tok::semi))
6595 D.getName().EndLocation = StartBracketLoc;
6597 SourceLocation SuggestParenLoc = Tok.getLocation();
6599 // Now that the brackets are removed, try parsing the declarator again.
6600 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6602 // Something went wrong parsing the brackets, in which case,
6603 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6605 if (TempDeclarator.getNumTypeObjects() == 0)
6608 // Determine if parens will need to be suggested in the diagnostic.
6609 bool NeedParens = false;
6610 if (D.getNumTypeObjects() != 0) {
6611 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6612 case DeclaratorChunk::Pointer:
6613 case DeclaratorChunk::Reference:
6614 case DeclaratorChunk::BlockPointer:
6615 case DeclaratorChunk::MemberPointer:
6616 case DeclaratorChunk::Pipe:
6619 case DeclaratorChunk::Array:
6620 case DeclaratorChunk::Function:
6621 case DeclaratorChunk::Paren:
6627 // Create a DeclaratorChunk for the inserted parens.
6628 ParsedAttributes attrs(AttrFactory);
6629 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6630 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), attrs,
6634 // Adding back the bracket info to the end of the Declarator.
6635 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6636 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
6637 ParsedAttributes attrs(AttrFactory);
6638 attrs.set(Chunk.Common.AttrList);
6639 D.AddTypeInfo(Chunk, attrs, SourceLocation());
6642 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6643 // If parentheses are required, always suggest them.
6644 if (!D.getIdentifier() && !NeedParens)
6647 SourceLocation EndBracketLoc = TempDeclarator.getLocEnd();
6649 // Generate the move bracket error message.
6650 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
6651 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6654 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6655 << getLangOpts().CPlusPlus
6656 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6657 << FixItHint::CreateInsertion(EndLoc, ")")
6658 << FixItHint::CreateInsertionFromRange(
6659 EndLoc, CharSourceRange(BracketRange, true))
6660 << FixItHint::CreateRemoval(BracketRange);
6662 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6663 << getLangOpts().CPlusPlus
6664 << FixItHint::CreateInsertionFromRange(
6665 EndLoc, CharSourceRange(BracketRange, true))
6666 << FixItHint::CreateRemoval(BracketRange);
6670 /// [GNU] typeof-specifier:
6671 /// typeof ( expressions )
6672 /// typeof ( type-name )
6673 /// [GNU/C++] typeof unary-expression
6675 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
6676 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
6678 SourceLocation StartLoc = ConsumeToken();
6680 const bool hasParens = Tok.is(tok::l_paren);
6682 EnterExpressionEvaluationContext Unevaluated(
6683 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6684 Sema::ReuseLambdaContextDecl);
6688 SourceRange CastRange;
6689 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6690 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
6692 DS.setTypeofParensRange(CastRange);
6694 if (CastRange.getEnd().isInvalid())
6695 // FIXME: Not accurate, the range gets one token more than it should.
6696 DS.SetRangeEnd(Tok.getLocation());
6698 DS.SetRangeEnd(CastRange.getEnd());
6702 DS.SetTypeSpecError();
6706 const char *PrevSpec = nullptr;
6708 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6709 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
6711 Actions.getASTContext().getPrintingPolicy()))
6712 Diag(StartLoc, DiagID) << PrevSpec;
6716 // If we get here, the operand to the typeof was an expression.
6717 if (Operand.isInvalid()) {
6718 DS.SetTypeSpecError();
6722 // We might need to transform the operand if it is potentially evaluated.
6723 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6724 if (Operand.isInvalid()) {
6725 DS.SetTypeSpecError();
6729 const char *PrevSpec = nullptr;
6731 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6732 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
6733 DiagID, Operand.get(),
6734 Actions.getASTContext().getPrintingPolicy()))
6735 Diag(StartLoc, DiagID) << PrevSpec;
6738 /// [C11] atomic-specifier:
6739 /// _Atomic ( type-name )
6741 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
6742 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6743 "Not an atomic specifier");
6745 SourceLocation StartLoc = ConsumeToken();
6746 BalancedDelimiterTracker T(*this, tok::l_paren);
6747 if (T.consumeOpen())
6750 TypeResult Result = ParseTypeName();
6751 if (Result.isInvalid()) {
6752 SkipUntil(tok::r_paren, StopAtSemi);
6759 if (T.getCloseLocation().isInvalid())
6762 DS.setTypeofParensRange(T.getRange());
6763 DS.SetRangeEnd(T.getCloseLocation());
6765 const char *PrevSpec = nullptr;
6767 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
6768 DiagID, Result.get(),
6769 Actions.getASTContext().getPrintingPolicy()))
6770 Diag(StartLoc, DiagID) << PrevSpec;
6773 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6774 /// from TryAltiVecVectorToken.
6775 bool Parser::TryAltiVecVectorTokenOutOfLine() {
6776 Token Next = NextToken();
6777 switch (Next.getKind()) {
6778 default: return false;
6781 case tok::kw_signed:
6782 case tok::kw_unsigned:
6787 case tok::kw_double:
6789 case tok::kw___bool:
6790 case tok::kw___pixel:
6791 Tok.setKind(tok::kw___vector);
6793 case tok::identifier:
6794 if (Next.getIdentifierInfo() == Ident_pixel) {
6795 Tok.setKind(tok::kw___vector);
6798 if (Next.getIdentifierInfo() == Ident_bool) {
6799 Tok.setKind(tok::kw___vector);
6806 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6807 const char *&PrevSpec, unsigned &DiagID,
6809 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
6810 if (Tok.getIdentifierInfo() == Ident_vector) {
6811 Token Next = NextToken();
6812 switch (Next.getKind()) {
6815 case tok::kw_signed:
6816 case tok::kw_unsigned:
6821 case tok::kw_double:
6823 case tok::kw___bool:
6824 case tok::kw___pixel:
6825 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
6827 case tok::identifier:
6828 if (Next.getIdentifierInfo() == Ident_pixel) {
6829 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6832 if (Next.getIdentifierInfo() == Ident_bool) {
6833 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6840 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
6841 DS.isTypeAltiVecVector()) {
6842 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
6844 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
6845 DS.isTypeAltiVecVector()) {
6846 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);