1 //===--- ParseDecl.cpp - Declaration Parsing ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Declaration portions of the Parser interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/Basic/AddressSpaces.h"
18 #include "clang/Basic/CharInfo.h"
19 #include "clang/Basic/OpenCL.h"
20 #include "clang/Parse/ParseDiagnostic.h"
21 #include "clang/Sema/Lookup.h"
22 #include "clang/Sema/ParsedTemplate.h"
23 #include "clang/Sema/PrettyDeclStackTrace.h"
24 #include "clang/Sema/Scope.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/StringSwitch.h"
28 using namespace clang;
30 //===----------------------------------------------------------------------===//
31 // C99 6.7: Declarations.
32 //===----------------------------------------------------------------------===//
35 /// type-name: [C99 6.7.6]
36 /// specifier-qualifier-list abstract-declarator[opt]
38 /// Called type-id in C++.
39 TypeResult Parser::ParseTypeName(SourceRange *Range,
40 Declarator::TheContext Context,
43 ParsedAttributes *Attrs) {
44 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
45 if (DSC == DSC_normal)
46 DSC = DSC_type_specifier;
48 // Parse the common declaration-specifiers piece.
49 DeclSpec DS(AttrFactory);
51 DS.addAttributes(Attrs->getList());
52 ParseSpecifierQualifierList(DS, AS, DSC);
54 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : 0;
56 // Parse the abstract-declarator, if present.
57 Declarator DeclaratorInfo(DS, Context);
58 ParseDeclarator(DeclaratorInfo);
60 *Range = DeclaratorInfo.getSourceRange();
62 if (DeclaratorInfo.isInvalidType())
65 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
69 /// isAttributeLateParsed - Return true if the attribute has arguments that
70 /// require late parsing.
71 static bool isAttributeLateParsed(const IdentifierInfo &II) {
72 return llvm::StringSwitch<bool>(II.getName())
73 #include "clang/Parse/AttrLateParsed.inc"
77 /// ParseGNUAttributes - Parse a non-empty attributes list.
81 /// attributes attribute
84 /// '__attribute__' '(' '(' attribute-list ')' ')'
86 /// [GNU] attribute-list:
88 /// attribute_list ',' attrib
93 /// attrib-name '(' identifier ')'
94 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
95 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
97 /// [GNU] attrib-name:
103 /// Whether an attribute takes an 'identifier' is determined by the
104 /// attrib-name. GCC's behavior here is not worth imitating:
106 /// * In C mode, if the attribute argument list starts with an identifier
107 /// followed by a ',' or an ')', and the identifier doesn't resolve to
108 /// a type, it is parsed as an identifier. If the attribute actually
109 /// wanted an expression, it's out of luck (but it turns out that no
110 /// attributes work that way, because C constant expressions are very
112 /// * In C++ mode, if the attribute argument list starts with an identifier,
113 /// and the attribute *wants* an identifier, it is parsed as an identifier.
114 /// At block scope, any additional tokens between the identifier and the
115 /// ',' or ')' are ignored, otherwise they produce a parse error.
117 /// We follow the C++ model, but don't allow junk after the identifier.
118 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
119 SourceLocation *endLoc,
120 LateParsedAttrList *LateAttrs) {
121 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
123 while (Tok.is(tok::kw___attribute)) {
125 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
127 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
130 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
131 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
134 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
135 while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
136 Tok.is(tok::comma)) {
137 if (Tok.is(tok::comma)) {
138 // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
142 // we have an identifier or declaration specifier (const, int, etc.)
143 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
144 SourceLocation AttrNameLoc = ConsumeToken();
146 if (Tok.is(tok::l_paren)) {
147 // handle "parameterized" attributes
148 if (LateAttrs && isAttributeLateParsed(*AttrName)) {
149 LateParsedAttribute *LA =
150 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
151 LateAttrs->push_back(LA);
153 // Attributes in a class are parsed at the end of the class, along
154 // with other late-parsed declarations.
155 if (!ClassStack.empty() && !LateAttrs->parseSoon())
156 getCurrentClass().LateParsedDeclarations.push_back(LA);
158 // consume everything up to and including the matching right parens
159 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false);
163 Eof.setLocation(Tok.getLocation());
164 LA->Toks.push_back(Eof);
166 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc,
167 0, SourceLocation(), AttributeList::AS_GNU);
170 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 0,
171 AttributeList::AS_GNU);
174 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
175 SkipUntil(tok::r_paren, StopAtSemi);
176 SourceLocation Loc = Tok.getLocation();
177 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
178 SkipUntil(tok::r_paren, StopAtSemi);
184 /// \brief Normalizes an attribute name by dropping prefixed and suffixed __.
185 static StringRef normalizeAttrName(StringRef Name) {
186 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
187 Name = Name.drop_front(2).drop_back(2);
191 /// \brief Determine whether the given attribute has an identifier argument.
192 static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
193 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
194 #include "clang/Parse/AttrIdentifierArg.inc"
198 /// \brief Determine whether the given attribute parses a type argument.
199 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
200 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
201 #include "clang/Parse/AttrTypeArg.inc"
205 IdentifierLoc *Parser::ParseIdentifierLoc() {
206 assert(Tok.is(tok::identifier) && "expected an identifier");
207 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
209 Tok.getIdentifierInfo());
214 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
215 SourceLocation AttrNameLoc,
216 ParsedAttributes &Attrs,
217 SourceLocation *EndLoc) {
218 BalancedDelimiterTracker Parens(*this, tok::l_paren);
219 Parens.consumeOpen();
222 if (Tok.isNot(tok::r_paren))
225 if (Parens.consumeClose())
232 Attrs.addNewTypeAttr(&AttrName,
233 SourceRange(AttrNameLoc, Parens.getCloseLocation()), 0,
234 AttrNameLoc, T.get(), AttributeList::AS_GNU);
236 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
237 0, AttrNameLoc, 0, 0, AttributeList::AS_GNU);
240 /// Parse the arguments to a parameterized GNU attribute or
241 /// a C++11 attribute in "gnu" namespace.
242 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
243 SourceLocation AttrNameLoc,
244 ParsedAttributes &Attrs,
245 SourceLocation *EndLoc,
246 IdentifierInfo *ScopeName,
247 SourceLocation ScopeLoc,
248 AttributeList::Syntax Syntax) {
250 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
252 AttributeList::Kind AttrKind =
253 AttributeList::getKind(AttrName, ScopeName, Syntax);
255 // Availability attributes have their own grammar.
256 // FIXME: All these cases fail to pass in the syntax and scope, and might be
257 // written as C++11 gnu:: attributes.
258 if (AttrKind == AttributeList::AT_Availability) {
259 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
262 // Thread safety attributes are parsed in an unevaluated context.
263 // FIXME: Share the bulk of the parsing code here and just pull out
264 // the unevaluated context.
265 if (IsThreadSafetyAttribute(AttrName->getName())) {
266 ParseThreadSafetyAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
269 // Type safety attributes have their own grammar.
270 if (AttrKind == AttributeList::AT_TypeTagForDatatype) {
271 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
274 // Some attributes expect solely a type parameter.
275 if (attributeIsTypeArgAttr(*AttrName)) {
276 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc);
280 // Ignore the left paren location for now.
285 if (Tok.is(tok::identifier)) {
286 // If this attribute wants an 'identifier' argument, make it so.
287 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName);
289 // If we don't know how to parse this attribute, but this is the only
290 // token in this argument, assume it's meant to be an identifier.
291 if (AttrKind == AttributeList::UnknownAttribute ||
292 AttrKind == AttributeList::IgnoredAttribute) {
293 const Token &Next = NextToken();
294 IsIdentifierArg = Next.is(tok::r_paren) || Next.is(tok::comma);
298 ArgExprs.push_back(ParseIdentifierLoc());
301 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
303 if (!ArgExprs.empty())
306 // Parse the non-empty comma-separated list of expressions.
308 ExprResult ArgExpr(ParseAssignmentExpression());
309 if (ArgExpr.isInvalid()) {
310 SkipUntil(tok::r_paren, StopAtSemi);
313 ArgExprs.push_back(ArgExpr.release());
314 if (Tok.isNot(tok::comma))
316 ConsumeToken(); // Eat the comma, move to the next argument
320 SourceLocation RParen = Tok.getLocation();
321 if (!ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
322 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
323 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
324 ArgExprs.data(), ArgExprs.size(), Syntax);
328 /// \brief Parses a single argument for a declspec, including the
329 /// surrounding parens.
330 void Parser::ParseMicrosoftDeclSpecWithSingleArg(IdentifierInfo *AttrName,
331 SourceLocation AttrNameLoc,
332 ParsedAttributes &Attrs)
334 BalancedDelimiterTracker T(*this, tok::l_paren);
335 if (T.expectAndConsume(diag::err_expected_lparen_after,
336 AttrName->getNameStart(), tok::r_paren))
339 ExprResult ArgExpr(ParseConstantExpression());
340 if (ArgExpr.isInvalid()) {
344 ArgsUnion ExprList = ArgExpr.take();
345 Attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, &ExprList, 1,
346 AttributeList::AS_Declspec);
351 /// \brief Determines whether a declspec is a "simple" one requiring no
353 bool Parser::IsSimpleMicrosoftDeclSpec(IdentifierInfo *Ident) {
354 return llvm::StringSwitch<bool>(Ident->getName())
355 .Case("dllimport", true)
356 .Case("dllexport", true)
357 .Case("noreturn", true)
358 .Case("nothrow", true)
359 .Case("noinline", true)
361 .Case("appdomain", true)
362 .Case("process", true)
363 .Case("jitintrinsic", true)
364 .Case("noalias", true)
365 .Case("restrict", true)
366 .Case("novtable", true)
367 .Case("selectany", true)
368 .Case("thread", true)
369 .Case("safebuffers", true )
373 /// \brief Attempts to parse a declspec which is not simple (one that takes
374 /// parameters). Will return false if we properly handled the declspec, or
375 /// true if it is an unknown declspec.
376 void Parser::ParseComplexMicrosoftDeclSpec(IdentifierInfo *Ident,
378 ParsedAttributes &Attrs) {
379 // Try to handle the easy case first -- these declspecs all take a single
380 // parameter as their argument.
381 if (llvm::StringSwitch<bool>(Ident->getName())
384 .Case("allocate", true)
386 ParseMicrosoftDeclSpecWithSingleArg(Ident, Loc, Attrs);
387 } else if (Ident->getName() == "deprecated") {
388 // The deprecated declspec has an optional single argument, so we will
389 // check for a l-paren to decide whether we should parse an argument or
391 if (Tok.getKind() == tok::l_paren)
392 ParseMicrosoftDeclSpecWithSingleArg(Ident, Loc, Attrs);
394 Attrs.addNew(Ident, Loc, 0, Loc, 0, 0, AttributeList::AS_Declspec);
395 } else if (Ident->getName() == "property") {
396 // The property declspec is more complex in that it can take one or two
397 // assignment expressions as a parameter, but the lhs of the assignment
398 // must be named get or put.
399 if (Tok.isNot(tok::l_paren)) {
400 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
401 << Ident->getNameStart();
404 BalancedDelimiterTracker T(*this, tok::l_paren);
405 T.expectAndConsume(diag::err_expected_lparen_after,
406 Ident->getNameStart(), tok::r_paren);
410 AK_Put = 0, AK_Get = 1 // indices into AccessorNames
412 IdentifierInfo *AccessorNames[] = { 0, 0 };
413 bool HasInvalidAccessor = false;
415 // Parse the accessor specifications.
417 // Stop if this doesn't look like an accessor spec.
418 if (!Tok.is(tok::identifier)) {
419 // If the user wrote a completely empty list, use a special diagnostic.
420 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
421 AccessorNames[AK_Put] == 0 && AccessorNames[AK_Get] == 0) {
422 Diag(Loc, diag::err_ms_property_no_getter_or_putter);
426 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
431 SourceLocation KindLoc = Tok.getLocation();
432 StringRef KindStr = Tok.getIdentifierInfo()->getName();
433 if (KindStr == "get") {
435 } else if (KindStr == "put") {
438 // Recover from the common mistake of using 'set' instead of 'put'.
439 } else if (KindStr == "set") {
440 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
441 << FixItHint::CreateReplacement(KindLoc, "put");
444 // Handle the mistake of forgetting the accessor kind by skipping
446 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
447 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
449 HasInvalidAccessor = true;
450 goto next_property_accessor;
452 // Otherwise, complain about the unknown accessor kind.
454 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
455 HasInvalidAccessor = true;
458 // Try to keep parsing unless it doesn't look like an accessor spec.
459 if (!NextToken().is(tok::equal)) break;
462 // Consume the identifier.
466 if (Tok.is(tok::equal)) {
469 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
474 // Expect the method name.
475 if (!Tok.is(tok::identifier)) {
476 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
480 if (Kind == AK_Invalid) {
481 // Just drop invalid accessors.
482 } else if (AccessorNames[Kind] != NULL) {
483 // Complain about the repeated accessor, ignore it, and keep parsing.
484 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
486 AccessorNames[Kind] = Tok.getIdentifierInfo();
490 next_property_accessor:
491 // Keep processing accessors until we run out.
492 if (Tok.is(tok::comma)) {
496 // If we run into the ')', stop without consuming it.
497 } else if (Tok.is(tok::r_paren)) {
500 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
505 // Only add the property attribute if it was well-formed.
506 if (!HasInvalidAccessor) {
507 Attrs.addNewPropertyAttr(Ident, Loc, 0, SourceLocation(),
508 AccessorNames[AK_Get], AccessorNames[AK_Put],
509 AttributeList::AS_Declspec);
513 // We don't recognize this as a valid declspec, but instead of creating the
514 // attribute and allowing sema to warn about it, we will warn here instead.
515 // This is because some attributes have multiple spellings, but we need to
516 // disallow that for declspecs (such as align vs aligned). If we made the
517 // attribute, we'd have to split the valid declspec spelling logic into
519 Diag(Loc, diag::warn_ms_declspec_unknown) << Ident;
521 // If there's an open paren, we should eat the open and close parens under
522 // the assumption that this unknown declspec has parameters.
523 BalancedDelimiterTracker T(*this, tok::l_paren);
524 if (!T.consumeOpen())
529 /// [MS] decl-specifier:
530 /// __declspec ( extended-decl-modifier-seq )
532 /// [MS] extended-decl-modifier-seq:
533 /// extended-decl-modifier[opt]
534 /// extended-decl-modifier extended-decl-modifier-seq
535 void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &Attrs) {
536 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
539 BalancedDelimiterTracker T(*this, tok::l_paren);
540 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
544 // An empty declspec is perfectly legal and should not warn. Additionally,
545 // you can specify multiple attributes per declspec.
546 while (Tok.getKind() != tok::r_paren) {
547 // We expect either a well-known identifier or a generic string. Anything
548 // else is a malformed declspec.
549 bool IsString = Tok.getKind() == tok::string_literal ? true : false;
550 if (!IsString && Tok.getKind() != tok::identifier &&
551 Tok.getKind() != tok::kw_restrict) {
552 Diag(Tok, diag::err_ms_declspec_type);
557 IdentifierInfo *AttrName;
558 SourceLocation AttrNameLoc;
560 SmallString<8> StrBuffer;
561 bool Invalid = false;
562 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
567 AttrName = PP.getIdentifierInfo(Str);
568 AttrNameLoc = ConsumeStringToken();
570 AttrName = Tok.getIdentifierInfo();
571 AttrNameLoc = ConsumeToken();
574 if (IsString || IsSimpleMicrosoftDeclSpec(AttrName))
575 // If we have a generic string, we will allow it because there is no
576 // documented list of allowable string declspecs, but we know they exist
577 // (for instance, SAL declspecs in older versions of MSVC).
579 // Alternatively, if the identifier is a simple one, then it requires no
580 // arguments and can be turned into an attribute directly.
581 Attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 0,
582 AttributeList::AS_Declspec);
584 ParseComplexMicrosoftDeclSpec(AttrName, AttrNameLoc, Attrs);
589 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
590 // Treat these like attributes
591 while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
592 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl) ||
593 Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) ||
594 Tok.is(tok::kw___ptr32) || Tok.is(tok::kw___unaligned) ||
595 Tok.is(tok::kw___sptr) || Tok.is(tok::kw___uptr)) {
596 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
597 SourceLocation AttrNameLoc = ConsumeToken();
598 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 0,
599 AttributeList::AS_Keyword);
603 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
604 // Treat these like attributes
605 while (Tok.is(tok::kw___pascal)) {
606 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
607 SourceLocation AttrNameLoc = ConsumeToken();
608 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 0,
609 AttributeList::AS_Keyword);
613 void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
614 // Treat these like attributes
615 while (Tok.is(tok::kw___kernel)) {
616 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
617 SourceLocation AttrNameLoc = ConsumeToken();
618 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 0,
619 AttributeList::AS_Keyword);
623 void Parser::ParseOpenCLQualifiers(DeclSpec &DS) {
624 // FIXME: The mapping from attribute spelling to semantics should be
625 // performed in Sema, not here.
626 SourceLocation Loc = Tok.getLocation();
627 switch(Tok.getKind()) {
628 // OpenCL qualifiers:
629 case tok::kw___private:
630 case tok::kw_private:
631 DS.getAttributes().addNewInteger(
632 Actions.getASTContext(),
633 PP.getIdentifierInfo("address_space"), Loc, 0);
636 case tok::kw___global:
637 DS.getAttributes().addNewInteger(
638 Actions.getASTContext(),
639 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global);
642 case tok::kw___local:
643 DS.getAttributes().addNewInteger(
644 Actions.getASTContext(),
645 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local);
648 case tok::kw___constant:
649 DS.getAttributes().addNewInteger(
650 Actions.getASTContext(),
651 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant);
654 case tok::kw___read_only:
655 DS.getAttributes().addNewInteger(
656 Actions.getASTContext(),
657 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only);
660 case tok::kw___write_only:
661 DS.getAttributes().addNewInteger(
662 Actions.getASTContext(),
663 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only);
666 case tok::kw___read_write:
667 DS.getAttributes().addNewInteger(
668 Actions.getASTContext(),
669 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write);
675 /// \brief Parse a version number.
679 /// simple-integer ',' simple-integer
680 /// simple-integer ',' simple-integer ',' simple-integer
681 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
682 Range = Tok.getLocation();
684 if (!Tok.is(tok::numeric_constant)) {
685 Diag(Tok, diag::err_expected_version);
686 SkipUntil(tok::comma, tok::r_paren,
687 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
688 return VersionTuple();
691 // Parse the major (and possibly minor and subminor) versions, which
692 // are stored in the numeric constant. We utilize a quirk of the
693 // lexer, which is that it handles something like 1.2.3 as a single
694 // numeric constant, rather than two separate tokens.
695 SmallString<512> Buffer;
696 Buffer.resize(Tok.getLength()+1);
697 const char *ThisTokBegin = &Buffer[0];
699 // Get the spelling of the token, which eliminates trigraphs, etc.
700 bool Invalid = false;
701 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
703 return VersionTuple();
705 // Parse the major version.
706 unsigned AfterMajor = 0;
708 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
709 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
713 if (AfterMajor == 0) {
714 Diag(Tok, diag::err_expected_version);
715 SkipUntil(tok::comma, tok::r_paren,
716 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
717 return VersionTuple();
720 if (AfterMajor == ActualLength) {
723 // We only had a single version component.
725 Diag(Tok, diag::err_zero_version);
726 return VersionTuple();
729 return VersionTuple(Major);
732 if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) {
733 Diag(Tok, diag::err_expected_version);
734 SkipUntil(tok::comma, tok::r_paren,
735 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
736 return VersionTuple();
739 // Parse the minor version.
740 unsigned AfterMinor = AfterMajor + 1;
742 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
743 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
747 if (AfterMinor == ActualLength) {
750 // We had major.minor.
751 if (Major == 0 && Minor == 0) {
752 Diag(Tok, diag::err_zero_version);
753 return VersionTuple();
756 return VersionTuple(Major, Minor);
759 // If what follows is not a '.', we have a problem.
760 if (ThisTokBegin[AfterMinor] != '.') {
761 Diag(Tok, diag::err_expected_version);
762 SkipUntil(tok::comma, tok::r_paren,
763 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
764 return VersionTuple();
767 // Parse the subminor version.
768 unsigned AfterSubminor = AfterMinor + 1;
769 unsigned Subminor = 0;
770 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
771 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
775 if (AfterSubminor != ActualLength) {
776 Diag(Tok, diag::err_expected_version);
777 SkipUntil(tok::comma, tok::r_paren,
778 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
779 return VersionTuple();
782 return VersionTuple(Major, Minor, Subminor);
785 /// \brief Parse the contents of the "availability" attribute.
787 /// availability-attribute:
788 /// 'availability' '(' platform ',' version-arg-list, opt-message')'
793 /// version-arg-list:
795 /// version-arg ',' version-arg-list
798 /// 'introduced' '=' version
799 /// 'deprecated' '=' version
800 /// 'obsoleted' = version
803 /// 'message' '=' <string>
804 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
805 SourceLocation AvailabilityLoc,
806 ParsedAttributes &attrs,
807 SourceLocation *endLoc) {
808 enum { Introduced, Deprecated, Obsoleted, Unknown };
809 AvailabilityChange Changes[Unknown];
810 ExprResult MessageExpr;
813 BalancedDelimiterTracker T(*this, tok::l_paren);
814 if (T.consumeOpen()) {
815 Diag(Tok, diag::err_expected_lparen);
819 // Parse the platform name,
820 if (Tok.isNot(tok::identifier)) {
821 Diag(Tok, diag::err_availability_expected_platform);
822 SkipUntil(tok::r_paren, StopAtSemi);
825 IdentifierLoc *Platform = ParseIdentifierLoc();
827 // Parse the ',' following the platform name.
828 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren))
831 // If we haven't grabbed the pointers for the identifiers
832 // "introduced", "deprecated", and "obsoleted", do so now.
833 if (!Ident_introduced) {
834 Ident_introduced = PP.getIdentifierInfo("introduced");
835 Ident_deprecated = PP.getIdentifierInfo("deprecated");
836 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
837 Ident_unavailable = PP.getIdentifierInfo("unavailable");
838 Ident_message = PP.getIdentifierInfo("message");
841 // Parse the set of introductions/deprecations/removals.
842 SourceLocation UnavailableLoc;
844 if (Tok.isNot(tok::identifier)) {
845 Diag(Tok, diag::err_availability_expected_change);
846 SkipUntil(tok::r_paren, StopAtSemi);
849 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
850 SourceLocation KeywordLoc = ConsumeToken();
852 if (Keyword == Ident_unavailable) {
853 if (UnavailableLoc.isValid()) {
854 Diag(KeywordLoc, diag::err_availability_redundant)
855 << Keyword << SourceRange(UnavailableLoc);
857 UnavailableLoc = KeywordLoc;
859 if (Tok.isNot(tok::comma))
866 if (Tok.isNot(tok::equal)) {
867 Diag(Tok, diag::err_expected_equal_after)
869 SkipUntil(tok::r_paren, StopAtSemi);
873 if (Keyword == Ident_message) {
874 if (Tok.isNot(tok::string_literal)) { // Also reject wide string literals.
875 Diag(Tok, diag::err_expected_string_literal)
876 << /*Source='availability attribute'*/2;
877 SkipUntil(tok::r_paren, StopAtSemi);
880 MessageExpr = ParseStringLiteralExpression();
884 SourceRange VersionRange;
885 VersionTuple Version = ParseVersionTuple(VersionRange);
887 if (Version.empty()) {
888 SkipUntil(tok::r_paren, StopAtSemi);
893 if (Keyword == Ident_introduced)
895 else if (Keyword == Ident_deprecated)
897 else if (Keyword == Ident_obsoleted)
902 if (Index < Unknown) {
903 if (!Changes[Index].KeywordLoc.isInvalid()) {
904 Diag(KeywordLoc, diag::err_availability_redundant)
906 << SourceRange(Changes[Index].KeywordLoc,
907 Changes[Index].VersionRange.getEnd());
910 Changes[Index].KeywordLoc = KeywordLoc;
911 Changes[Index].Version = Version;
912 Changes[Index].VersionRange = VersionRange;
914 Diag(KeywordLoc, diag::err_availability_unknown_change)
915 << Keyword << VersionRange;
918 if (Tok.isNot(tok::comma))
925 if (T.consumeClose())
929 *endLoc = T.getCloseLocation();
931 // The 'unavailable' availability cannot be combined with any other
932 // availability changes. Make sure that hasn't happened.
933 if (UnavailableLoc.isValid()) {
934 bool Complained = false;
935 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
936 if (Changes[Index].KeywordLoc.isValid()) {
938 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
939 << SourceRange(Changes[Index].KeywordLoc,
940 Changes[Index].VersionRange.getEnd());
944 // Clear out the availability.
945 Changes[Index] = AvailabilityChange();
950 // Record this attribute
951 attrs.addNew(&Availability,
952 SourceRange(AvailabilityLoc, T.getCloseLocation()),
958 UnavailableLoc, MessageExpr.take(),
959 AttributeList::AS_GNU);
963 // Late Parsed Attributes:
964 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
966 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
968 void Parser::LateParsedClass::ParseLexedAttributes() {
969 Self->ParseLexedAttributes(*Class);
972 void Parser::LateParsedAttribute::ParseLexedAttributes() {
973 Self->ParseLexedAttribute(*this, true, false);
976 /// Wrapper class which calls ParseLexedAttribute, after setting up the
977 /// scope appropriately.
978 void Parser::ParseLexedAttributes(ParsingClass &Class) {
979 // Deal with templates
980 // FIXME: Test cases to make sure this does the right thing for templates.
981 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
982 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
984 if (HasTemplateScope)
985 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
987 // Set or update the scope flags.
988 bool AlreadyHasClassScope = Class.TopLevelClass;
989 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
990 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
991 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
993 // Enter the scope of nested classes
994 if (!AlreadyHasClassScope)
995 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
996 Class.TagOrTemplate);
997 if (!Class.LateParsedDeclarations.empty()) {
998 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
999 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1003 if (!AlreadyHasClassScope)
1004 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1005 Class.TagOrTemplate);
1009 /// \brief Parse all attributes in LAs, and attach them to Decl D.
1010 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1011 bool EnterScope, bool OnDefinition) {
1012 assert(LAs.parseSoon() &&
1013 "Attribute list should be marked for immediate parsing.");
1014 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1017 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1024 /// \brief Finish parsing an attribute for which parsing was delayed.
1025 /// This will be called at the end of parsing a class declaration
1026 /// for each LateParsedAttribute. We consume the saved tokens and
1027 /// create an attribute with the arguments filled in. We add this
1028 /// to the Attribute list for the decl.
1029 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1030 bool EnterScope, bool OnDefinition) {
1031 // Save the current token position.
1032 SourceLocation OrigLoc = Tok.getLocation();
1034 // Append the current token at the end of the new token stream so that it
1035 // doesn't get lost.
1036 LA.Toks.push_back(Tok);
1037 PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false);
1038 // Consume the previously pushed token.
1039 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1041 if (OnDefinition && !IsThreadSafetyAttribute(LA.AttrName.getName())) {
1042 // FIXME: Do not warn on C++11 attributes, once we start supporting
1044 Diag(Tok, diag::warn_attribute_on_function_definition)
1045 << LA.AttrName.getName();
1048 ParsedAttributes Attrs(AttrFactory);
1049 SourceLocation endLoc;
1051 if (LA.Decls.size() > 0) {
1052 Decl *D = LA.Decls[0];
1053 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1054 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1056 // Allow 'this' within late-parsed attributes.
1057 Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0,
1058 ND && ND->isCXXInstanceMember());
1060 if (LA.Decls.size() == 1) {
1061 // If the Decl is templatized, add template parameters to scope.
1062 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1063 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1064 if (HasTemplateScope)
1065 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1067 // If the Decl is on a function, add function parameters to the scope.
1068 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1069 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunScope);
1071 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1073 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1074 0, SourceLocation(), AttributeList::AS_GNU);
1077 Actions.ActOnExitFunctionContext();
1078 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1080 if (HasTemplateScope) {
1084 // If there are multiple decls, then the decl cannot be within the
1086 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1087 0, SourceLocation(), AttributeList::AS_GNU);
1090 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1093 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i) {
1094 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1097 if (Tok.getLocation() != OrigLoc) {
1098 // Due to a parsing error, we either went over the cached tokens or
1099 // there are still cached tokens left, so we skip the leftover tokens.
1100 // Since this is an uncommon situation that should be avoided, use the
1101 // expensive isBeforeInTranslationUnit call.
1102 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
1104 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
1109 /// \brief Wrapper around a case statement checking if AttrName is
1110 /// one of the thread safety attributes
1111 bool Parser::IsThreadSafetyAttribute(StringRef AttrName) {
1112 return llvm::StringSwitch<bool>(AttrName)
1113 .Case("guarded_by", true)
1114 .Case("guarded_var", true)
1115 .Case("pt_guarded_by", true)
1116 .Case("pt_guarded_var", true)
1117 .Case("lockable", true)
1118 .Case("scoped_lockable", true)
1119 .Case("no_thread_safety_analysis", true)
1120 .Case("acquired_after", true)
1121 .Case("acquired_before", true)
1122 .Case("exclusive_lock_function", true)
1123 .Case("shared_lock_function", true)
1124 .Case("exclusive_trylock_function", true)
1125 .Case("shared_trylock_function", true)
1126 .Case("unlock_function", true)
1127 .Case("lock_returned", true)
1128 .Case("locks_excluded", true)
1129 .Case("exclusive_locks_required", true)
1130 .Case("shared_locks_required", true)
1134 /// \brief Parse the contents of thread safety attributes. These
1135 /// should always be parsed as an expression list.
1137 /// We need to special case the parsing due to the fact that if the first token
1138 /// of the first argument is an identifier, the main parse loop will store
1139 /// that token as a "parameter" and the rest of
1140 /// the arguments will be added to a list of "arguments". However,
1141 /// subsequent tokens in the first argument are lost. We instead parse each
1142 /// argument as an expression and add all arguments to the list of "arguments".
1143 /// In future, we will take advantage of this special case to also
1144 /// deal with some argument scoping issues here (for example, referring to a
1145 /// function parameter in the attribute on that function).
1146 void Parser::ParseThreadSafetyAttribute(IdentifierInfo &AttrName,
1147 SourceLocation AttrNameLoc,
1148 ParsedAttributes &Attrs,
1149 SourceLocation *EndLoc) {
1150 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1152 BalancedDelimiterTracker T(*this, tok::l_paren);
1155 ArgsVector ArgExprs;
1156 bool ArgExprsOk = true;
1158 // now parse the list of expressions
1159 while (Tok.isNot(tok::r_paren)) {
1160 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1161 ExprResult ArgExpr(ParseAssignmentExpression());
1162 if (ArgExpr.isInvalid()) {
1167 ArgExprs.push_back(ArgExpr.release());
1169 if (Tok.isNot(tok::comma))
1171 ConsumeToken(); // Eat the comma, move to the next argument
1174 if (ArgExprsOk && !T.consumeClose()) {
1175 Attrs.addNew(&AttrName, AttrNameLoc, 0, AttrNameLoc, ArgExprs.data(),
1176 ArgExprs.size(), AttributeList::AS_GNU);
1179 *EndLoc = T.getCloseLocation();
1182 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1183 SourceLocation AttrNameLoc,
1184 ParsedAttributes &Attrs,
1185 SourceLocation *EndLoc) {
1186 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1188 BalancedDelimiterTracker T(*this, tok::l_paren);
1191 if (Tok.isNot(tok::identifier)) {
1192 Diag(Tok, diag::err_expected_ident);
1196 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1198 if (Tok.isNot(tok::comma)) {
1199 Diag(Tok, diag::err_expected_comma);
1205 SourceRange MatchingCTypeRange;
1206 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1207 if (MatchingCType.isInvalid()) {
1212 bool LayoutCompatible = false;
1213 bool MustBeNull = false;
1214 while (Tok.is(tok::comma)) {
1216 if (Tok.isNot(tok::identifier)) {
1217 Diag(Tok, diag::err_expected_ident);
1221 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1222 if (Flag->isStr("layout_compatible"))
1223 LayoutCompatible = true;
1224 else if (Flag->isStr("must_be_null"))
1227 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1231 ConsumeToken(); // consume flag
1234 if (!T.consumeClose()) {
1235 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, 0, AttrNameLoc,
1236 ArgumentKind, MatchingCType.release(),
1237 LayoutCompatible, MustBeNull,
1238 AttributeList::AS_GNU);
1242 *EndLoc = T.getCloseLocation();
1245 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1246 /// of a C++11 attribute-specifier in a location where an attribute is not
1247 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1250 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1251 /// this doesn't appear to actually be an attribute-specifier, and the caller
1252 /// should try to parse it.
1253 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1254 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1256 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1257 case CAK_NotAttributeSpecifier:
1258 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1261 case CAK_InvalidAttributeSpecifier:
1262 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1265 case CAK_AttributeSpecifier:
1266 // Parse and discard the attributes.
1267 SourceLocation BeginLoc = ConsumeBracket();
1269 SkipUntil(tok::r_square);
1270 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1271 SourceLocation EndLoc = ConsumeBracket();
1272 Diag(BeginLoc, diag::err_attributes_not_allowed)
1273 << SourceRange(BeginLoc, EndLoc);
1276 llvm_unreachable("All cases handled above.");
1279 /// \brief We have found the opening square brackets of a C++11
1280 /// attribute-specifier in a location where an attribute is not permitted, but
1281 /// we know where the attributes ought to be written. Parse them anyway, and
1282 /// provide a fixit moving them to the right place.
1283 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1284 SourceLocation CorrectLocation) {
1285 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1286 Tok.is(tok::kw_alignas));
1288 // Consume the attributes.
1289 SourceLocation Loc = Tok.getLocation();
1290 ParseCXX11Attributes(Attrs);
1291 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1293 Diag(Loc, diag::err_attributes_not_allowed)
1294 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1295 << FixItHint::CreateRemoval(AttrRange);
1298 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
1299 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
1303 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs) {
1304 AttributeList *AttrList = attrs.getList();
1306 if (AttrList->isCXX11Attribute()) {
1307 Diag(AttrList->getLoc(), diag::err_attribute_not_type_attr)
1308 << AttrList->getName();
1309 AttrList->setInvalid();
1311 AttrList = AttrList->getNext();
1315 /// ParseDeclaration - Parse a full 'declaration', which consists of
1316 /// declaration-specifiers, some number of declarators, and a semicolon.
1317 /// 'Context' should be a Declarator::TheContext value. This returns the
1318 /// location of the semicolon in DeclEnd.
1320 /// declaration: [C99 6.7]
1321 /// block-declaration ->
1322 /// simple-declaration
1324 /// [C++] template-declaration
1325 /// [C++] namespace-definition
1326 /// [C++] using-directive
1327 /// [C++] using-declaration
1328 /// [C++11/C11] static_assert-declaration
1329 /// others... [FIXME]
1331 Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts,
1333 SourceLocation &DeclEnd,
1334 ParsedAttributesWithRange &attrs) {
1335 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1336 // Must temporarily exit the objective-c container scope for
1337 // parsing c none objective-c decls.
1338 ObjCDeclContextSwitch ObjCDC(*this);
1340 Decl *SingleDecl = 0;
1341 Decl *OwnedType = 0;
1342 switch (Tok.getKind()) {
1343 case tok::kw_template:
1344 case tok::kw_export:
1345 ProhibitAttributes(attrs);
1346 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
1348 case tok::kw_inline:
1349 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1350 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1351 ProhibitAttributes(attrs);
1352 SourceLocation InlineLoc = ConsumeToken();
1353 SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc);
1356 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs,
1358 case tok::kw_namespace:
1359 ProhibitAttributes(attrs);
1360 SingleDecl = ParseNamespace(Context, DeclEnd);
1363 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1364 DeclEnd, attrs, &OwnedType);
1366 case tok::kw_static_assert:
1367 case tok::kw__Static_assert:
1368 ProhibitAttributes(attrs);
1369 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1372 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true);
1375 // This routine returns a DeclGroup, if the thing we parsed only contains a
1376 // single decl, convert it now. Alias declarations can also declare a type;
1377 // include that too if it is present.
1378 return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType);
1381 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1382 /// declaration-specifiers init-declarator-list[opt] ';'
1383 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1384 /// init-declarator-list ';'
1385 ///[C90/C++]init-declarator-list ';' [TODO]
1386 /// [OMP] threadprivate-directive [TODO]
1388 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1389 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1391 /// If RequireSemi is false, this does not check for a ';' at the end of the
1392 /// declaration. If it is true, it checks for and eats it.
1394 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1395 /// of a simple-declaration. If we find that we are, we also parse the
1396 /// for-range-initializer, and place it here.
1397 Parser::DeclGroupPtrTy
1398 Parser::ParseSimpleDeclaration(StmtVector &Stmts, unsigned Context,
1399 SourceLocation &DeclEnd,
1400 ParsedAttributesWithRange &Attrs,
1401 bool RequireSemi, ForRangeInit *FRI) {
1402 // Parse the common declaration-specifiers piece.
1403 ParsingDeclSpec DS(*this);
1405 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1406 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1408 // If we had a free-standing type definition with a missing semicolon, we
1409 // may get this far before the problem becomes obvious.
1410 if (DS.hasTagDefinition() &&
1411 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1412 return DeclGroupPtrTy();
1414 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1415 // declaration-specifiers init-declarator-list[opt] ';'
1416 if (Tok.is(tok::semi)) {
1417 ProhibitAttributes(Attrs);
1418 DeclEnd = Tok.getLocation();
1419 if (RequireSemi) ConsumeToken();
1420 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1422 DS.complete(TheDecl);
1423 return Actions.ConvertDeclToDeclGroup(TheDecl);
1426 DS.takeAttributesFrom(Attrs);
1427 return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI);
1430 /// Returns true if this might be the start of a declarator, or a common typo
1431 /// for a declarator.
1432 bool Parser::MightBeDeclarator(unsigned Context) {
1433 switch (Tok.getKind()) {
1434 case tok::annot_cxxscope:
1435 case tok::annot_template_id:
1437 case tok::code_completion:
1438 case tok::coloncolon:
1440 case tok::kw___attribute:
1441 case tok::kw_operator:
1448 return getLangOpts().CPlusPlus;
1450 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1451 return Context == Declarator::MemberContext && getLangOpts().CPlusPlus11 &&
1452 NextToken().is(tok::l_square);
1454 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1455 return Context == Declarator::MemberContext || getLangOpts().CPlusPlus;
1457 case tok::identifier:
1458 switch (NextToken().getKind()) {
1459 case tok::code_completion:
1460 case tok::coloncolon:
1463 case tok::equalequal: // Might be a typo for '='.
1464 case tok::kw_alignas:
1466 case tok::kw___attribute:
1478 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1479 // and in block scope it's probably a label. Inside a class definition,
1480 // this is a bit-field.
1481 return Context == Declarator::MemberContext ||
1482 (getLangOpts().CPlusPlus && Context == Declarator::FileContext);
1484 case tok::identifier: // Possible virt-specifier.
1485 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1496 /// Skip until we reach something which seems like a sensible place to pick
1497 /// up parsing after a malformed declaration. This will sometimes stop sooner
1498 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1499 void Parser::SkipMalformedDecl() {
1501 switch (Tok.getKind()) {
1503 // Skip until matching }, then stop. We've probably skipped over
1504 // a malformed class or function definition or similar.
1506 SkipUntil(tok::r_brace);
1507 if (Tok.is(tok::comma) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try)) {
1508 // This declaration isn't over yet. Keep skipping.
1511 if (Tok.is(tok::semi))
1517 SkipUntil(tok::r_square);
1522 SkipUntil(tok::r_paren);
1532 case tok::kw_inline:
1533 // 'inline namespace' at the start of a line is almost certainly
1534 // a good place to pick back up parsing, except in an Objective-C
1535 // @interface context.
1536 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1537 (!ParsingInObjCContainer || CurParsedObjCImpl))
1541 case tok::kw_namespace:
1542 // 'namespace' at the start of a line is almost certainly a good
1543 // place to pick back up parsing, except in an Objective-C
1544 // @interface context.
1545 if (Tok.isAtStartOfLine() &&
1546 (!ParsingInObjCContainer || CurParsedObjCImpl))
1551 // @end is very much like } in Objective-C contexts.
1552 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1553 ParsingInObjCContainer)
1559 // - and + probably start new method declarations in Objective-C contexts.
1560 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1575 /// ParseDeclGroup - Having concluded that this is either a function
1576 /// definition or a group of object declarations, actually parse the
1578 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1580 bool AllowFunctionDefinitions,
1581 SourceLocation *DeclEnd,
1582 ForRangeInit *FRI) {
1583 // Parse the first declarator.
1584 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
1587 // Bail out if the first declarator didn't seem well-formed.
1588 if (!D.hasName() && !D.mayOmitIdentifier()) {
1589 SkipMalformedDecl();
1590 return DeclGroupPtrTy();
1593 // Save late-parsed attributes for now; they need to be parsed in the
1594 // appropriate function scope after the function Decl has been constructed.
1595 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1596 LateParsedAttrList LateParsedAttrs(true);
1597 if (D.isFunctionDeclarator())
1598 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1600 // Check to see if we have a function *definition* which must have a body.
1601 if (D.isFunctionDeclarator() &&
1602 // Look at the next token to make sure that this isn't a function
1603 // declaration. We have to check this because __attribute__ might be the
1604 // start of a function definition in GCC-extended K&R C.
1605 !isDeclarationAfterDeclarator()) {
1607 if (AllowFunctionDefinitions) {
1608 if (isStartOfFunctionDefinition(D)) {
1609 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1610 Diag(Tok, diag::err_function_declared_typedef);
1612 // Recover by treating the 'typedef' as spurious.
1613 DS.ClearStorageClassSpecs();
1617 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1618 return Actions.ConvertDeclToDeclGroup(TheDecl);
1621 if (isDeclarationSpecifier()) {
1622 // If there is an invalid declaration specifier right after the function
1623 // prototype, then we must be in a missing semicolon case where this isn't
1624 // actually a body. Just fall through into the code that handles it as a
1625 // prototype, and let the top-level code handle the erroneous declspec
1626 // where it would otherwise expect a comma or semicolon.
1628 Diag(Tok, diag::err_expected_fn_body);
1629 SkipUntil(tok::semi);
1630 return DeclGroupPtrTy();
1633 if (Tok.is(tok::l_brace)) {
1634 Diag(Tok, diag::err_function_definition_not_allowed);
1635 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1640 if (ParseAsmAttributesAfterDeclarator(D))
1641 return DeclGroupPtrTy();
1643 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1644 // must parse and analyze the for-range-initializer before the declaration is
1647 // Handle the Objective-C for-in loop variable similarly, although we
1648 // don't need to parse the container in advance.
1649 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
1650 bool IsForRangeLoop = false;
1651 if (Tok.is(tok::colon)) {
1652 IsForRangeLoop = true;
1653 FRI->ColonLoc = ConsumeToken();
1654 if (Tok.is(tok::l_brace))
1655 FRI->RangeExpr = ParseBraceInitializer();
1657 FRI->RangeExpr = ParseExpression();
1660 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1662 Actions.ActOnCXXForRangeDecl(ThisDecl);
1663 Actions.FinalizeDeclaration(ThisDecl);
1664 D.complete(ThisDecl);
1665 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
1668 SmallVector<Decl *, 8> DeclsInGroup;
1669 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(D);
1670 if (LateParsedAttrs.size() > 0)
1671 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
1672 D.complete(FirstDecl);
1674 DeclsInGroup.push_back(FirstDecl);
1676 bool ExpectSemi = Context != Declarator::ForContext;
1678 // If we don't have a comma, it is either the end of the list (a ';') or an
1680 while (Tok.is(tok::comma)) {
1681 SourceLocation CommaLoc = ConsumeToken();
1683 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
1684 // This comma was followed by a line-break and something which can't be
1685 // the start of a declarator. The comma was probably a typo for a
1687 Diag(CommaLoc, diag::err_expected_semi_declaration)
1688 << FixItHint::CreateReplacement(CommaLoc, ";");
1693 // Parse the next declarator.
1695 D.setCommaLoc(CommaLoc);
1697 // Accept attributes in an init-declarator. In the first declarator in a
1698 // declaration, these would be part of the declspec. In subsequent
1699 // declarators, they become part of the declarator itself, so that they
1700 // don't apply to declarators after *this* one. Examples:
1701 // short __attribute__((common)) var; -> declspec
1702 // short var __attribute__((common)); -> declarator
1703 // short x, __attribute__((common)) var; -> declarator
1704 MaybeParseGNUAttributes(D);
1707 if (!D.isInvalidType()) {
1708 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
1709 D.complete(ThisDecl);
1711 DeclsInGroup.push_back(ThisDecl);
1716 *DeclEnd = Tok.getLocation();
1719 ExpectAndConsumeSemi(Context == Declarator::FileContext
1720 ? diag::err_invalid_token_after_toplevel_declarator
1721 : diag::err_expected_semi_declaration)) {
1722 // Okay, there was no semicolon and one was expected. If we see a
1723 // declaration specifier, just assume it was missing and continue parsing.
1724 // Otherwise things are very confused and we skip to recover.
1725 if (!isDeclarationSpecifier()) {
1726 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1727 if (Tok.is(tok::semi))
1732 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
1735 /// Parse an optional simple-asm-expr and attributes, and attach them to a
1736 /// declarator. Returns true on an error.
1737 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
1738 // If a simple-asm-expr is present, parse it.
1739 if (Tok.is(tok::kw_asm)) {
1741 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1742 if (AsmLabel.isInvalid()) {
1743 SkipUntil(tok::semi, StopBeforeMatch);
1747 D.setAsmLabel(AsmLabel.release());
1751 MaybeParseGNUAttributes(D);
1755 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
1756 /// declarator'. This method parses the remainder of the declaration
1757 /// (including any attributes or initializer, among other things) and
1758 /// finalizes the declaration.
1760 /// init-declarator: [C99 6.7]
1762 /// declarator '=' initializer
1763 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
1764 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
1765 /// [C++] declarator initializer[opt]
1767 /// [C++] initializer:
1768 /// [C++] '=' initializer-clause
1769 /// [C++] '(' expression-list ')'
1770 /// [C++0x] '=' 'default' [TODO]
1771 /// [C++0x] '=' 'delete'
1772 /// [C++0x] braced-init-list
1774 /// According to the standard grammar, =default and =delete are function
1775 /// definitions, but that definitely doesn't fit with the parser here.
1777 Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D,
1778 const ParsedTemplateInfo &TemplateInfo) {
1779 if (ParseAsmAttributesAfterDeclarator(D))
1782 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
1785 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
1786 const ParsedTemplateInfo &TemplateInfo) {
1787 // Inform the current actions module that we just parsed this declarator.
1789 switch (TemplateInfo.Kind) {
1790 case ParsedTemplateInfo::NonTemplate:
1791 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1794 case ParsedTemplateInfo::Template:
1795 case ParsedTemplateInfo::ExplicitSpecialization: {
1796 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
1797 *TemplateInfo.TemplateParams,
1799 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
1800 // Re-direct this decl to refer to the templated decl so that we can
1802 ThisDecl = VT->getTemplatedDecl();
1805 case ParsedTemplateInfo::ExplicitInstantiation: {
1806 if (Tok.is(tok::semi)) {
1807 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
1808 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
1809 if (ThisRes.isInvalid()) {
1810 SkipUntil(tok::semi, StopBeforeMatch);
1813 ThisDecl = ThisRes.get();
1815 // FIXME: This check should be for a variable template instantiation only.
1817 // Check that this is a valid instantiation
1818 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
1819 // If the declarator-id is not a template-id, issue a diagnostic and
1820 // recover by ignoring the 'template' keyword.
1821 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1822 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1823 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1825 SourceLocation LAngleLoc =
1826 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1827 Diag(D.getIdentifierLoc(),
1828 diag::err_explicit_instantiation_with_definition)
1829 << SourceRange(TemplateInfo.TemplateLoc)
1830 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1832 // Recover as if it were an explicit specialization.
1833 TemplateParameterLists FakedParamLists;
1834 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1835 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, 0, 0,
1839 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
1846 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
1848 // Parse declarator '=' initializer.
1849 // If a '==' or '+=' is found, suggest a fixit to '='.
1850 if (isTokenEqualOrEqualTypo()) {
1853 if (Tok.is(tok::kw_delete)) {
1854 if (D.isFunctionDeclarator())
1855 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1858 Diag(ConsumeToken(), diag::err_deleted_non_function);
1859 } else if (Tok.is(tok::kw_default)) {
1860 if (D.isFunctionDeclarator())
1861 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1864 Diag(ConsumeToken(), diag::err_default_special_members);
1866 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1868 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1871 if (Tok.is(tok::code_completion)) {
1872 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
1873 Actions.FinalizeDeclaration(ThisDecl);
1878 ExprResult Init(ParseInitializer());
1880 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1881 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1885 if (Init.isInvalid()) {
1886 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
1887 Actions.ActOnInitializerError(ThisDecl);
1889 Actions.AddInitializerToDecl(ThisDecl, Init.take(),
1890 /*DirectInit=*/false, TypeContainsAuto);
1892 } else if (Tok.is(tok::l_paren)) {
1893 // Parse C++ direct initializer: '(' expression-list ')'
1894 BalancedDelimiterTracker T(*this, tok::l_paren);
1898 CommaLocsTy CommaLocs;
1900 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1902 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1905 if (ParseExpressionList(Exprs, CommaLocs)) {
1906 Actions.ActOnInitializerError(ThisDecl);
1907 SkipUntil(tok::r_paren, StopAtSemi);
1909 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1910 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1917 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
1918 "Unexpected number of commas!");
1920 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1921 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1925 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
1926 T.getCloseLocation(),
1928 Actions.AddInitializerToDecl(ThisDecl, Initializer.take(),
1929 /*DirectInit=*/true, TypeContainsAuto);
1931 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
1932 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
1933 // Parse C++0x braced-init-list.
1934 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1936 if (D.getCXXScopeSpec().isSet()) {
1938 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1941 ExprResult Init(ParseBraceInitializer());
1943 if (D.getCXXScopeSpec().isSet()) {
1944 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1948 if (Init.isInvalid()) {
1949 Actions.ActOnInitializerError(ThisDecl);
1951 Actions.AddInitializerToDecl(ThisDecl, Init.take(),
1952 /*DirectInit=*/true, TypeContainsAuto);
1955 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
1958 Actions.FinalizeDeclaration(ThisDecl);
1963 /// ParseSpecifierQualifierList
1964 /// specifier-qualifier-list:
1965 /// type-specifier specifier-qualifier-list[opt]
1966 /// type-qualifier specifier-qualifier-list[opt]
1967 /// [GNU] attributes specifier-qualifier-list[opt]
1969 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
1970 DeclSpecContext DSC) {
1971 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
1972 /// parse declaration-specifiers and complain about extra stuff.
1973 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
1974 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
1976 // Validate declspec for type-name.
1977 unsigned Specs = DS.getParsedSpecifiers();
1978 if ((DSC == DSC_type_specifier || DSC == DSC_trailing) &&
1979 !DS.hasTypeSpecifier()) {
1980 Diag(Tok, diag::err_expected_type);
1981 DS.SetTypeSpecError();
1982 } else if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
1983 !DS.hasAttributes()) {
1984 Diag(Tok, diag::err_typename_requires_specqual);
1985 if (!DS.hasTypeSpecifier())
1986 DS.SetTypeSpecError();
1989 // Issue diagnostic and remove storage class if present.
1990 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
1991 if (DS.getStorageClassSpecLoc().isValid())
1992 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
1994 Diag(DS.getThreadStorageClassSpecLoc(),
1995 diag::err_typename_invalid_storageclass);
1996 DS.ClearStorageClassSpecs();
1999 // Issue diagnostic and remove function specfier if present.
2000 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2001 if (DS.isInlineSpecified())
2002 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2003 if (DS.isVirtualSpecified())
2004 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2005 if (DS.isExplicitSpecified())
2006 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2007 DS.ClearFunctionSpecs();
2010 // Issue diagnostic and remove constexpr specfier if present.
2011 if (DS.isConstexprSpecified()) {
2012 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2013 DS.ClearConstexprSpec();
2017 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2018 /// specified token is valid after the identifier in a declarator which
2019 /// immediately follows the declspec. For example, these things are valid:
2021 /// int x [ 4]; // direct-declarator
2022 /// int x ( int y); // direct-declarator
2023 /// int(int x ) // direct-declarator
2024 /// int x ; // simple-declaration
2025 /// int x = 17; // init-declarator-list
2026 /// int x , y; // init-declarator-list
2027 /// int x __asm__ ("foo"); // init-declarator-list
2028 /// int x : 4; // struct-declarator
2029 /// int x { 5}; // C++'0x unified initializers
2031 /// This is not, because 'x' does not immediately follow the declspec (though
2032 /// ')' happens to be valid anyway).
2035 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2036 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
2037 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
2038 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
2042 /// ParseImplicitInt - This method is called when we have an non-typename
2043 /// identifier in a declspec (which normally terminates the decl spec) when
2044 /// the declspec has no type specifier. In this case, the declspec is either
2045 /// malformed or is "implicit int" (in K&R and C89).
2047 /// This method handles diagnosing this prettily and returns false if the
2048 /// declspec is done being processed. If it recovers and thinks there may be
2049 /// other pieces of declspec after it, it returns true.
2051 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2052 const ParsedTemplateInfo &TemplateInfo,
2053 AccessSpecifier AS, DeclSpecContext DSC,
2054 ParsedAttributesWithRange &Attrs) {
2055 assert(Tok.is(tok::identifier) && "should have identifier");
2057 SourceLocation Loc = Tok.getLocation();
2058 // If we see an identifier that is not a type name, we normally would
2059 // parse it as the identifer being declared. However, when a typename
2060 // is typo'd or the definition is not included, this will incorrectly
2061 // parse the typename as the identifier name and fall over misparsing
2062 // later parts of the diagnostic.
2064 // As such, we try to do some look-ahead in cases where this would
2065 // otherwise be an "implicit-int" case to see if this is invalid. For
2066 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2067 // an identifier with implicit int, we'd get a parse error because the
2068 // next token is obviously invalid for a type. Parse these as a case
2069 // with an invalid type specifier.
2070 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2072 // Since we know that this either implicit int (which is rare) or an
2073 // error, do lookahead to try to do better recovery. This never applies
2074 // within a type specifier. Outside of C++, we allow this even if the
2075 // language doesn't "officially" support implicit int -- we support
2076 // implicit int as an extension in C99 and C11.
2077 if (DSC != DSC_type_specifier && DSC != DSC_trailing &&
2078 !getLangOpts().CPlusPlus &&
2079 isValidAfterIdentifierInDeclarator(NextToken())) {
2080 // If this token is valid for implicit int, e.g. "static x = 4", then
2081 // we just avoid eating the identifier, so it will be parsed as the
2082 // identifier in the declarator.
2086 if (getLangOpts().CPlusPlus &&
2087 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2088 // Don't require a type specifier if we have the 'auto' storage class
2089 // specifier in C++98 -- we'll promote it to a type specifier.
2091 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2095 // Otherwise, if we don't consume this token, we are going to emit an
2096 // error anyway. Try to recover from various common problems. Check
2097 // to see if this was a reference to a tag name without a tag specified.
2098 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2100 // C++ doesn't need this, and isTagName doesn't take SS.
2102 const char *TagName = 0, *FixitTagName = 0;
2103 tok::TokenKind TagKind = tok::unknown;
2105 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2107 case DeclSpec::TST_enum:
2108 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2109 case DeclSpec::TST_union:
2110 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2111 case DeclSpec::TST_struct:
2112 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2113 case DeclSpec::TST_interface:
2114 TagName="__interface"; FixitTagName = "__interface ";
2115 TagKind=tok::kw___interface;break;
2116 case DeclSpec::TST_class:
2117 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2121 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2122 LookupResult R(Actions, TokenName, SourceLocation(),
2123 Sema::LookupOrdinaryName);
2125 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2126 << TokenName << TagName << getLangOpts().CPlusPlus
2127 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2129 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2130 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2132 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2133 << TokenName << TagName;
2136 // Parse this as a tag as if the missing tag were present.
2137 if (TagKind == tok::kw_enum)
2138 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
2140 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2141 /*EnteringContext*/ false, DSC_normal, Attrs);
2146 // Determine whether this identifier could plausibly be the name of something
2147 // being declared (with a missing type).
2148 if (DSC != DSC_type_specifier && DSC != DSC_trailing &&
2149 (!SS || DSC == DSC_top_level || DSC == DSC_class)) {
2150 // Look ahead to the next token to try to figure out what this declaration
2151 // was supposed to be.
2152 switch (NextToken().getKind()) {
2153 case tok::l_paren: {
2154 // static x(4); // 'x' is not a type
2155 // x(int n); // 'x' is not a type
2156 // x (*p)[]; // 'x' is a type
2158 // Since we're in an error case (or the rare 'implicit int in C++' MS
2159 // extension), we can afford to perform a tentative parse to determine
2160 // which case we're in.
2161 TentativeParsingAction PA(*this);
2163 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2166 if (TPR != TPResult::False()) {
2167 // The identifier is followed by a parenthesized declarator.
2168 // It's supposed to be a type.
2172 // If we're in a context where we could be declaring a constructor,
2173 // check whether this is a constructor declaration with a bogus name.
2174 if (DSC == DSC_class || (DSC == DSC_top_level && SS)) {
2175 IdentifierInfo *II = Tok.getIdentifierInfo();
2176 if (Actions.isCurrentClassNameTypo(II, SS)) {
2177 Diag(Loc, diag::err_constructor_bad_name)
2178 << Tok.getIdentifierInfo() << II
2179 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2180 Tok.setIdentifierInfo(II);
2191 // This looks like a variable or function declaration. The type is
2192 // probably missing. We're done parsing decl-specifiers.
2194 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2198 // This is probably supposed to be a type. This includes cases like:
2200 // struct S { unsinged : 4; };
2205 // This is almost certainly an invalid type name. Let the action emit a
2206 // diagnostic and attempt to recover.
2208 IdentifierInfo *II = Tok.getIdentifierInfo();
2209 if (Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T)) {
2210 // The action emitted a diagnostic, so we don't have to.
2212 // The action has suggested that the type T could be used. Set that as
2213 // the type in the declaration specifiers, consume the would-be type
2214 // name token, and we're done.
2215 const char *PrevSpec;
2217 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T);
2218 DS.SetRangeEnd(Tok.getLocation());
2220 // There may be other declaration specifiers after this.
2222 } else if (II != Tok.getIdentifierInfo()) {
2223 // If no type was suggested, the correction is to a keyword
2224 Tok.setKind(II->getTokenID());
2225 // There may be other declaration specifiers after this.
2229 // Fall through; the action had no suggestion for us.
2231 // The action did not emit a diagnostic, so emit one now.
2233 if (SS) R = SS->getRange();
2234 Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
2237 // Mark this as an error.
2238 DS.SetTypeSpecError();
2239 DS.SetRangeEnd(Tok.getLocation());
2242 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2243 // avoid rippling error messages on subsequent uses of the same type,
2244 // could be useful if #include was forgotten.
2248 /// \brief Determine the declaration specifier context from the declarator
2251 /// \param Context the declarator context, which is one of the
2252 /// Declarator::TheContext enumerator values.
2253 Parser::DeclSpecContext
2254 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
2255 if (Context == Declarator::MemberContext)
2257 if (Context == Declarator::FileContext)
2258 return DSC_top_level;
2259 if (Context == Declarator::TrailingReturnContext)
2260 return DSC_trailing;
2264 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2266 /// FIXME: Simply returns an alignof() expression if the argument is a
2267 /// type. Ideally, the type should be propagated directly into Sema.
2270 /// [C11] constant-expression
2271 /// [C++0x] type-id ...[opt]
2272 /// [C++0x] assignment-expression ...[opt]
2273 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2274 SourceLocation &EllipsisLoc) {
2276 if (isTypeIdInParens()) {
2277 SourceLocation TypeLoc = Tok.getLocation();
2278 ParsedType Ty = ParseTypeName().get();
2279 SourceRange TypeRange(Start, Tok.getLocation());
2280 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2281 Ty.getAsOpaquePtr(), TypeRange);
2283 ER = ParseConstantExpression();
2285 if (getLangOpts().CPlusPlus11 && Tok.is(tok::ellipsis))
2286 EllipsisLoc = ConsumeToken();
2291 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2292 /// attribute to Attrs.
2294 /// alignment-specifier:
2295 /// [C11] '_Alignas' '(' type-id ')'
2296 /// [C11] '_Alignas' '(' constant-expression ')'
2297 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2298 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2299 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2300 SourceLocation *EndLoc) {
2301 assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) &&
2302 "Not an alignment-specifier!");
2304 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2305 SourceLocation KWLoc = ConsumeToken();
2307 BalancedDelimiterTracker T(*this, tok::l_paren);
2308 if (T.expectAndConsume(diag::err_expected_lparen))
2311 SourceLocation EllipsisLoc;
2312 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2313 if (ArgExpr.isInvalid()) {
2320 *EndLoc = T.getCloseLocation();
2322 ArgsVector ArgExprs;
2323 ArgExprs.push_back(ArgExpr.release());
2324 Attrs.addNew(KWName, KWLoc, 0, KWLoc, ArgExprs.data(), 1,
2325 AttributeList::AS_Keyword, EllipsisLoc);
2328 /// Determine whether we're looking at something that might be a declarator
2329 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2330 /// diagnose a missing semicolon after a prior tag definition in the decl
2333 /// \return \c true if an error occurred and this can't be any kind of
2336 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2337 DeclSpecContext DSContext,
2338 LateParsedAttrList *LateAttrs) {
2339 assert(DS.hasTagDefinition() && "shouldn't call this");
2341 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2342 bool HasMissingSemi = false;
2344 if (getLangOpts().CPlusPlus &&
2345 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
2346 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id)) &&
2347 TryAnnotateCXXScopeToken(EnteringContext)) {
2348 SkipMalformedDecl();
2352 // Determine whether the following tokens could possibly be a
2354 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
2355 const Token &Next = NextToken();
2356 // These tokens cannot come after the declarator-id in a
2357 // simple-declaration, and are likely to come after a type-specifier.
2358 HasMissingSemi = Next.is(tok::star) || Next.is(tok::amp) ||
2359 Next.is(tok::ampamp) || Next.is(tok::identifier) ||
2360 Next.is(tok::annot_cxxscope) ||
2361 Next.is(tok::coloncolon);
2362 } else if (Tok.is(tok::annot_cxxscope) &&
2363 NextToken().is(tok::identifier) &&
2364 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
2365 // We almost certainly have a missing semicolon. Look up the name and
2366 // check; if it names a type, we're missing a semicolon.
2368 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2369 Tok.getAnnotationRange(), SS);
2370 const Token &Next = NextToken();
2371 IdentifierInfo *Name = Next.getIdentifierInfo();
2372 Sema::NameClassification Classification =
2373 Actions.ClassifyName(getCurScope(), SS, Name, Next.getLocation(),
2374 NextToken(), /*IsAddressOfOperand*/false);
2375 switch (Classification.getKind()) {
2376 case Sema::NC_Error:
2377 SkipMalformedDecl();
2380 case Sema::NC_Keyword:
2381 case Sema::NC_NestedNameSpecifier:
2382 llvm_unreachable("typo correction and nested name specifiers not "
2386 case Sema::NC_TypeTemplate:
2387 // Not a previously-declared non-type entity.
2388 HasMissingSemi = true;
2391 case Sema::NC_Unknown:
2392 case Sema::NC_Expression:
2393 case Sema::NC_VarTemplate:
2394 case Sema::NC_FunctionTemplate:
2395 // Might be a redeclaration of a prior entity.
2396 HasMissingSemi = false;
2399 } else if (Tok.is(tok::kw_typename) || Tok.is(tok::annot_typename)) {
2400 HasMissingSemi = true;
2403 if (!HasMissingSemi)
2406 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()),
2407 diag::err_expected_semi_after_tagdecl)
2408 << DeclSpec::getSpecifierName(DS.getTypeSpecType());
2410 // Try to recover from the typo, by dropping the tag definition and parsing
2411 // the problematic tokens as a type.
2413 // FIXME: Split the DeclSpec into pieces for the standalone
2414 // declaration and pieces for the following declaration, instead
2415 // of assuming that all the other pieces attach to new declaration,
2416 // and call ParsedFreeStandingDeclSpec as appropriate.
2417 DS.ClearTypeSpecType();
2418 ParsedTemplateInfo NotATemplate;
2419 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2423 /// ParseDeclarationSpecifiers
2424 /// declaration-specifiers: [C99 6.7]
2425 /// storage-class-specifier declaration-specifiers[opt]
2426 /// type-specifier declaration-specifiers[opt]
2427 /// [C99] function-specifier declaration-specifiers[opt]
2428 /// [C11] alignment-specifier declaration-specifiers[opt]
2429 /// [GNU] attributes declaration-specifiers[opt]
2430 /// [Clang] '__module_private__' declaration-specifiers[opt]
2432 /// storage-class-specifier: [C99 6.7.1]
2439 /// [C++11] 'thread_local'
2440 /// [C11] '_Thread_local'
2441 /// [GNU] '__thread'
2442 /// function-specifier: [C99 6.7.4]
2445 /// [C++] 'explicit'
2446 /// [OpenCL] '__kernel'
2447 /// 'friend': [C++ dcl.friend]
2448 /// 'constexpr': [C++0x dcl.constexpr]
2451 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2452 const ParsedTemplateInfo &TemplateInfo,
2454 DeclSpecContext DSContext,
2455 LateParsedAttrList *LateAttrs) {
2456 if (DS.getSourceRange().isInvalid()) {
2457 DS.SetRangeStart(Tok.getLocation());
2458 DS.SetRangeEnd(Tok.getLocation());
2461 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2462 bool AttrsLastTime = false;
2463 ParsedAttributesWithRange attrs(AttrFactory);
2465 bool isInvalid = false;
2466 const char *PrevSpec = 0;
2467 unsigned DiagID = 0;
2469 SourceLocation Loc = Tok.getLocation();
2471 switch (Tok.getKind()) {
2475 ProhibitAttributes(attrs);
2477 // Reject C++11 attributes that appertain to decl specifiers as
2478 // we don't support any C++11 attributes that appertain to decl
2479 // specifiers. This also conforms to what g++ 4.8 is doing.
2480 ProhibitCXX11Attributes(attrs);
2482 DS.takeAttributesFrom(attrs);
2485 // If this is not a declaration specifier token, we're done reading decl
2486 // specifiers. First verify that DeclSpec's are consistent.
2487 DS.Finish(Diags, PP);
2491 case tok::kw_alignas:
2492 if (!getLangOpts().CPlusPlus11 || !isCXX11AttributeSpecifier())
2493 goto DoneWithDeclSpec;
2495 ProhibitAttributes(attrs);
2496 // FIXME: It would be good to recover by accepting the attributes,
2497 // but attempting to do that now would cause serious
2498 // madness in terms of diagnostics.
2500 attrs.Range = SourceRange();
2502 ParseCXX11Attributes(attrs);
2503 AttrsLastTime = true;
2506 case tok::code_completion: {
2507 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2508 if (DS.hasTypeSpecifier()) {
2509 bool AllowNonIdentifiers
2510 = (getCurScope()->getFlags() & (Scope::ControlScope |
2512 Scope::TemplateParamScope |
2513 Scope::FunctionPrototypeScope |
2514 Scope::AtCatchScope)) == 0;
2515 bool AllowNestedNameSpecifiers
2516 = DSContext == DSC_top_level ||
2517 (DSContext == DSC_class && DS.isFriendSpecified());
2519 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
2520 AllowNonIdentifiers,
2521 AllowNestedNameSpecifiers);
2522 return cutOffParsing();
2525 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
2526 CCC = Sema::PCC_LocalDeclarationSpecifiers;
2527 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
2528 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
2529 : Sema::PCC_Template;
2530 else if (DSContext == DSC_class)
2531 CCC = Sema::PCC_Class;
2532 else if (CurParsedObjCImpl)
2533 CCC = Sema::PCC_ObjCImplementation;
2535 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
2536 return cutOffParsing();
2539 case tok::coloncolon: // ::foo::bar
2540 // C++ scope specifier. Annotate and loop, or bail out on error.
2541 if (TryAnnotateCXXScopeToken(EnteringContext)) {
2542 if (!DS.hasTypeSpecifier())
2543 DS.SetTypeSpecError();
2544 goto DoneWithDeclSpec;
2546 if (Tok.is(tok::coloncolon)) // ::new or ::delete
2547 goto DoneWithDeclSpec;
2550 case tok::annot_cxxscope: {
2551 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
2552 goto DoneWithDeclSpec;
2555 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2556 Tok.getAnnotationRange(),
2559 // We are looking for a qualified typename.
2560 Token Next = NextToken();
2561 if (Next.is(tok::annot_template_id) &&
2562 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
2563 ->Kind == TNK_Type_template) {
2564 // We have a qualified template-id, e.g., N::A<int>
2566 // C++ [class.qual]p2:
2567 // In a lookup in which the constructor is an acceptable lookup
2568 // result and the nested-name-specifier nominates a class C:
2570 // - if the name specified after the
2571 // nested-name-specifier, when looked up in C, is the
2572 // injected-class-name of C (Clause 9), or
2574 // - if the name specified after the nested-name-specifier
2575 // is the same as the identifier or the
2576 // simple-template-id's template-name in the last
2577 // component of the nested-name-specifier,
2579 // the name is instead considered to name the constructor of
2582 // Thus, if the template-name is actually the constructor
2583 // name, then the code is ill-formed; this interpretation is
2584 // reinforced by the NAD status of core issue 635.
2585 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
2586 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2588 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2589 if (isConstructorDeclarator()) {
2590 // The user meant this to be an out-of-line constructor
2591 // definition, but template arguments are not allowed
2592 // there. Just allow this as a constructor; we'll
2593 // complain about it later.
2594 goto DoneWithDeclSpec;
2597 // The user meant this to name a type, but it actually names
2598 // a constructor with some extraneous template
2599 // arguments. Complain, then parse it as a type as the user
2601 Diag(TemplateId->TemplateNameLoc,
2602 diag::err_out_of_line_template_id_names_constructor)
2603 << TemplateId->Name;
2606 DS.getTypeSpecScope() = SS;
2607 ConsumeToken(); // The C++ scope.
2608 assert(Tok.is(tok::annot_template_id) &&
2609 "ParseOptionalCXXScopeSpecifier not working");
2610 AnnotateTemplateIdTokenAsType();
2614 if (Next.is(tok::annot_typename)) {
2615 DS.getTypeSpecScope() = SS;
2616 ConsumeToken(); // The C++ scope.
2617 if (Tok.getAnnotationValue()) {
2618 ParsedType T = getTypeAnnotation(Tok);
2619 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
2620 Tok.getAnnotationEndLoc(),
2621 PrevSpec, DiagID, T);
2626 DS.SetTypeSpecError();
2627 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2628 ConsumeToken(); // The typename
2631 if (Next.isNot(tok::identifier))
2632 goto DoneWithDeclSpec;
2634 // If we're in a context where the identifier could be a class name,
2635 // check whether this is a constructor declaration.
2636 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2637 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
2639 if (isConstructorDeclarator())
2640 goto DoneWithDeclSpec;
2642 // As noted in C++ [class.qual]p2 (cited above), when the name
2643 // of the class is qualified in a context where it could name
2644 // a constructor, its a constructor name. However, we've
2645 // looked at the declarator, and the user probably meant this
2646 // to be a type. Complain that it isn't supposed to be treated
2647 // as a type, then proceed to parse it as a type.
2648 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
2649 << Next.getIdentifierInfo();
2652 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
2655 false, false, ParsedType(),
2656 /*IsCtorOrDtorName=*/false,
2657 /*NonTrivialSourceInfo=*/true);
2659 // If the referenced identifier is not a type, then this declspec is
2660 // erroneous: We already checked about that it has no type specifier, and
2661 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
2664 ConsumeToken(); // Eat the scope spec so the identifier is current.
2665 ParsedAttributesWithRange Attrs(AttrFactory);
2666 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
2667 if (!Attrs.empty()) {
2668 AttrsLastTime = true;
2669 attrs.takeAllFrom(Attrs);
2673 goto DoneWithDeclSpec;
2676 DS.getTypeSpecScope() = SS;
2677 ConsumeToken(); // The C++ scope.
2679 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2684 DS.SetRangeEnd(Tok.getLocation());
2685 ConsumeToken(); // The typename.
2690 case tok::annot_typename: {
2691 // If we've previously seen a tag definition, we were almost surely
2692 // missing a semicolon after it.
2693 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
2694 goto DoneWithDeclSpec;
2696 if (Tok.getAnnotationValue()) {
2697 ParsedType T = getTypeAnnotation(Tok);
2698 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2701 DS.SetTypeSpecError();
2706 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2707 ConsumeToken(); // The typename
2709 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2710 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2711 // Objective-C interface.
2712 if (Tok.is(tok::less) && getLangOpts().ObjC1)
2713 ParseObjCProtocolQualifiers(DS);
2718 case tok::kw___is_signed:
2719 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
2720 // typically treats it as a trait. If we see __is_signed as it appears
2721 // in libstdc++, e.g.,
2723 // static const bool __is_signed;
2725 // then treat __is_signed as an identifier rather than as a keyword.
2726 if (DS.getTypeSpecType() == TST_bool &&
2727 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
2728 DS.getStorageClassSpec() == DeclSpec::SCS_static)
2729 TryKeywordIdentFallback(true);
2731 // We're done with the declaration-specifiers.
2732 goto DoneWithDeclSpec;
2735 case tok::kw_decltype:
2736 case tok::identifier: {
2737 // In C++, check to see if this is a scope specifier like foo::bar::, if
2738 // so handle it as such. This is important for ctor parsing.
2739 if (getLangOpts().CPlusPlus) {
2740 if (TryAnnotateCXXScopeToken(EnteringContext)) {
2741 if (!DS.hasTypeSpecifier())
2742 DS.SetTypeSpecError();
2743 goto DoneWithDeclSpec;
2745 if (!Tok.is(tok::identifier))
2749 // This identifier can only be a typedef name if we haven't already seen
2750 // a type-specifier. Without this check we misparse:
2751 // typedef int X; struct Y { short X; }; as 'short int'.
2752 if (DS.hasTypeSpecifier())
2753 goto DoneWithDeclSpec;
2755 // Check for need to substitute AltiVec keyword tokens.
2756 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
2759 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
2760 // allow the use of a typedef name as a type specifier.
2761 if (DS.isTypeAltiVecVector())
2762 goto DoneWithDeclSpec;
2764 ParsedType TypeRep =
2765 Actions.getTypeName(*Tok.getIdentifierInfo(),
2766 Tok.getLocation(), getCurScope());
2768 // If this is not a typedef name, don't parse it as part of the declspec,
2769 // it must be an implicit int or an error.
2771 ParsedAttributesWithRange Attrs(AttrFactory);
2772 if (ParseImplicitInt(DS, 0, TemplateInfo, AS, DSContext, Attrs)) {
2773 if (!Attrs.empty()) {
2774 AttrsLastTime = true;
2775 attrs.takeAllFrom(Attrs);
2779 goto DoneWithDeclSpec;
2782 // If we're in a context where the identifier could be a class name,
2783 // check whether this is a constructor declaration.
2784 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2785 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
2786 isConstructorDeclarator())
2787 goto DoneWithDeclSpec;
2789 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2794 DS.SetRangeEnd(Tok.getLocation());
2795 ConsumeToken(); // The identifier
2797 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2798 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2799 // Objective-C interface.
2800 if (Tok.is(tok::less) && getLangOpts().ObjC1)
2801 ParseObjCProtocolQualifiers(DS);
2803 // Need to support trailing type qualifiers (e.g. "id<p> const").
2804 // If a type specifier follows, it will be diagnosed elsewhere.
2809 case tok::annot_template_id: {
2810 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2811 if (TemplateId->Kind != TNK_Type_template) {
2812 // This template-id does not refer to a type name, so we're
2813 // done with the type-specifiers.
2814 goto DoneWithDeclSpec;
2817 // If we're in a context where the template-id could be a
2818 // constructor name or specialization, check whether this is a
2819 // constructor declaration.
2820 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2821 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
2822 isConstructorDeclarator())
2823 goto DoneWithDeclSpec;
2825 // Turn the template-id annotation token into a type annotation
2826 // token, then try again to parse it as a type-specifier.
2827 AnnotateTemplateIdTokenAsType();
2831 // GNU attributes support.
2832 case tok::kw___attribute:
2833 ParseGNUAttributes(DS.getAttributes(), 0, LateAttrs);
2836 // Microsoft declspec support.
2837 case tok::kw___declspec:
2838 ParseMicrosoftDeclSpec(DS.getAttributes());
2841 // Microsoft single token adornments.
2842 case tok::kw___forceinline: {
2843 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
2844 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
2845 SourceLocation AttrNameLoc = Tok.getLocation();
2846 // FIXME: This does not work correctly if it is set to be a declspec
2847 // attribute, and a GNU attribute is simply incorrect.
2848 DS.getAttributes().addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 0,
2849 AttributeList::AS_GNU);
2853 case tok::kw___sptr:
2854 case tok::kw___uptr:
2855 case tok::kw___ptr64:
2856 case tok::kw___ptr32:
2858 case tok::kw___cdecl:
2859 case tok::kw___stdcall:
2860 case tok::kw___fastcall:
2861 case tok::kw___thiscall:
2862 case tok::kw___unaligned:
2863 ParseMicrosoftTypeAttributes(DS.getAttributes());
2866 // Borland single token adornments.
2867 case tok::kw___pascal:
2868 ParseBorlandTypeAttributes(DS.getAttributes());
2871 // OpenCL single token adornments.
2872 case tok::kw___kernel:
2873 ParseOpenCLAttributes(DS.getAttributes());
2876 // storage-class-specifier
2877 case tok::kw_typedef:
2878 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
2881 case tok::kw_extern:
2882 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
2883 Diag(Tok, diag::ext_thread_before) << "extern";
2884 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
2887 case tok::kw___private_extern__:
2888 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
2889 Loc, PrevSpec, DiagID);
2891 case tok::kw_static:
2892 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
2893 Diag(Tok, diag::ext_thread_before) << "static";
2894 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
2898 if (getLangOpts().CPlusPlus11) {
2899 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
2900 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
2903 Diag(Tok, diag::ext_auto_storage_class)
2904 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
2906 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
2909 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
2912 case tok::kw_register:
2913 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
2916 case tok::kw_mutable:
2917 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
2920 case tok::kw___thread:
2921 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
2924 case tok::kw_thread_local:
2925 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
2928 case tok::kw__Thread_local:
2929 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
2930 Loc, PrevSpec, DiagID);
2933 // function-specifier
2934 case tok::kw_inline:
2935 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
2937 case tok::kw_virtual:
2938 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
2940 case tok::kw_explicit:
2941 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
2943 case tok::kw__Noreturn:
2944 if (!getLangOpts().C11)
2945 Diag(Loc, diag::ext_c11_noreturn);
2946 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2949 // alignment-specifier
2950 case tok::kw__Alignas:
2951 if (!getLangOpts().C11)
2952 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
2953 ParseAlignmentSpecifier(DS.getAttributes());
2957 case tok::kw_friend:
2958 if (DSContext == DSC_class)
2959 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
2961 PrevSpec = ""; // not actually used by the diagnostic
2962 DiagID = diag::err_friend_invalid_in_context;
2968 case tok::kw___module_private__:
2969 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
2973 case tok::kw_constexpr:
2974 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
2979 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
2983 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
2984 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
2987 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2990 case tok::kw___int64:
2991 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2994 case tok::kw_signed:
2995 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
2998 case tok::kw_unsigned:
2999 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3002 case tok::kw__Complex:
3003 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3006 case tok::kw__Imaginary:
3007 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3011 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3015 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3019 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3022 case tok::kw___int128:
3023 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3027 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3031 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3034 case tok::kw_double:
3035 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3038 case tok::kw_wchar_t:
3039 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3042 case tok::kw_char16_t:
3043 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3046 case tok::kw_char32_t:
3047 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3052 if (Tok.is(tok::kw_bool) &&
3053 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3054 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3055 PrevSpec = ""; // Not used by the diagnostic.
3056 DiagID = diag::err_bool_redeclaration;
3057 // For better error recovery.
3058 Tok.setKind(tok::identifier);
3061 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3065 case tok::kw__Decimal32:
3066 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3069 case tok::kw__Decimal64:
3070 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3073 case tok::kw__Decimal128:
3074 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3077 case tok::kw___vector:
3078 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
3080 case tok::kw___pixel:
3081 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
3083 case tok::kw_image1d_t:
3084 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image1d_t, Loc,
3087 case tok::kw_image1d_array_t:
3088 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image1d_array_t, Loc,
3091 case tok::kw_image1d_buffer_t:
3092 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image1d_buffer_t, Loc,
3095 case tok::kw_image2d_t:
3096 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image2d_t, Loc,
3099 case tok::kw_image2d_array_t:
3100 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image2d_array_t, Loc,
3103 case tok::kw_image3d_t:
3104 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image3d_t, Loc,
3107 case tok::kw_sampler_t:
3108 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_sampler_t, Loc,
3111 case tok::kw_event_t:
3112 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_event_t, Loc,
3115 case tok::kw___unknown_anytype:
3116 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3122 case tok::kw_struct:
3123 case tok::kw___interface:
3124 case tok::kw_union: {
3125 tok::TokenKind Kind = Tok.getKind();
3128 // These are attributes following class specifiers.
3129 // To produce better diagnostic, we parse them when
3130 // parsing class specifier.
3131 ParsedAttributesWithRange Attributes(AttrFactory);
3132 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3133 EnteringContext, DSContext, Attributes);
3135 // If there are attributes following class specifier,
3136 // take them over and handle them here.
3137 if (!Attributes.empty()) {
3138 AttrsLastTime = true;
3139 attrs.takeAllFrom(Attributes);
3147 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3152 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3155 case tok::kw_volatile:
3156 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3159 case tok::kw_restrict:
3160 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3164 // C++ typename-specifier:
3165 case tok::kw_typename:
3166 if (TryAnnotateTypeOrScopeToken()) {
3167 DS.SetTypeSpecError();
3168 goto DoneWithDeclSpec;
3170 if (!Tok.is(tok::kw_typename))
3174 // GNU typeof support.
3175 case tok::kw_typeof:
3176 ParseTypeofSpecifier(DS);
3179 case tok::annot_decltype:
3180 ParseDecltypeSpecifier(DS);
3183 case tok::kw___underlying_type:
3184 ParseUnderlyingTypeSpecifier(DS);
3187 case tok::kw__Atomic:
3189 // If the _Atomic keyword is immediately followed by a left parenthesis,
3190 // it is interpreted as a type specifier (with a type name), not as a
3192 if (NextToken().is(tok::l_paren)) {
3193 ParseAtomicSpecifier(DS);
3196 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3200 // OpenCL qualifiers:
3201 case tok::kw_private:
3202 if (!getLangOpts().OpenCL)
3203 goto DoneWithDeclSpec;
3204 case tok::kw___private:
3205 case tok::kw___global:
3206 case tok::kw___local:
3207 case tok::kw___constant:
3208 case tok::kw___read_only:
3209 case tok::kw___write_only:
3210 case tok::kw___read_write:
3211 ParseOpenCLQualifiers(DS);
3215 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3216 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3217 // but we support it.
3218 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
3219 goto DoneWithDeclSpec;
3221 if (!ParseObjCProtocolQualifiers(DS))
3222 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
3223 << FixItHint::CreateInsertion(Loc, "id")
3224 << SourceRange(Loc, DS.getSourceRange().getEnd());
3226 // Need to support trailing type qualifiers (e.g. "id<p> const").
3227 // If a type specifier follows, it will be diagnosed elsewhere.
3230 // If the specifier wasn't legal, issue a diagnostic.
3232 assert(PrevSpec && "Method did not return previous specifier!");
3235 if (DiagID == diag::ext_duplicate_declspec)
3237 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
3239 Diag(Tok, DiagID) << PrevSpec;
3242 DS.SetRangeEnd(Tok.getLocation());
3243 if (DiagID != diag::err_bool_redeclaration)
3246 AttrsLastTime = false;
3250 /// ParseStructDeclaration - Parse a struct declaration without the terminating
3253 /// struct-declaration:
3254 /// specifier-qualifier-list struct-declarator-list
3255 /// [GNU] __extension__ struct-declaration
3256 /// [GNU] specifier-qualifier-list
3257 /// struct-declarator-list:
3258 /// struct-declarator
3259 /// struct-declarator-list ',' struct-declarator
3260 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3261 /// struct-declarator:
3263 /// [GNU] declarator attributes[opt]
3264 /// declarator[opt] ':' constant-expression
3265 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3268 ParseStructDeclaration(ParsingDeclSpec &DS, FieldCallback &Fields) {
3270 if (Tok.is(tok::kw___extension__)) {
3271 // __extension__ silences extension warnings in the subexpression.
3272 ExtensionRAIIObject O(Diags); // Use RAII to do this.
3274 return ParseStructDeclaration(DS, Fields);
3277 // Parse the common specifier-qualifiers-list piece.
3278 ParseSpecifierQualifierList(DS);
3280 // If there are no declarators, this is a free-standing declaration
3281 // specifier. Let the actions module cope with it.
3282 if (Tok.is(tok::semi)) {
3283 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
3285 DS.complete(TheDecl);
3289 // Read struct-declarators until we find the semicolon.
3290 bool FirstDeclarator = true;
3291 SourceLocation CommaLoc;
3293 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
3294 DeclaratorInfo.D.setCommaLoc(CommaLoc);
3296 // Attributes are only allowed here on successive declarators.
3297 if (!FirstDeclarator)
3298 MaybeParseGNUAttributes(DeclaratorInfo.D);
3300 /// struct-declarator: declarator
3301 /// struct-declarator: declarator[opt] ':' constant-expression
3302 if (Tok.isNot(tok::colon)) {
3303 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3304 ColonProtectionRAIIObject X(*this);
3305 ParseDeclarator(DeclaratorInfo.D);
3308 if (Tok.is(tok::colon)) {
3310 ExprResult Res(ParseConstantExpression());
3311 if (Res.isInvalid())
3312 SkipUntil(tok::semi, StopBeforeMatch);
3314 DeclaratorInfo.BitfieldSize = Res.release();
3317 // If attributes exist after the declarator, parse them.
3318 MaybeParseGNUAttributes(DeclaratorInfo.D);
3320 // We're done with this declarator; invoke the callback.
3321 Fields.invoke(DeclaratorInfo);
3323 // If we don't have a comma, it is either the end of the list (a ';')
3324 // or an error, bail out.
3325 if (Tok.isNot(tok::comma))
3328 // Consume the comma.
3329 CommaLoc = ConsumeToken();
3331 FirstDeclarator = false;
3335 /// ParseStructUnionBody
3336 /// struct-contents:
3337 /// struct-declaration-list
3339 /// [GNU] "struct-declaration-list" without terminatoring ';'
3340 /// struct-declaration-list:
3341 /// struct-declaration
3342 /// struct-declaration-list struct-declaration
3343 /// [OBC] '@' 'defs' '(' class-name ')'
3345 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
3346 unsigned TagType, Decl *TagDecl) {
3347 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3348 "parsing struct/union body");
3349 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
3351 BalancedDelimiterTracker T(*this, tok::l_brace);
3352 if (T.consumeOpen())
3355 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
3356 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3358 SmallVector<Decl *, 32> FieldDecls;
3360 // While we still have something to read, read the declarations in the struct.
3361 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
3362 // Each iteration of this loop reads one struct-declaration.
3364 // Check for extraneous top-level semicolon.
3365 if (Tok.is(tok::semi)) {
3366 ConsumeExtraSemi(InsideStruct, TagType);
3370 // Parse _Static_assert declaration.
3371 if (Tok.is(tok::kw__Static_assert)) {
3372 SourceLocation DeclEnd;
3373 ParseStaticAssertDeclaration(DeclEnd);
3377 if (Tok.is(tok::annot_pragma_pack)) {
3382 if (Tok.is(tok::annot_pragma_align)) {
3383 HandlePragmaAlign();
3387 if (!Tok.is(tok::at)) {
3388 struct CFieldCallback : FieldCallback {
3391 SmallVectorImpl<Decl *> &FieldDecls;
3393 CFieldCallback(Parser &P, Decl *TagDecl,
3394 SmallVectorImpl<Decl *> &FieldDecls) :
3395 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
3397 void invoke(ParsingFieldDeclarator &FD) {
3398 // Install the declarator into the current TagDecl.
3399 Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl,
3400 FD.D.getDeclSpec().getSourceRange().getBegin(),
3401 FD.D, FD.BitfieldSize);
3402 FieldDecls.push_back(Field);
3405 } Callback(*this, TagDecl, FieldDecls);
3407 // Parse all the comma separated declarators.
3408 ParsingDeclSpec DS(*this);
3409 ParseStructDeclaration(DS, Callback);
3410 } else { // Handle @defs
3412 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
3413 Diag(Tok, diag::err_unexpected_at);
3414 SkipUntil(tok::semi);
3418 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
3419 if (!Tok.is(tok::identifier)) {
3420 Diag(Tok, diag::err_expected_ident);
3421 SkipUntil(tok::semi);
3424 SmallVector<Decl *, 16> Fields;
3425 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
3426 Tok.getIdentifierInfo(), Fields);
3427 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
3429 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
3432 if (Tok.is(tok::semi)) {
3434 } else if (Tok.is(tok::r_brace)) {
3435 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
3438 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
3439 // Skip to end of block or statement to avoid ext-warning on extra ';'.
3440 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
3441 // If we stopped at a ';', eat it.
3442 if (Tok.is(tok::semi)) ConsumeToken();
3448 ParsedAttributes attrs(AttrFactory);
3449 // If attributes exist after struct contents, parse them.
3450 MaybeParseGNUAttributes(attrs);
3452 Actions.ActOnFields(getCurScope(),
3453 RecordLoc, TagDecl, FieldDecls,
3454 T.getOpenLocation(), T.getCloseLocation(),
3457 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
3458 T.getCloseLocation());
3461 /// ParseEnumSpecifier
3462 /// enum-specifier: [C99 6.7.2.2]
3463 /// 'enum' identifier[opt] '{' enumerator-list '}'
3464 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
3465 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
3466 /// '}' attributes[opt]
3467 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
3469 /// 'enum' identifier
3470 /// [GNU] 'enum' attributes[opt] identifier
3472 /// [C++11] enum-head '{' enumerator-list[opt] '}'
3473 /// [C++11] enum-head '{' enumerator-list ',' '}'
3475 /// enum-head: [C++11]
3476 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
3477 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
3478 /// identifier enum-base[opt]
3480 /// enum-key: [C++11]
3485 /// enum-base: [C++11]
3486 /// ':' type-specifier-seq
3488 /// [C++] elaborated-type-specifier:
3489 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
3491 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
3492 const ParsedTemplateInfo &TemplateInfo,
3493 AccessSpecifier AS, DeclSpecContext DSC) {
3494 // Parse the tag portion of this.
3495 if (Tok.is(tok::code_completion)) {
3496 // Code completion for an enum name.
3497 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
3498 return cutOffParsing();
3501 // If attributes exist after tag, parse them.
3502 ParsedAttributesWithRange attrs(AttrFactory);
3503 MaybeParseGNUAttributes(attrs);
3504 MaybeParseCXX11Attributes(attrs);
3506 // If declspecs exist after tag, parse them.
3507 while (Tok.is(tok::kw___declspec))
3508 ParseMicrosoftDeclSpec(attrs);
3510 SourceLocation ScopedEnumKWLoc;
3511 bool IsScopedUsingClassTag = false;
3513 // In C++11, recognize 'enum class' and 'enum struct'.
3514 if (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct)) {
3515 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
3516 : diag::ext_scoped_enum);
3517 IsScopedUsingClassTag = Tok.is(tok::kw_class);
3518 ScopedEnumKWLoc = ConsumeToken();
3520 // Attributes are not allowed between these keywords. Diagnose,
3521 // but then just treat them like they appeared in the right place.
3522 ProhibitAttributes(attrs);
3524 // They are allowed afterwards, though.
3525 MaybeParseGNUAttributes(attrs);
3526 MaybeParseCXX11Attributes(attrs);
3527 while (Tok.is(tok::kw___declspec))
3528 ParseMicrosoftDeclSpec(attrs);
3531 // C++11 [temp.explicit]p12:
3532 // The usual access controls do not apply to names used to specify
3533 // explicit instantiations.
3534 // We extend this to also cover explicit specializations. Note that
3535 // we don't suppress if this turns out to be an elaborated type
3537 bool shouldDelayDiagsInTag =
3538 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3539 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3540 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
3542 // Enum definitions should not be parsed in a trailing-return-type.
3543 bool AllowDeclaration = DSC != DSC_trailing;
3545 bool AllowFixedUnderlyingType = AllowDeclaration &&
3546 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
3547 getLangOpts().ObjC2);
3549 CXXScopeSpec &SS = DS.getTypeSpecScope();
3550 if (getLangOpts().CPlusPlus) {
3551 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
3552 // if a fixed underlying type is allowed.
3553 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
3555 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
3556 /*EnteringContext=*/true))
3559 if (SS.isSet() && Tok.isNot(tok::identifier)) {
3560 Diag(Tok, diag::err_expected_ident);
3561 if (Tok.isNot(tok::l_brace)) {
3562 // Has no name and is not a definition.
3563 // Skip the rest of this declarator, up until the comma or semicolon.
3564 SkipUntil(tok::comma, StopAtSemi);
3570 // Must have either 'enum name' or 'enum {...}'.
3571 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
3572 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
3573 Diag(Tok, diag::err_expected_ident_lbrace);
3575 // Skip the rest of this declarator, up until the comma or semicolon.
3576 SkipUntil(tok::comma, StopAtSemi);
3580 // If an identifier is present, consume and remember it.
3581 IdentifierInfo *Name = 0;
3582 SourceLocation NameLoc;
3583 if (Tok.is(tok::identifier)) {
3584 Name = Tok.getIdentifierInfo();
3585 NameLoc = ConsumeToken();
3588 if (!Name && ScopedEnumKWLoc.isValid()) {
3589 // C++0x 7.2p2: The optional identifier shall not be omitted in the
3590 // declaration of a scoped enumeration.
3591 Diag(Tok, diag::err_scoped_enum_missing_identifier);
3592 ScopedEnumKWLoc = SourceLocation();
3593 IsScopedUsingClassTag = false;
3596 // Okay, end the suppression area. We'll decide whether to emit the
3597 // diagnostics in a second.
3598 if (shouldDelayDiagsInTag)
3599 diagsFromTag.done();
3601 TypeResult BaseType;
3603 // Parse the fixed underlying type.
3604 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
3605 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
3606 bool PossibleBitfield = false;
3607 if (CanBeBitfield) {
3608 // If we're in class scope, this can either be an enum declaration with
3609 // an underlying type, or a declaration of a bitfield member. We try to
3610 // use a simple disambiguation scheme first to catch the common cases
3611 // (integer literal, sizeof); if it's still ambiguous, we then consider
3612 // anything that's a simple-type-specifier followed by '(' as an
3613 // expression. This suffices because function types are not valid
3614 // underlying types anyway.
3615 EnterExpressionEvaluationContext Unevaluated(Actions,
3616 Sema::ConstantEvaluated);
3617 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
3618 // If the next token starts an expression, we know we're parsing a
3619 // bit-field. This is the common case.
3620 if (TPR == TPResult::True())
3621 PossibleBitfield = true;
3622 // If the next token starts a type-specifier-seq, it may be either a
3623 // a fixed underlying type or the start of a function-style cast in C++;
3624 // lookahead one more token to see if it's obvious that we have a
3625 // fixed underlying type.
3626 else if (TPR == TPResult::False() &&
3627 GetLookAheadToken(2).getKind() == tok::semi) {
3631 // We have the start of a type-specifier-seq, so we have to perform
3632 // tentative parsing to determine whether we have an expression or a
3634 TentativeParsingAction TPA(*this);
3639 // If we see a type specifier followed by an open-brace, we have an
3640 // ambiguity between an underlying type and a C++11 braced
3641 // function-style cast. Resolve this by always treating it as an
3643 // FIXME: The standard is not entirely clear on how to disambiguate in
3645 if ((getLangOpts().CPlusPlus &&
3646 isCXXDeclarationSpecifier(TPResult::True()) != TPResult::True()) ||
3647 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
3648 // We'll parse this as a bitfield later.
3649 PossibleBitfield = true;
3652 // We have a type-specifier-seq.
3661 if (!PossibleBitfield) {
3663 BaseType = ParseTypeName(&Range);
3665 if (getLangOpts().CPlusPlus11) {
3666 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
3667 } else if (!getLangOpts().ObjC2) {
3668 if (getLangOpts().CPlusPlus)
3669 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
3671 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
3676 // There are four options here. If we have 'friend enum foo;' then this is a
3677 // friend declaration, and cannot have an accompanying definition. If we have
3678 // 'enum foo;', then this is a forward declaration. If we have
3679 // 'enum foo {...' then this is a definition. Otherwise we have something
3680 // like 'enum foo xyz', a reference.
3682 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
3683 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
3684 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
3686 Sema::TagUseKind TUK;
3687 if (!AllowDeclaration) {
3688 TUK = Sema::TUK_Reference;
3689 } else if (Tok.is(tok::l_brace)) {
3690 if (DS.isFriendSpecified()) {
3691 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
3692 << SourceRange(DS.getFriendSpecLoc());
3694 SkipUntil(tok::r_brace, StopAtSemi);
3695 TUK = Sema::TUK_Friend;
3697 TUK = Sema::TUK_Definition;
3699 } else if (DSC != DSC_type_specifier &&
3700 (Tok.is(tok::semi) ||
3701 (Tok.isAtStartOfLine() &&
3702 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
3703 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
3704 if (Tok.isNot(tok::semi)) {
3705 // A semicolon was missing after this declaration. Diagnose and recover.
3706 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
3709 Tok.setKind(tok::semi);
3712 TUK = Sema::TUK_Reference;
3715 // If this is an elaborated type specifier, and we delayed
3716 // diagnostics before, just merge them into the current pool.
3717 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
3718 diagsFromTag.redelay();
3721 MultiTemplateParamsArg TParams;
3722 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
3723 TUK != Sema::TUK_Reference) {
3724 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
3725 // Skip the rest of this declarator, up until the comma or semicolon.
3726 Diag(Tok, diag::err_enum_template);
3727 SkipUntil(tok::comma, StopAtSemi);
3731 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
3732 // Enumerations can't be explicitly instantiated.
3733 DS.SetTypeSpecError();
3734 Diag(StartLoc, diag::err_explicit_instantiation_enum);
3738 assert(TemplateInfo.TemplateParams && "no template parameters");
3739 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
3740 TemplateInfo.TemplateParams->size());
3743 if (TUK == Sema::TUK_Reference)
3744 ProhibitAttributes(attrs);
3746 if (!Name && TUK != Sema::TUK_Definition) {
3747 Diag(Tok, diag::err_enumerator_unnamed_no_def);
3749 // Skip the rest of this declarator, up until the comma or semicolon.
3750 SkipUntil(tok::comma, StopAtSemi);
3755 bool IsDependent = false;
3756 const char *PrevSpec = 0;
3758 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
3759 StartLoc, SS, Name, NameLoc, attrs.getList(),
3760 AS, DS.getModulePrivateSpecLoc(), TParams,
3761 Owned, IsDependent, ScopedEnumKWLoc,
3762 IsScopedUsingClassTag, BaseType);
3765 // This enum has a dependent nested-name-specifier. Handle it as a
3768 DS.SetTypeSpecError();
3769 Diag(Tok, diag::err_expected_type_name_after_typename);
3773 TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum,
3774 TUK, SS, Name, StartLoc,
3776 if (Type.isInvalid()) {
3777 DS.SetTypeSpecError();
3781 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
3782 NameLoc.isValid() ? NameLoc : StartLoc,
3783 PrevSpec, DiagID, Type.get()))
3784 Diag(StartLoc, DiagID) << PrevSpec;
3790 // The action failed to produce an enumeration tag. If this is a
3791 // definition, consume the entire definition.
3792 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
3794 SkipUntil(tok::r_brace, StopAtSemi);
3797 DS.SetTypeSpecError();
3801 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference)
3802 ParseEnumBody(StartLoc, TagDecl);
3804 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
3805 NameLoc.isValid() ? NameLoc : StartLoc,
3806 PrevSpec, DiagID, TagDecl, Owned))
3807 Diag(StartLoc, DiagID) << PrevSpec;
3810 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
3811 /// enumerator-list:
3813 /// enumerator-list ',' enumerator
3815 /// enumeration-constant
3816 /// enumeration-constant '=' constant-expression
3817 /// enumeration-constant:
3820 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
3821 // Enter the scope of the enum body and start the definition.
3822 ParseScope EnumScope(this, Scope::DeclScope);
3823 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
3825 BalancedDelimiterTracker T(*this, tok::l_brace);
3828 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
3829 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
3830 Diag(Tok, diag::error_empty_enum);
3832 SmallVector<Decl *, 32> EnumConstantDecls;
3834 Decl *LastEnumConstDecl = 0;
3836 // Parse the enumerator-list.
3837 while (Tok.is(tok::identifier)) {
3838 IdentifierInfo *Ident = Tok.getIdentifierInfo();
3839 SourceLocation IdentLoc = ConsumeToken();
3841 // If attributes exist after the enumerator, parse them.
3842 ParsedAttributesWithRange attrs(AttrFactory);
3843 MaybeParseGNUAttributes(attrs);
3844 MaybeParseCXX11Attributes(attrs);
3845 ProhibitAttributes(attrs);
3847 SourceLocation EqualLoc;
3848 ExprResult AssignedVal;
3849 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
3851 if (Tok.is(tok::equal)) {
3852 EqualLoc = ConsumeToken();
3853 AssignedVal = ParseConstantExpression();
3854 if (AssignedVal.isInvalid())
3855 SkipUntil(tok::comma, tok::r_brace, StopAtSemi | StopBeforeMatch);
3858 // Install the enumerator constant into EnumDecl.
3859 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
3862 attrs.getList(), EqualLoc,
3863 AssignedVal.release());
3864 PD.complete(EnumConstDecl);
3866 EnumConstantDecls.push_back(EnumConstDecl);
3867 LastEnumConstDecl = EnumConstDecl;
3869 if (Tok.is(tok::identifier)) {
3870 // We're missing a comma between enumerators.
3871 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3872 Diag(Loc, diag::err_enumerator_list_missing_comma)
3873 << FixItHint::CreateInsertion(Loc, ", ");
3877 if (Tok.isNot(tok::comma))
3879 SourceLocation CommaLoc = ConsumeToken();
3881 if (Tok.isNot(tok::identifier)) {
3882 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
3883 Diag(CommaLoc, getLangOpts().CPlusPlus ?
3884 diag::ext_enumerator_list_comma_cxx :
3885 diag::ext_enumerator_list_comma_c)
3886 << FixItHint::CreateRemoval(CommaLoc);
3887 else if (getLangOpts().CPlusPlus11)
3888 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
3889 << FixItHint::CreateRemoval(CommaLoc);
3896 // If attributes exist after the identifier list, parse them.
3897 ParsedAttributes attrs(AttrFactory);
3898 MaybeParseGNUAttributes(attrs);
3900 Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(),
3901 EnumDecl, EnumConstantDecls,
3906 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl,
3907 T.getCloseLocation());
3909 // The next token must be valid after an enum definition. If not, a ';'
3910 // was probably forgotten.
3911 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
3912 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
3913 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, "enum");
3914 // Push this token back into the preprocessor and change our current token
3915 // to ';' so that the rest of the code recovers as though there were an
3916 // ';' after the definition.
3918 Tok.setKind(tok::semi);
3922 /// isTypeSpecifierQualifier - Return true if the current token could be the
3923 /// start of a type-qualifier-list.
3924 bool Parser::isTypeQualifier() const {
3925 switch (Tok.getKind()) {
3926 default: return false;
3928 // type-qualifier only in OpenCL
3929 case tok::kw_private:
3930 return getLangOpts().OpenCL;
3934 case tok::kw_volatile:
3935 case tok::kw_restrict:
3936 case tok::kw___private:
3937 case tok::kw___local:
3938 case tok::kw___global:
3939 case tok::kw___constant:
3940 case tok::kw___read_only:
3941 case tok::kw___read_write:
3942 case tok::kw___write_only:
3947 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
3948 /// is definitely a type-specifier. Return false if it isn't part of a type
3949 /// specifier or if we're not sure.
3950 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
3951 switch (Tok.getKind()) {
3952 default: return false;
3956 case tok::kw___int64:
3957 case tok::kw___int128:
3958 case tok::kw_signed:
3959 case tok::kw_unsigned:
3960 case tok::kw__Complex:
3961 case tok::kw__Imaginary:
3964 case tok::kw_wchar_t:
3965 case tok::kw_char16_t:
3966 case tok::kw_char32_t:
3970 case tok::kw_double:
3973 case tok::kw__Decimal32:
3974 case tok::kw__Decimal64:
3975 case tok::kw__Decimal128:
3976 case tok::kw___vector:
3978 // OpenCL specific types:
3979 case tok::kw_image1d_t:
3980 case tok::kw_image1d_array_t:
3981 case tok::kw_image1d_buffer_t:
3982 case tok::kw_image2d_t:
3983 case tok::kw_image2d_array_t:
3984 case tok::kw_image3d_t:
3985 case tok::kw_sampler_t:
3986 case tok::kw_event_t:
3988 // struct-or-union-specifier (C99) or class-specifier (C++)
3990 case tok::kw_struct:
3991 case tok::kw___interface:
3997 case tok::annot_typename:
4002 /// isTypeSpecifierQualifier - Return true if the current token could be the
4003 /// start of a specifier-qualifier-list.
4004 bool Parser::isTypeSpecifierQualifier() {
4005 switch (Tok.getKind()) {
4006 default: return false;
4008 case tok::identifier: // foo::bar
4009 if (TryAltiVecVectorToken())
4012 case tok::kw_typename: // typename T::type
4013 // Annotate typenames and C++ scope specifiers. If we get one, just
4014 // recurse to handle whatever we get.
4015 if (TryAnnotateTypeOrScopeToken())
4017 if (Tok.is(tok::identifier))
4019 return isTypeSpecifierQualifier();
4021 case tok::coloncolon: // ::foo::bar
4022 if (NextToken().is(tok::kw_new) || // ::new
4023 NextToken().is(tok::kw_delete)) // ::delete
4026 if (TryAnnotateTypeOrScopeToken())
4028 return isTypeSpecifierQualifier();
4030 // GNU attributes support.
4031 case tok::kw___attribute:
4032 // GNU typeof support.
4033 case tok::kw_typeof:
4038 case tok::kw___int64:
4039 case tok::kw___int128:
4040 case tok::kw_signed:
4041 case tok::kw_unsigned:
4042 case tok::kw__Complex:
4043 case tok::kw__Imaginary:
4046 case tok::kw_wchar_t:
4047 case tok::kw_char16_t:
4048 case tok::kw_char32_t:
4052 case tok::kw_double:
4055 case tok::kw__Decimal32:
4056 case tok::kw__Decimal64:
4057 case tok::kw__Decimal128:
4058 case tok::kw___vector:
4060 // OpenCL specific types:
4061 case tok::kw_image1d_t:
4062 case tok::kw_image1d_array_t:
4063 case tok::kw_image1d_buffer_t:
4064 case tok::kw_image2d_t:
4065 case tok::kw_image2d_array_t:
4066 case tok::kw_image3d_t:
4067 case tok::kw_sampler_t:
4068 case tok::kw_event_t:
4070 // struct-or-union-specifier (C99) or class-specifier (C++)
4072 case tok::kw_struct:
4073 case tok::kw___interface:
4080 case tok::kw_volatile:
4081 case tok::kw_restrict:
4083 // Debugger support.
4084 case tok::kw___unknown_anytype:
4087 case tok::annot_typename:
4090 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4092 return getLangOpts().ObjC1;
4094 case tok::kw___cdecl:
4095 case tok::kw___stdcall:
4096 case tok::kw___fastcall:
4097 case tok::kw___thiscall:
4099 case tok::kw___ptr64:
4100 case tok::kw___ptr32:
4101 case tok::kw___pascal:
4102 case tok::kw___unaligned:
4104 case tok::kw___private:
4105 case tok::kw___local:
4106 case tok::kw___global:
4107 case tok::kw___constant:
4108 case tok::kw___read_only:
4109 case tok::kw___read_write:
4110 case tok::kw___write_only:
4114 case tok::kw_private:
4115 return getLangOpts().OpenCL;
4118 case tok::kw__Atomic:
4123 /// isDeclarationSpecifier() - Return true if the current token is part of a
4124 /// declaration specifier.
4126 /// \param DisambiguatingWithExpression True to indicate that the purpose of
4127 /// this check is to disambiguate between an expression and a declaration.
4128 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4129 switch (Tok.getKind()) {
4130 default: return false;
4132 case tok::kw_private:
4133 return getLangOpts().OpenCL;
4135 case tok::identifier: // foo::bar
4136 // Unfortunate hack to support "Class.factoryMethod" notation.
4137 if (getLangOpts().ObjC1 && NextToken().is(tok::period))
4139 if (TryAltiVecVectorToken())
4142 case tok::kw_decltype: // decltype(T())::type
4143 case tok::kw_typename: // typename T::type
4144 // Annotate typenames and C++ scope specifiers. If we get one, just
4145 // recurse to handle whatever we get.
4146 if (TryAnnotateTypeOrScopeToken())
4148 if (Tok.is(tok::identifier))
4151 // If we're in Objective-C and we have an Objective-C class type followed
4152 // by an identifier and then either ':' or ']', in a place where an
4153 // expression is permitted, then this is probably a class message send
4154 // missing the initial '['. In this case, we won't consider this to be
4155 // the start of a declaration.
4156 if (DisambiguatingWithExpression &&
4157 isStartOfObjCClassMessageMissingOpenBracket())
4160 return isDeclarationSpecifier();
4162 case tok::coloncolon: // ::foo::bar
4163 if (NextToken().is(tok::kw_new) || // ::new
4164 NextToken().is(tok::kw_delete)) // ::delete
4167 // Annotate typenames and C++ scope specifiers. If we get one, just
4168 // recurse to handle whatever we get.
4169 if (TryAnnotateTypeOrScopeToken())
4171 return isDeclarationSpecifier();
4173 // storage-class-specifier
4174 case tok::kw_typedef:
4175 case tok::kw_extern:
4176 case tok::kw___private_extern__:
4177 case tok::kw_static:
4179 case tok::kw_register:
4180 case tok::kw___thread:
4181 case tok::kw_thread_local:
4182 case tok::kw__Thread_local:
4185 case tok::kw___module_private__:
4188 case tok::kw___unknown_anytype:
4193 case tok::kw___int64:
4194 case tok::kw___int128:
4195 case tok::kw_signed:
4196 case tok::kw_unsigned:
4197 case tok::kw__Complex:
4198 case tok::kw__Imaginary:
4201 case tok::kw_wchar_t:
4202 case tok::kw_char16_t:
4203 case tok::kw_char32_t:
4208 case tok::kw_double:
4211 case tok::kw__Decimal32:
4212 case tok::kw__Decimal64:
4213 case tok::kw__Decimal128:
4214 case tok::kw___vector:
4216 // OpenCL specific types:
4217 case tok::kw_image1d_t:
4218 case tok::kw_image1d_array_t:
4219 case tok::kw_image1d_buffer_t:
4220 case tok::kw_image2d_t:
4221 case tok::kw_image2d_array_t:
4222 case tok::kw_image3d_t:
4223 case tok::kw_sampler_t:
4224 case tok::kw_event_t:
4226 // struct-or-union-specifier (C99) or class-specifier (C++)
4228 case tok::kw_struct:
4230 case tok::kw___interface:
4236 case tok::kw_volatile:
4237 case tok::kw_restrict:
4239 // function-specifier
4240 case tok::kw_inline:
4241 case tok::kw_virtual:
4242 case tok::kw_explicit:
4243 case tok::kw__Noreturn:
4245 // alignment-specifier
4246 case tok::kw__Alignas:
4249 case tok::kw_friend:
4251 // static_assert-declaration
4252 case tok::kw__Static_assert:
4254 // GNU typeof support.
4255 case tok::kw_typeof:
4258 case tok::kw___attribute:
4260 // C++11 decltype and constexpr.
4261 case tok::annot_decltype:
4262 case tok::kw_constexpr:
4265 case tok::kw__Atomic:
4268 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4270 return getLangOpts().ObjC1;
4273 case tok::annot_typename:
4274 return !DisambiguatingWithExpression ||
4275 !isStartOfObjCClassMessageMissingOpenBracket();
4277 case tok::kw___declspec:
4278 case tok::kw___cdecl:
4279 case tok::kw___stdcall:
4280 case tok::kw___fastcall:
4281 case tok::kw___thiscall:
4283 case tok::kw___sptr:
4284 case tok::kw___uptr:
4285 case tok::kw___ptr64:
4286 case tok::kw___ptr32:
4287 case tok::kw___forceinline:
4288 case tok::kw___pascal:
4289 case tok::kw___unaligned:
4291 case tok::kw___private:
4292 case tok::kw___local:
4293 case tok::kw___global:
4294 case tok::kw___constant:
4295 case tok::kw___read_only:
4296 case tok::kw___read_write:
4297 case tok::kw___write_only:
4303 bool Parser::isConstructorDeclarator() {
4304 TentativeParsingAction TPA(*this);
4306 // Parse the C++ scope specifier.
4308 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
4309 /*EnteringContext=*/true)) {
4314 // Parse the constructor name.
4315 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
4316 // We already know that we have a constructor name; just consume
4324 // Current class name must be followed by a left parenthesis.
4325 if (Tok.isNot(tok::l_paren)) {
4331 // A right parenthesis, or ellipsis followed by a right parenthesis signals
4332 // that we have a constructor.
4333 if (Tok.is(tok::r_paren) ||
4334 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
4339 // A C++11 attribute here signals that we have a constructor, and is an
4340 // attribute on the first constructor parameter.
4341 if (getLangOpts().CPlusPlus11 &&
4342 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
4343 /*OuterMightBeMessageSend*/ true)) {
4348 // If we need to, enter the specified scope.
4349 DeclaratorScopeObj DeclScopeObj(*this, SS);
4350 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
4351 DeclScopeObj.EnterDeclaratorScope();
4353 // Optionally skip Microsoft attributes.
4354 ParsedAttributes Attrs(AttrFactory);
4355 MaybeParseMicrosoftAttributes(Attrs);
4357 // Check whether the next token(s) are part of a declaration
4358 // specifier, in which case we have the start of a parameter and,
4359 // therefore, we know that this is a constructor.
4360 bool IsConstructor = false;
4361 if (isDeclarationSpecifier())
4362 IsConstructor = true;
4363 else if (Tok.is(tok::identifier) ||
4364 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
4365 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
4366 // This might be a parenthesized member name, but is more likely to
4367 // be a constructor declaration with an invalid argument type. Keep
4369 if (Tok.is(tok::annot_cxxscope))
4373 // If this is not a constructor, we must be parsing a declarator,
4374 // which must have one of the following syntactic forms (see the
4375 // grammar extract at the start of ParseDirectDeclarator):
4376 switch (Tok.getKind()) {
4381 // C(X [ [attribute]]);
4382 case tok::coloncolon:
4387 // Assume this isn't a constructor, rather than assuming it's a
4388 // constructor with an unnamed parameter of an ill-formed type.
4392 IsConstructor = true;
4398 return IsConstructor;
4401 /// ParseTypeQualifierListOpt
4402 /// type-qualifier-list: [C99 6.7.5]
4404 /// [vendor] attributes
4405 /// [ only if VendorAttributesAllowed=true ]
4406 /// type-qualifier-list type-qualifier
4407 /// [vendor] type-qualifier-list attributes
4408 /// [ only if VendorAttributesAllowed=true ]
4409 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
4410 /// [ only if CXX11AttributesAllowed=true ]
4411 /// Note: vendor can be GNU, MS, etc.
4413 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
4414 bool VendorAttributesAllowed,
4415 bool CXX11AttributesAllowed,
4417 bool IdentifierRequired) {
4418 if (getLangOpts().CPlusPlus11 && CXX11AttributesAllowed &&
4419 isCXX11AttributeSpecifier()) {
4420 ParsedAttributesWithRange attrs(AttrFactory);
4421 ParseCXX11Attributes(attrs);
4422 DS.takeAttributesFrom(attrs);
4425 SourceLocation EndLoc;
4428 bool isInvalid = false;
4429 const char *PrevSpec = 0;
4430 unsigned DiagID = 0;
4431 SourceLocation Loc = Tok.getLocation();
4433 switch (Tok.getKind()) {
4434 case tok::code_completion:
4435 Actions.CodeCompleteTypeQualifiers(DS);
4436 return cutOffParsing();
4439 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
4442 case tok::kw_volatile:
4443 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4446 case tok::kw_restrict:
4447 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4450 case tok::kw__Atomic:
4452 goto DoneWithTypeQuals;
4453 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4457 // OpenCL qualifiers:
4458 case tok::kw_private:
4459 if (!getLangOpts().OpenCL)
4460 goto DoneWithTypeQuals;
4461 case tok::kw___private:
4462 case tok::kw___global:
4463 case tok::kw___local:
4464 case tok::kw___constant:
4465 case tok::kw___read_only:
4466 case tok::kw___write_only:
4467 case tok::kw___read_write:
4468 ParseOpenCLQualifiers(DS);
4471 case tok::kw___uptr:
4472 // GNU libc headers in C mode use '__uptr' as an identifer which conflicts
4473 // with the MS modifier keyword.
4474 if (VendorAttributesAllowed && !getLangOpts().CPlusPlus &&
4475 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
4476 if (TryKeywordIdentFallback(false))
4479 case tok::kw___sptr:
4481 case tok::kw___ptr64:
4482 case tok::kw___ptr32:
4483 case tok::kw___cdecl:
4484 case tok::kw___stdcall:
4485 case tok::kw___fastcall:
4486 case tok::kw___thiscall:
4487 case tok::kw___unaligned:
4488 if (VendorAttributesAllowed) {
4489 ParseMicrosoftTypeAttributes(DS.getAttributes());
4492 goto DoneWithTypeQuals;
4493 case tok::kw___pascal:
4494 if (VendorAttributesAllowed) {
4495 ParseBorlandTypeAttributes(DS.getAttributes());
4498 goto DoneWithTypeQuals;
4499 case tok::kw___attribute:
4500 if (VendorAttributesAllowed) {
4501 ParseGNUAttributes(DS.getAttributes());
4502 continue; // do *not* consume the next token!
4504 // otherwise, FALL THROUGH!
4507 // If this is not a type-qualifier token, we're done reading type
4508 // qualifiers. First verify that DeclSpec's are consistent.
4509 DS.Finish(Diags, PP);
4510 if (EndLoc.isValid())
4511 DS.SetRangeEnd(EndLoc);
4515 // If the specifier combination wasn't legal, issue a diagnostic.
4517 assert(PrevSpec && "Method did not return previous specifier!");
4518 Diag(Tok, DiagID) << PrevSpec;
4520 EndLoc = ConsumeToken();
4525 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
4527 void Parser::ParseDeclarator(Declarator &D) {
4528 /// This implements the 'declarator' production in the C grammar, then checks
4529 /// for well-formedness and issues diagnostics.
4530 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
4533 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang) {
4534 if (Kind == tok::star || Kind == tok::caret)
4537 // We parse rvalue refs in C++03, because otherwise the errors are scary.
4538 if (!Lang.CPlusPlus)
4541 return Kind == tok::amp || Kind == tok::ampamp;
4544 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
4545 /// is parsed by the function passed to it. Pass null, and the direct-declarator
4546 /// isn't parsed at all, making this function effectively parse the C++
4547 /// ptr-operator production.
4549 /// If the grammar of this construct is extended, matching changes must also be
4550 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
4551 /// isConstructorDeclarator.
4553 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
4554 /// [C] pointer[opt] direct-declarator
4555 /// [C++] direct-declarator
4556 /// [C++] ptr-operator declarator
4558 /// pointer: [C99 6.7.5]
4559 /// '*' type-qualifier-list[opt]
4560 /// '*' type-qualifier-list[opt] pointer
4563 /// '*' cv-qualifier-seq[opt]
4566 /// [GNU] '&' restrict[opt] attributes[opt]
4567 /// [GNU?] '&&' restrict[opt] attributes[opt]
4568 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
4569 void Parser::ParseDeclaratorInternal(Declarator &D,
4570 DirectDeclParseFunction DirectDeclParser) {
4571 if (Diags.hasAllExtensionsSilenced())
4574 // C++ member pointers start with a '::' or a nested-name.
4575 // Member pointers get special handling, since there's no place for the
4576 // scope spec in the generic path below.
4577 if (getLangOpts().CPlusPlus &&
4578 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
4579 Tok.is(tok::annot_cxxscope))) {
4580 bool EnteringContext = D.getContext() == Declarator::FileContext ||
4581 D.getContext() == Declarator::MemberContext;
4583 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext);
4585 if (SS.isNotEmpty()) {
4586 if (Tok.isNot(tok::star)) {
4587 // The scope spec really belongs to the direct-declarator.
4588 if (D.mayHaveIdentifier())
4589 D.getCXXScopeSpec() = SS;
4591 AnnotateScopeToken(SS, true);
4593 if (DirectDeclParser)
4594 (this->*DirectDeclParser)(D);
4598 SourceLocation Loc = ConsumeToken();
4600 DeclSpec DS(AttrFactory);
4601 ParseTypeQualifierListOpt(DS);
4602 D.ExtendWithDeclSpec(DS);
4604 // Recurse to parse whatever is left.
4605 ParseDeclaratorInternal(D, DirectDeclParser);
4607 // Sema will have to catch (syntactically invalid) pointers into global
4608 // scope. It has to catch pointers into namespace scope anyway.
4609 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
4612 /* Don't replace range end. */SourceLocation());
4617 tok::TokenKind Kind = Tok.getKind();
4618 // Not a pointer, C++ reference, or block.
4619 if (!isPtrOperatorToken(Kind, getLangOpts())) {
4620 if (DirectDeclParser)
4621 (this->*DirectDeclParser)(D);
4625 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
4626 // '&&' -> rvalue reference
4627 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
4630 if (Kind == tok::star || Kind == tok::caret) {
4632 DeclSpec DS(AttrFactory);
4634 // FIXME: GNU attributes are not allowed here in a new-type-id.
4635 ParseTypeQualifierListOpt(DS, true, true, true, !D.mayOmitIdentifier());
4636 D.ExtendWithDeclSpec(DS);
4638 // Recursively parse the declarator.
4639 ParseDeclaratorInternal(D, DirectDeclParser);
4640 if (Kind == tok::star)
4641 // Remember that we parsed a pointer type, and remember the type-quals.
4642 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
4643 DS.getConstSpecLoc(),
4644 DS.getVolatileSpecLoc(),
4645 DS.getRestrictSpecLoc()),
4649 // Remember that we parsed a Block type, and remember the type-quals.
4650 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
4656 DeclSpec DS(AttrFactory);
4658 // Complain about rvalue references in C++03, but then go on and build
4660 if (Kind == tok::ampamp)
4661 Diag(Loc, getLangOpts().CPlusPlus11 ?
4662 diag::warn_cxx98_compat_rvalue_reference :
4663 diag::ext_rvalue_reference);
4665 // GNU-style and C++11 attributes are allowed here, as is restrict.
4666 ParseTypeQualifierListOpt(DS);
4667 D.ExtendWithDeclSpec(DS);
4669 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
4670 // cv-qualifiers are introduced through the use of a typedef or of a
4671 // template type argument, in which case the cv-qualifiers are ignored.
4672 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
4673 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4674 Diag(DS.getConstSpecLoc(),
4675 diag::err_invalid_reference_qualifier_application) << "const";
4676 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4677 Diag(DS.getVolatileSpecLoc(),
4678 diag::err_invalid_reference_qualifier_application) << "volatile";
4679 // 'restrict' is permitted as an extension.
4680 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4681 Diag(DS.getAtomicSpecLoc(),
4682 diag::err_invalid_reference_qualifier_application) << "_Atomic";
4685 // Recursively parse the declarator.
4686 ParseDeclaratorInternal(D, DirectDeclParser);
4688 if (D.getNumTypeObjects() > 0) {
4689 // C++ [dcl.ref]p4: There shall be no references to references.
4690 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
4691 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
4692 if (const IdentifierInfo *II = D.getIdentifier())
4693 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
4696 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
4699 // Once we've complained about the reference-to-reference, we
4700 // can go ahead and build the (technically ill-formed)
4701 // declarator: reference collapsing will take care of it.
4705 // Remember that we parsed a reference type.
4706 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
4713 static void diagnoseMisplacedEllipsis(Parser &P, Declarator &D,
4714 SourceLocation EllipsisLoc) {
4715 if (EllipsisLoc.isValid()) {
4716 FixItHint Insertion;
4717 if (!D.getEllipsisLoc().isValid()) {
4718 Insertion = FixItHint::CreateInsertion(D.getIdentifierLoc(), "...");
4719 D.setEllipsisLoc(EllipsisLoc);
4721 P.Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
4722 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion << !D.hasName();
4726 /// ParseDirectDeclarator
4727 /// direct-declarator: [C99 6.7.5]
4728 /// [C99] identifier
4729 /// '(' declarator ')'
4730 /// [GNU] '(' attributes declarator ')'
4731 /// [C90] direct-declarator '[' constant-expression[opt] ']'
4732 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
4733 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
4734 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
4735 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
4736 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
4737 /// attribute-specifier-seq[opt]
4738 /// direct-declarator '(' parameter-type-list ')'
4739 /// direct-declarator '(' identifier-list[opt] ')'
4740 /// [GNU] direct-declarator '(' parameter-forward-declarations
4741 /// parameter-type-list[opt] ')'
4742 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
4743 /// cv-qualifier-seq[opt] exception-specification[opt]
4744 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
4745 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
4746 /// ref-qualifier[opt] exception-specification[opt]
4747 /// [C++] declarator-id
4748 /// [C++11] declarator-id attribute-specifier-seq[opt]
4750 /// declarator-id: [C++ 8]
4751 /// '...'[opt] id-expression
4752 /// '::'[opt] nested-name-specifier[opt] type-name
4754 /// id-expression: [C++ 5.1]
4758 /// unqualified-id: [C++ 5.1]
4760 /// operator-function-id
4761 /// conversion-function-id
4765 /// Note, any additional constructs added here may need corresponding changes
4766 /// in isConstructorDeclarator.
4767 void Parser::ParseDirectDeclarator(Declarator &D) {
4768 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
4770 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
4771 // ParseDeclaratorInternal might already have parsed the scope.
4772 if (D.getCXXScopeSpec().isEmpty()) {
4773 bool EnteringContext = D.getContext() == Declarator::FileContext ||
4774 D.getContext() == Declarator::MemberContext;
4775 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(),
4779 if (D.getCXXScopeSpec().isValid()) {
4780 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
4781 // Change the declaration context for name lookup, until this function
4782 // is exited (and the declarator has been parsed).
4783 DeclScopeObj.EnterDeclaratorScope();
4786 // C++0x [dcl.fct]p14:
4787 // There is a syntactic ambiguity when an ellipsis occurs at the end
4788 // of a parameter-declaration-clause without a preceding comma. In
4789 // this case, the ellipsis is parsed as part of the
4790 // abstract-declarator if the type of the parameter names a template
4791 // parameter pack that has not been expanded; otherwise, it is parsed
4792 // as part of the parameter-declaration-clause.
4793 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
4794 !((D.getContext() == Declarator::PrototypeContext ||
4795 D.getContext() == Declarator::LambdaExprParameterContext ||
4796 D.getContext() == Declarator::BlockLiteralContext) &&
4797 NextToken().is(tok::r_paren) &&
4798 !D.hasGroupingParens() &&
4799 !Actions.containsUnexpandedParameterPacks(D))) {
4800 SourceLocation EllipsisLoc = ConsumeToken();
4801 if (isPtrOperatorToken(Tok.getKind(), getLangOpts())) {
4802 // The ellipsis was put in the wrong place. Recover, and explain to
4803 // the user what they should have done.
4805 diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
4808 D.setEllipsisLoc(EllipsisLoc);
4810 // The ellipsis can't be followed by a parenthesized declarator. We
4811 // check for that in ParseParenDeclarator, after we have disambiguated
4812 // the l_paren token.
4815 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
4816 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
4817 // We found something that indicates the start of an unqualified-id.
4818 // Parse that unqualified-id.
4819 bool AllowConstructorName;
4820 if (D.getDeclSpec().hasTypeSpecifier())
4821 AllowConstructorName = false;
4822 else if (D.getCXXScopeSpec().isSet())
4823 AllowConstructorName =
4824 (D.getContext() == Declarator::FileContext ||
4825 D.getContext() == Declarator::MemberContext);
4827 AllowConstructorName = (D.getContext() == Declarator::MemberContext);
4829 SourceLocation TemplateKWLoc;
4830 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
4831 /*EnteringContext=*/true,
4832 /*AllowDestructorName=*/true,
4833 AllowConstructorName,
4837 // Once we're past the identifier, if the scope was bad, mark the
4838 // whole declarator bad.
4839 D.getCXXScopeSpec().isInvalid()) {
4840 D.SetIdentifier(0, Tok.getLocation());
4841 D.setInvalidType(true);
4843 // Parsed the unqualified-id; update range information and move along.
4844 if (D.getSourceRange().getBegin().isInvalid())
4845 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
4846 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
4848 goto PastIdentifier;
4850 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
4851 assert(!getLangOpts().CPlusPlus &&
4852 "There's a C++-specific check for tok::identifier above");
4853 assert(Tok.getIdentifierInfo() && "Not an identifier?");
4854 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
4856 goto PastIdentifier;
4857 } else if (Tok.is(tok::identifier) && D.diagnoseIdentifier()) {
4858 // A virt-specifier isn't treated as an identifier if it appears after a
4859 // trailing-return-type.
4860 if (D.getContext() != Declarator::TrailingReturnContext ||
4861 !isCXX11VirtSpecifier(Tok)) {
4862 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
4863 << FixItHint::CreateRemoval(Tok.getLocation());
4864 D.SetIdentifier(0, Tok.getLocation());
4866 goto PastIdentifier;
4870 if (Tok.is(tok::l_paren)) {
4871 // direct-declarator: '(' declarator ')'
4872 // direct-declarator: '(' attributes declarator ')'
4873 // Example: 'char (*X)' or 'int (*XX)(void)'
4874 ParseParenDeclarator(D);
4876 // If the declarator was parenthesized, we entered the declarator
4877 // scope when parsing the parenthesized declarator, then exited
4878 // the scope already. Re-enter the scope, if we need to.
4879 if (D.getCXXScopeSpec().isSet()) {
4880 // If there was an error parsing parenthesized declarator, declarator
4881 // scope may have been entered before. Don't do it again.
4882 if (!D.isInvalidType() &&
4883 Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
4884 // Change the declaration context for name lookup, until this function
4885 // is exited (and the declarator has been parsed).
4886 DeclScopeObj.EnterDeclaratorScope();
4888 } else if (D.mayOmitIdentifier()) {
4889 // This could be something simple like "int" (in which case the declarator
4890 // portion is empty), if an abstract-declarator is allowed.
4891 D.SetIdentifier(0, Tok.getLocation());
4893 // The grammar for abstract-pack-declarator does not allow grouping parens.
4894 // FIXME: Revisit this once core issue 1488 is resolved.
4895 if (D.hasEllipsis() && D.hasGroupingParens())
4896 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
4897 diag::ext_abstract_pack_declarator_parens);
4899 if (Tok.getKind() == tok::annot_pragma_parser_crash)
4901 if (D.getContext() == Declarator::MemberContext)
4902 Diag(Tok, diag::err_expected_member_name_or_semi)
4903 << D.getDeclSpec().getSourceRange();
4904 else if (getLangOpts().CPlusPlus) {
4905 if (Tok.is(tok::period) || Tok.is(tok::arrow))
4906 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
4908 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
4909 if (Tok.isAtStartOfLine() && Loc.isValid())
4910 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
4911 << getLangOpts().CPlusPlus;
4913 Diag(Tok, diag::err_expected_unqualified_id)
4914 << getLangOpts().CPlusPlus;
4917 Diag(Tok, diag::err_expected_ident_lparen);
4918 D.SetIdentifier(0, Tok.getLocation());
4919 D.setInvalidType(true);
4923 assert(D.isPastIdentifier() &&
4924 "Haven't past the location of the identifier yet?");
4926 // Don't parse attributes unless we have parsed an unparenthesized name.
4927 if (D.hasName() && !D.getNumTypeObjects())
4928 MaybeParseCXX11Attributes(D);
4931 if (Tok.is(tok::l_paren)) {
4932 // Enter function-declaration scope, limiting any declarators to the
4933 // function prototype scope, including parameter declarators.
4934 ParseScope PrototypeScope(this,
4935 Scope::FunctionPrototypeScope|Scope::DeclScope|
4936 (D.isFunctionDeclaratorAFunctionDeclaration()
4937 ? Scope::FunctionDeclarationScope : 0));
4939 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
4940 // In such a case, check if we actually have a function declarator; if it
4941 // is not, the declarator has been fully parsed.
4942 bool IsAmbiguous = false;
4943 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
4944 // The name of the declarator, if any, is tentatively declared within
4945 // a possible direct initializer.
4946 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
4947 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
4948 TentativelyDeclaredIdentifiers.pop_back();
4949 if (!IsFunctionDecl)
4952 ParsedAttributes attrs(AttrFactory);
4953 BalancedDelimiterTracker T(*this, tok::l_paren);
4955 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
4956 PrototypeScope.Exit();
4957 } else if (Tok.is(tok::l_square)) {
4958 ParseBracketDeclarator(D);
4965 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
4966 /// only called before the identifier, so these are most likely just grouping
4967 /// parens for precedence. If we find that these are actually function
4968 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
4970 /// direct-declarator:
4971 /// '(' declarator ')'
4972 /// [GNU] '(' attributes declarator ')'
4973 /// direct-declarator '(' parameter-type-list ')'
4974 /// direct-declarator '(' identifier-list[opt] ')'
4975 /// [GNU] direct-declarator '(' parameter-forward-declarations
4976 /// parameter-type-list[opt] ')'
4978 void Parser::ParseParenDeclarator(Declarator &D) {
4979 BalancedDelimiterTracker T(*this, tok::l_paren);
4982 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
4984 // Eat any attributes before we look at whether this is a grouping or function
4985 // declarator paren. If this is a grouping paren, the attribute applies to
4986 // the type being built up, for example:
4987 // int (__attribute__(()) *x)(long y)
4988 // If this ends up not being a grouping paren, the attribute applies to the
4989 // first argument, for example:
4990 // int (__attribute__(()) int x)
4991 // In either case, we need to eat any attributes to be able to determine what
4992 // sort of paren this is.
4994 ParsedAttributes attrs(AttrFactory);
4995 bool RequiresArg = false;
4996 if (Tok.is(tok::kw___attribute)) {
4997 ParseGNUAttributes(attrs);
4999 // We require that the argument list (if this is a non-grouping paren) be
5000 // present even if the attribute list was empty.
5004 // Eat any Microsoft extensions.
5005 ParseMicrosoftTypeAttributes(attrs);
5007 // Eat any Borland extensions.
5008 if (Tok.is(tok::kw___pascal))
5009 ParseBorlandTypeAttributes(attrs);
5011 // If we haven't past the identifier yet (or where the identifier would be
5012 // stored, if this is an abstract declarator), then this is probably just
5013 // grouping parens. However, if this could be an abstract-declarator, then
5014 // this could also be the start of function arguments (consider 'void()').
5017 if (!D.mayOmitIdentifier()) {
5018 // If this can't be an abstract-declarator, this *must* be a grouping
5019 // paren, because we haven't seen the identifier yet.
5021 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
5022 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
5023 NextToken().is(tok::r_paren)) || // C++ int(...)
5024 isDeclarationSpecifier() || // 'int(int)' is a function.
5025 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
5026 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
5027 // considered to be a type, not a K&R identifier-list.
5030 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
5034 // If this is a grouping paren, handle:
5035 // direct-declarator: '(' declarator ')'
5036 // direct-declarator: '(' attributes declarator ')'
5038 SourceLocation EllipsisLoc = D.getEllipsisLoc();
5039 D.setEllipsisLoc(SourceLocation());
5041 bool hadGroupingParens = D.hasGroupingParens();
5042 D.setGroupingParens(true);
5043 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5046 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
5047 T.getCloseLocation()),
5048 attrs, T.getCloseLocation());
5050 D.setGroupingParens(hadGroupingParens);
5052 // An ellipsis cannot be placed outside parentheses.
5053 if (EllipsisLoc.isValid())
5054 diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
5059 // Okay, if this wasn't a grouping paren, it must be the start of a function
5060 // argument list. Recognize that this declarator will never have an
5061 // identifier (and remember where it would have been), then call into
5062 // ParseFunctionDeclarator to handle of argument list.
5063 D.SetIdentifier(0, Tok.getLocation());
5065 // Enter function-declaration scope, limiting any declarators to the
5066 // function prototype scope, including parameter declarators.
5067 ParseScope PrototypeScope(this,
5068 Scope::FunctionPrototypeScope | Scope::DeclScope |
5069 (D.isFunctionDeclaratorAFunctionDeclaration()
5070 ? Scope::FunctionDeclarationScope : 0));
5071 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
5072 PrototypeScope.Exit();
5075 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
5076 /// declarator D up to a paren, which indicates that we are parsing function
5079 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
5080 /// immediately after the open paren - they should be considered to be the
5081 /// first argument of a parameter.
5083 /// If RequiresArg is true, then the first argument of the function is required
5084 /// to be present and required to not be an identifier list.
5086 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
5087 /// (C++11) ref-qualifier[opt], exception-specification[opt],
5088 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
5090 /// [C++11] exception-specification:
5091 /// dynamic-exception-specification
5092 /// noexcept-specification
5094 void Parser::ParseFunctionDeclarator(Declarator &D,
5095 ParsedAttributes &FirstArgAttrs,
5096 BalancedDelimiterTracker &Tracker,
5099 assert(getCurScope()->isFunctionPrototypeScope() &&
5100 "Should call from a Function scope");
5101 // lparen is already consumed!
5102 assert(D.isPastIdentifier() && "Should not call before identifier!");
5104 // This should be true when the function has typed arguments.
5105 // Otherwise, it is treated as a K&R-style function.
5106 bool HasProto = false;
5107 // Build up an array of information about the parsed arguments.
5108 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
5109 // Remember where we see an ellipsis, if any.
5110 SourceLocation EllipsisLoc;
5112 DeclSpec DS(AttrFactory);
5113 bool RefQualifierIsLValueRef = true;
5114 SourceLocation RefQualifierLoc;
5115 SourceLocation ConstQualifierLoc;
5116 SourceLocation VolatileQualifierLoc;
5117 ExceptionSpecificationType ESpecType = EST_None;
5118 SourceRange ESpecRange;
5119 SmallVector<ParsedType, 2> DynamicExceptions;
5120 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5121 ExprResult NoexceptExpr;
5122 ParsedAttributes FnAttrs(AttrFactory);
5123 TypeResult TrailingReturnType;
5125 Actions.ActOnStartFunctionDeclarator();
5126 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
5127 EndLoc is the end location for the function declarator.
5128 They differ for trailing return types. */
5129 SourceLocation StartLoc, LocalEndLoc, EndLoc;
5130 SourceLocation LParenLoc, RParenLoc;
5131 LParenLoc = Tracker.getOpenLocation();
5132 StartLoc = LParenLoc;
5134 if (isFunctionDeclaratorIdentifierList()) {
5136 Diag(Tok, diag::err_argument_required_after_attribute);
5138 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
5140 Tracker.consumeClose();
5141 RParenLoc = Tracker.getCloseLocation();
5142 LocalEndLoc = RParenLoc;
5145 if (Tok.isNot(tok::r_paren))
5146 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
5148 else if (RequiresArg)
5149 Diag(Tok, diag::err_argument_required_after_attribute);
5151 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
5153 // If we have the closing ')', eat it.
5154 Tracker.consumeClose();
5155 RParenLoc = Tracker.getCloseLocation();
5156 LocalEndLoc = RParenLoc;
5159 if (getLangOpts().CPlusPlus) {
5160 // FIXME: Accept these components in any order, and produce fixits to
5161 // correct the order if the user gets it wrong. Ideally we should deal
5162 // with the virt-specifier-seq and pure-specifier in the same way.
5164 // Parse cv-qualifier-seq[opt].
5165 ParseTypeQualifierListOpt(DS, /*VendorAttributesAllowed*/ false,
5166 /*CXX11AttributesAllowed*/ false,
5167 /*AtomicAllowed*/ false);
5168 if (!DS.getSourceRange().getEnd().isInvalid()) {
5169 EndLoc = DS.getSourceRange().getEnd();
5170 ConstQualifierLoc = DS.getConstSpecLoc();
5171 VolatileQualifierLoc = DS.getVolatileSpecLoc();
5174 // Parse ref-qualifier[opt].
5175 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
5176 Diag(Tok, getLangOpts().CPlusPlus11 ?
5177 diag::warn_cxx98_compat_ref_qualifier :
5178 diag::ext_ref_qualifier);
5180 RefQualifierIsLValueRef = Tok.is(tok::amp);
5181 RefQualifierLoc = ConsumeToken();
5182 EndLoc = RefQualifierLoc;
5185 // C++11 [expr.prim.general]p3:
5186 // If a declaration declares a member function or member function
5187 // template of a class X, the expression this is a prvalue of type
5188 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5189 // and the end of the function-definition, member-declarator, or
5191 // FIXME: currently, "static" case isn't handled correctly.
5192 bool IsCXX11MemberFunction =
5193 getLangOpts().CPlusPlus11 &&
5194 (D.getContext() == Declarator::MemberContext
5195 ? !D.getDeclSpec().isFriendSpecified()
5196 : D.getContext() == Declarator::FileContext &&
5197 D.getCXXScopeSpec().isValid() &&
5198 Actions.CurContext->isRecord());
5199 Sema::CXXThisScopeRAII ThisScope(Actions,
5200 dyn_cast<CXXRecordDecl>(Actions.CurContext),
5201 DS.getTypeQualifiers() |
5202 (D.getDeclSpec().isConstexprSpecified() &&
5203 !getLangOpts().CPlusPlus1y
5204 ? Qualifiers::Const : 0),
5205 IsCXX11MemberFunction);
5207 // Parse exception-specification[opt].
5208 ESpecType = tryParseExceptionSpecification(ESpecRange,
5210 DynamicExceptionRanges,
5212 if (ESpecType != EST_None)
5213 EndLoc = ESpecRange.getEnd();
5215 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
5216 // after the exception-specification.
5217 MaybeParseCXX11Attributes(FnAttrs);
5219 // Parse trailing-return-type[opt].
5220 LocalEndLoc = EndLoc;
5221 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
5222 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
5223 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
5224 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5225 LocalEndLoc = Tok.getLocation();
5227 TrailingReturnType = ParseTrailingReturnType(Range);
5228 EndLoc = Range.getEnd();
5233 // Remember that we parsed a function type, and remember the attributes.
5234 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
5237 ParamInfo.data(), ParamInfo.size(),
5238 EllipsisLoc, RParenLoc,
5239 DS.getTypeQualifiers(),
5240 RefQualifierIsLValueRef,
5241 RefQualifierLoc, ConstQualifierLoc,
5242 VolatileQualifierLoc,
5243 /*MutableLoc=*/SourceLocation(),
5244 ESpecType, ESpecRange.getBegin(),
5245 DynamicExceptions.data(),
5246 DynamicExceptionRanges.data(),
5247 DynamicExceptions.size(),
5248 NoexceptExpr.isUsable() ?
5249 NoexceptExpr.get() : 0,
5250 StartLoc, LocalEndLoc, D,
5251 TrailingReturnType),
5254 Actions.ActOnEndFunctionDeclarator();
5257 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
5258 /// identifier list form for a K&R-style function: void foo(a,b,c)
5260 /// Note that identifier-lists are only allowed for normal declarators, not for
5261 /// abstract-declarators.
5262 bool Parser::isFunctionDeclaratorIdentifierList() {
5263 return !getLangOpts().CPlusPlus
5264 && Tok.is(tok::identifier)
5265 && !TryAltiVecVectorToken()
5266 // K&R identifier lists can't have typedefs as identifiers, per C99
5268 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
5269 // Identifier lists follow a really simple grammar: the identifiers can
5270 // be followed *only* by a ", identifier" or ")". However, K&R
5271 // identifier lists are really rare in the brave new modern world, and
5272 // it is very common for someone to typo a type in a non-K&R style
5273 // list. If we are presented with something like: "void foo(intptr x,
5274 // float y)", we don't want to start parsing the function declarator as
5275 // though it is a K&R style declarator just because intptr is an
5278 // To handle this, we check to see if the token after the first
5279 // identifier is a "," or ")". Only then do we parse it as an
5281 && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren));
5284 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
5285 /// we found a K&R-style identifier list instead of a typed parameter list.
5287 /// After returning, ParamInfo will hold the parsed parameters.
5289 /// identifier-list: [C99 6.7.5]
5291 /// identifier-list ',' identifier
5293 void Parser::ParseFunctionDeclaratorIdentifierList(
5295 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
5296 // If there was no identifier specified for the declarator, either we are in
5297 // an abstract-declarator, or we are in a parameter declarator which was found
5298 // to be abstract. In abstract-declarators, identifier lists are not valid:
5300 if (!D.getIdentifier())
5301 Diag(Tok, diag::ext_ident_list_in_param);
5303 // Maintain an efficient lookup of params we have seen so far.
5304 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
5307 // If this isn't an identifier, report the error and skip until ')'.
5308 if (Tok.isNot(tok::identifier)) {
5309 Diag(Tok, diag::err_expected_ident);
5310 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
5311 // Forget we parsed anything.
5316 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
5318 // Reject 'typedef int y; int test(x, y)', but continue parsing.
5319 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
5320 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
5322 // Verify that the argument identifier has not already been mentioned.
5323 if (!ParamsSoFar.insert(ParmII)) {
5324 Diag(Tok, diag::err_param_redefinition) << ParmII;
5326 // Remember this identifier in ParamInfo.
5327 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
5332 // Eat the identifier.
5335 // The list continues if we see a comma.
5336 if (Tok.isNot(tok::comma))
5342 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
5343 /// after the opening parenthesis. This function will not parse a K&R-style
5344 /// identifier list.
5346 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
5347 /// caller parsed those arguments immediately after the open paren - they should
5348 /// be considered to be part of the first parameter.
5350 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
5351 /// be the location of the ellipsis, if any was parsed.
5353 /// parameter-type-list: [C99 6.7.5]
5355 /// parameter-list ',' '...'
5356 /// [C++] parameter-list '...'
5358 /// parameter-list: [C99 6.7.5]
5359 /// parameter-declaration
5360 /// parameter-list ',' parameter-declaration
5362 /// parameter-declaration: [C99 6.7.5]
5363 /// declaration-specifiers declarator
5364 /// [C++] declaration-specifiers declarator '=' assignment-expression
5365 /// [C++11] initializer-clause
5366 /// [GNU] declaration-specifiers declarator attributes
5367 /// declaration-specifiers abstract-declarator[opt]
5368 /// [C++] declaration-specifiers abstract-declarator[opt]
5369 /// '=' assignment-expression
5370 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
5371 /// [C++11] attribute-specifier-seq parameter-declaration
5373 void Parser::ParseParameterDeclarationClause(
5375 ParsedAttributes &FirstArgAttrs,
5376 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
5377 SourceLocation &EllipsisLoc) {
5379 if (Tok.is(tok::ellipsis)) {
5380 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
5381 // before deciding this was a parameter-declaration-clause.
5382 EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
5386 // Parse the declaration-specifiers.
5387 // Just use the ParsingDeclaration "scope" of the declarator.
5388 DeclSpec DS(AttrFactory);
5390 // Parse any C++11 attributes.
5391 MaybeParseCXX11Attributes(DS.getAttributes());
5393 // Skip any Microsoft attributes before a param.
5394 MaybeParseMicrosoftAttributes(DS.getAttributes());
5396 SourceLocation DSStart = Tok.getLocation();
5398 // If the caller parsed attributes for the first argument, add them now.
5399 // Take them so that we only apply the attributes to the first parameter.
5400 // FIXME: If we can leave the attributes in the token stream somehow, we can
5401 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
5403 DS.takeAttributesFrom(FirstArgAttrs);
5405 ParseDeclarationSpecifiers(DS);
5408 // Parse the declarator. This is "PrototypeContext" or
5409 // "LambdaExprParameterContext", because we must accept either
5410 // 'declarator' or 'abstract-declarator' here.
5411 Declarator ParmDeclarator(DS,
5412 D.getContext() == Declarator::LambdaExprContext ?
5413 Declarator::LambdaExprParameterContext :
5414 Declarator::PrototypeContext);
5415 ParseDeclarator(ParmDeclarator);
5417 // Parse GNU attributes, if present.
5418 MaybeParseGNUAttributes(ParmDeclarator);
5420 // Remember this parsed parameter in ParamInfo.
5421 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
5423 // DefArgToks is used when the parsing of default arguments needs
5425 CachedTokens *DefArgToks = 0;
5427 // If no parameter was specified, verify that *something* was specified,
5428 // otherwise we have a missing type and identifier.
5429 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == 0 &&
5430 ParmDeclarator.getNumTypeObjects() == 0) {
5431 // Completely missing, emit error.
5432 Diag(DSStart, diag::err_missing_param);
5434 // Otherwise, we have something. Add it and let semantic analysis try
5435 // to grok it and add the result to the ParamInfo we are building.
5437 // Inform the actions module about the parameter declarator, so it gets
5438 // added to the current scope.
5439 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(),
5441 // Parse the default argument, if any. We parse the default
5442 // arguments in all dialects; the semantic analysis in
5443 // ActOnParamDefaultArgument will reject the default argument in
5445 if (Tok.is(tok::equal)) {
5446 SourceLocation EqualLoc = Tok.getLocation();
5448 // Parse the default argument
5449 if (D.getContext() == Declarator::MemberContext) {
5450 // If we're inside a class definition, cache the tokens
5451 // corresponding to the default argument. We'll actually parse
5452 // them when we see the end of the class definition.
5453 // FIXME: Can we use a smart pointer for Toks?
5454 DefArgToks = new CachedTokens;
5456 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
5459 Actions.ActOnParamDefaultArgumentError(Param);
5461 // Mark the end of the default argument so that we know when to
5462 // stop when we parse it later on.
5464 DefArgEnd.startToken();
5465 DefArgEnd.setKind(tok::cxx_defaultarg_end);
5466 DefArgEnd.setLocation(Tok.getLocation());
5467 DefArgToks->push_back(DefArgEnd);
5468 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
5469 (*DefArgToks)[1].getLocation());
5475 // The argument isn't actually potentially evaluated unless it is
5477 EnterExpressionEvaluationContext Eval(Actions,
5478 Sema::PotentiallyEvaluatedIfUsed,
5481 ExprResult DefArgResult;
5482 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
5483 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
5484 DefArgResult = ParseBraceInitializer();
5486 DefArgResult = ParseAssignmentExpression();
5487 if (DefArgResult.isInvalid()) {
5488 Actions.ActOnParamDefaultArgumentError(Param);
5489 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
5491 // Inform the actions module about the default argument
5492 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
5493 DefArgResult.take());
5498 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
5499 ParmDeclarator.getIdentifierLoc(),
5500 Param, DefArgToks));
5503 // If the next token is a comma, consume it and keep reading arguments.
5504 if (Tok.isNot(tok::comma)) {
5505 if (Tok.is(tok::ellipsis)) {
5506 EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
5508 if (!getLangOpts().CPlusPlus) {
5509 // We have ellipsis without a preceding ',', which is ill-formed
5510 // in C. Complain and provide the fix.
5511 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
5512 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
5519 // Consume the comma.
5525 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5526 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5527 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5528 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5529 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5530 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5531 /// attribute-specifier-seq[opt]
5532 void Parser::ParseBracketDeclarator(Declarator &D) {
5533 if (CheckProhibitedCXX11Attribute())
5536 BalancedDelimiterTracker T(*this, tok::l_square);
5539 // C array syntax has many features, but by-far the most common is [] and [4].
5540 // This code does a fast path to handle some of the most obvious cases.
5541 if (Tok.getKind() == tok::r_square) {
5543 ParsedAttributes attrs(AttrFactory);
5544 MaybeParseCXX11Attributes(attrs);
5546 // Remember that we parsed the empty array type.
5547 ExprResult NumElements;
5548 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
5549 T.getOpenLocation(),
5550 T.getCloseLocation()),
5551 attrs, T.getCloseLocation());
5553 } else if (Tok.getKind() == tok::numeric_constant &&
5554 GetLookAheadToken(1).is(tok::r_square)) {
5555 // [4] is very common. Parse the numeric constant expression.
5556 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
5560 ParsedAttributes attrs(AttrFactory);
5561 MaybeParseCXX11Attributes(attrs);
5563 // Remember that we parsed a array type, and remember its features.
5564 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false,
5566 T.getOpenLocation(),
5567 T.getCloseLocation()),
5568 attrs, T.getCloseLocation());
5572 // If valid, this location is the position where we read the 'static' keyword.
5573 SourceLocation StaticLoc;
5574 if (Tok.is(tok::kw_static))
5575 StaticLoc = ConsumeToken();
5577 // If there is a type-qualifier-list, read it now.
5578 // Type qualifiers in an array subscript are a C99 feature.
5579 DeclSpec DS(AttrFactory);
5580 ParseTypeQualifierListOpt(DS, false /*no attributes*/);
5582 // If we haven't already read 'static', check to see if there is one after the
5583 // type-qualifier-list.
5584 if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
5585 StaticLoc = ConsumeToken();
5587 // Handle "direct-declarator [ type-qual-list[opt] * ]".
5588 bool isStar = false;
5589 ExprResult NumElements;
5591 // Handle the case where we have '[*]' as the array size. However, a leading
5592 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
5593 // the token after the star is a ']'. Since stars in arrays are
5594 // infrequent, use of lookahead is not costly here.
5595 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
5596 ConsumeToken(); // Eat the '*'.
5598 if (StaticLoc.isValid()) {
5599 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
5600 StaticLoc = SourceLocation(); // Drop the static.
5603 } else if (Tok.isNot(tok::r_square)) {
5604 // Note, in C89, this production uses the constant-expr production instead
5605 // of assignment-expr. The only difference is that assignment-expr allows
5606 // things like '=' and '*='. Sema rejects these in C89 mode because they
5607 // are not i-c-e's, so we don't need to distinguish between the two here.
5609 // Parse the constant-expression or assignment-expression now (depending
5611 if (getLangOpts().CPlusPlus) {
5612 NumElements = ParseConstantExpression();
5614 EnterExpressionEvaluationContext Unevaluated(Actions,
5615 Sema::ConstantEvaluated);
5616 NumElements = ParseAssignmentExpression();
5620 // If there was an error parsing the assignment-expression, recover.
5621 if (NumElements.isInvalid()) {
5622 D.setInvalidType(true);
5623 // If the expression was invalid, skip it.
5624 SkipUntil(tok::r_square, StopAtSemi);
5630 ParsedAttributes attrs(AttrFactory);
5631 MaybeParseCXX11Attributes(attrs);
5633 // Remember that we parsed a array type, and remember its features.
5634 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
5635 StaticLoc.isValid(), isStar,
5636 NumElements.release(),
5637 T.getOpenLocation(),
5638 T.getCloseLocation()),
5639 attrs, T.getCloseLocation());
5642 /// [GNU] typeof-specifier:
5643 /// typeof ( expressions )
5644 /// typeof ( type-name )
5645 /// [GNU/C++] typeof unary-expression
5647 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
5648 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
5650 SourceLocation StartLoc = ConsumeToken();
5652 const bool hasParens = Tok.is(tok::l_paren);
5654 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
5655 Sema::ReuseLambdaContextDecl);
5659 SourceRange CastRange;
5660 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
5663 DS.setTypeofParensRange(CastRange);
5665 if (CastRange.getEnd().isInvalid())
5666 // FIXME: Not accurate, the range gets one token more than it should.
5667 DS.SetRangeEnd(Tok.getLocation());
5669 DS.SetRangeEnd(CastRange.getEnd());
5673 DS.SetTypeSpecError();
5677 const char *PrevSpec = 0;
5679 // Check for duplicate type specifiers (e.g. "int typeof(int)").
5680 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
5682 Diag(StartLoc, DiagID) << PrevSpec;
5686 // If we get here, the operand to the typeof was an expresion.
5687 if (Operand.isInvalid()) {
5688 DS.SetTypeSpecError();
5692 // We might need to transform the operand if it is potentially evaluated.
5693 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
5694 if (Operand.isInvalid()) {
5695 DS.SetTypeSpecError();
5699 const char *PrevSpec = 0;
5701 // Check for duplicate type specifiers (e.g. "int typeof(int)").
5702 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
5703 DiagID, Operand.get()))
5704 Diag(StartLoc, DiagID) << PrevSpec;
5707 /// [C11] atomic-specifier:
5708 /// _Atomic ( type-name )
5710 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
5711 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
5712 "Not an atomic specifier");
5714 SourceLocation StartLoc = ConsumeToken();
5715 BalancedDelimiterTracker T(*this, tok::l_paren);
5716 if (T.consumeOpen())
5719 TypeResult Result = ParseTypeName();
5720 if (Result.isInvalid()) {
5721 SkipUntil(tok::r_paren, StopAtSemi);
5728 if (T.getCloseLocation().isInvalid())
5731 DS.setTypeofParensRange(T.getRange());
5732 DS.SetRangeEnd(T.getCloseLocation());
5734 const char *PrevSpec = 0;
5736 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
5737 DiagID, Result.release()))
5738 Diag(StartLoc, DiagID) << PrevSpec;
5742 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
5743 /// from TryAltiVecVectorToken.
5744 bool Parser::TryAltiVecVectorTokenOutOfLine() {
5745 Token Next = NextToken();
5746 switch (Next.getKind()) {
5747 default: return false;
5750 case tok::kw_signed:
5751 case tok::kw_unsigned:
5756 case tok::kw_double:
5758 case tok::kw___pixel:
5759 Tok.setKind(tok::kw___vector);
5761 case tok::identifier:
5762 if (Next.getIdentifierInfo() == Ident_pixel) {
5763 Tok.setKind(tok::kw___vector);
5766 if (Next.getIdentifierInfo() == Ident_bool) {
5767 Tok.setKind(tok::kw___vector);
5774 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
5775 const char *&PrevSpec, unsigned &DiagID,
5777 if (Tok.getIdentifierInfo() == Ident_vector) {
5778 Token Next = NextToken();
5779 switch (Next.getKind()) {
5782 case tok::kw_signed:
5783 case tok::kw_unsigned:
5788 case tok::kw_double:
5790 case tok::kw___pixel:
5791 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
5793 case tok::identifier:
5794 if (Next.getIdentifierInfo() == Ident_pixel) {
5795 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
5798 if (Next.getIdentifierInfo() == Ident_bool) {
5799 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
5806 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
5807 DS.isTypeAltiVecVector()) {
5808 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
5810 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
5811 DS.isTypeAltiVecVector()) {
5812 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID);