ParseDecl.cpp revision 152b4e4652baedfceba1cd8115515629225e713f
166ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton//===--- ParseDecl.cpp - Declaration Parsing ------------------------------===//
266ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton//
366ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton//                     The LLVM Compiler Infrastructure
466ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton//
566ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton// This file is distributed under the University of Illinois Open Source
666ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton// License. See LICENSE.TXT for details.
766ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton//
866ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton//===----------------------------------------------------------------------===//
966ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton//
1066ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton//  This file implements the Declaration portions of the Parser interfaces.
1166ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton//
12915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata//===----------------------------------------------------------------------===//
13915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata
1466ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton#include "clang/Parse/Parser.h"
1566ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton#include "RAIIObjectsForParser.h"
160d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton#include "clang/AST/DeclTemplate.h"
1766ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton#include "clang/Basic/AddressSpaces.h"
1866ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton#include "clang/Basic/CharInfo.h"
1966ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton#include "clang/Basic/OpenCL.h"
2066ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton#include "clang/Parse/ParseDiagnostic.h"
2166ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton#include "clang/Sema/Lookup.h"
2266ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton#include "clang/Sema/ParsedTemplate.h"
2366ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton#include "clang/Sema/PrettyDeclStackTrace.h"
2466ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton#include "clang/Sema/Scope.h"
2566ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton#include "llvm/ADT/SmallSet.h"
2666ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton#include "llvm/ADT/SmallString.h"
2766ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton#include "llvm/ADT/StringSwitch.h"
2866ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Claytonusing namespace clang;
2966ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton
3066ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton//===----------------------------------------------------------------------===//
3166ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton// C99 6.7: Declarations.
3247da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham//===----------------------------------------------------------------------===//
3352f792329be5db8e38961350589e97e8f2823acdGreg Clayton
3452f792329be5db8e38961350589e97e8f2823acdGreg Clayton/// ParseTypeName
3552f792329be5db8e38961350589e97e8f2823acdGreg Clayton///       type-name: [C99 6.7.6]
3652f792329be5db8e38961350589e97e8f2823acdGreg Clayton///         specifier-qualifier-list abstract-declarator[opt]
3747da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham///
3847da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham/// Called type-id in C++.
3947da810225d8674eb9158bcf5f1f5b847cbaeedfJim InghamTypeResult Parser::ParseTypeName(SourceRange *Range,
40915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata                                 Declarator::TheContext Context,
41915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata                                 AccessSpecifier AS,
4247da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham                                 Decl **OwnedType,
4347da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham                                 ParsedAttributes *Attrs) {
4452f792329be5db8e38961350589e97e8f2823acdGreg Clayton  DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
4552f792329be5db8e38961350589e97e8f2823acdGreg Clayton  if (DSC == DSC_normal)
4652f792329be5db8e38961350589e97e8f2823acdGreg Clayton    DSC = DSC_type_specifier;
4752f792329be5db8e38961350589e97e8f2823acdGreg Clayton
48fa3a16a2ea380ef38388ebe323817bd1b32c20cdJim Ingham  // Parse the common declaration-specifiers piece.
49427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton  DeclSpec DS(AttrFactory);
50915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata  if (Attrs)
51915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata    DS.addAttributes(Attrs->getList());
52427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton  ParseSpecifierQualifierList(DS, AS, DSC);
53427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton  if (OwnedType)
54427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton    *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : 0;
55427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton
56427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton  // Parse the abstract-declarator, if present.
57915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata  Declarator DeclaratorInfo(DS, Context);
58427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton  ParseDeclarator(DeclaratorInfo);
59427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton  if (Range)
6047da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham    *Range = DeclaratorInfo.getSourceRange();
6147da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham
6247da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham  if (DeclaratorInfo.isInvalidType())
6347da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham    return true;
6452f792329be5db8e38961350589e97e8f2823acdGreg Clayton
6547da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham  return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
66915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata}
67915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata
6847da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham
6947da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham/// isAttributeLateParsed - Return true if the attribute has arguments that
7047da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham/// require late parsing.
7147da810225d8674eb9158bcf5f1f5b847cbaeedfJim Inghamstatic bool isAttributeLateParsed(const IdentifierInfo &II) {
7247da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham    return llvm::StringSwitch<bool>(II.getName())
73915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata#include "clang/Parse/AttrLateParsed.inc"
74915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata        .Default(false);
7547da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham}
7647da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham
7752f792329be5db8e38961350589e97e8f2823acdGreg Clayton/// ParseGNUAttributes - Parse a non-empty attributes list.
7852f792329be5db8e38961350589e97e8f2823acdGreg Clayton///
7952f792329be5db8e38961350589e97e8f2823acdGreg Clayton/// [GNU] attributes:
8052f792329be5db8e38961350589e97e8f2823acdGreg Clayton///         attribute
8152f792329be5db8e38961350589e97e8f2823acdGreg Clayton///         attributes attribute
82fa3a16a2ea380ef38388ebe323817bd1b32c20cdJim Ingham///
83427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton/// [GNU]  attribute:
84915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata///          '__attribute__' '(' '(' attribute-list ')' ')'
85915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata///
86427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton/// [GNU]  attribute-list:
87427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton///          attrib
889ac3d8b086bbe0413fa85351383072e9ce8b4a60Sean Callanan///          attribute_list ',' attrib
899ac3d8b086bbe0413fa85351383072e9ce8b4a60Sean Callanan///
909ac3d8b086bbe0413fa85351383072e9ce8b4a60Sean Callanan/// [GNU]  attrib:
919ac3d8b086bbe0413fa85351383072e9ce8b4a60Sean Callanan///          empty
929ac3d8b086bbe0413fa85351383072e9ce8b4a60Sean Callanan///          attrib-name
939ac3d8b086bbe0413fa85351383072e9ce8b4a60Sean Callanan///          attrib-name '(' identifier ')'
949ac3d8b086bbe0413fa85351383072e9ce8b4a60Sean Callanan///          attrib-name '(' identifier ',' nonempty-expr-list ')'
95427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
96427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton///
9752f792329be5db8e38961350589e97e8f2823acdGreg Clayton/// [GNU]  attrib-name:
98427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton///          identifier
99427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton///          typespec
100427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton///          typequal
101915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata///          storageclass
102427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton///
103427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton/// FIXME: The GCC grammar/code for this construct implies we need two
10447da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham/// token lookahead. Comment from gcc: "If they start with an identifier
10552f792329be5db8e38961350589e97e8f2823acdGreg Clayton/// which is followed by a comma or close parenthesis, then the arguments
10652f792329be5db8e38961350589e97e8f2823acdGreg Clayton/// start with that identifier; otherwise they are an expression list."
10752f792329be5db8e38961350589e97e8f2823acdGreg Clayton///
10852f792329be5db8e38961350589e97e8f2823acdGreg Clayton/// GCC does not require the ',' between attribs in an attribute-list.
10952f792329be5db8e38961350589e97e8f2823acdGreg Clayton///
11052f792329be5db8e38961350589e97e8f2823acdGreg Clayton/// At the moment, I am not doing 2 token lookahead. I am also unaware of
11152f792329be5db8e38961350589e97e8f2823acdGreg Clayton/// any attributes that don't work (based on my limited testing). Most
11247da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham/// attributes are very simple in practice. Until we find a bug, I don't see
11347da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham/// a pressing need to implement the 2 token lookahead.
11447da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham
11547da810225d8674eb9158bcf5f1f5b847cbaeedfJim Inghamvoid Parser::ParseGNUAttributes(ParsedAttributes &attrs,
11647da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham                                SourceLocation *endLoc,
11747da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham                                LateParsedAttrList *LateAttrs) {
118915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata  assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
119915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata
12047da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham  while (Tok.is(tok::kw___attribute)) {
12147da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham    ConsumeToken();
1221586d9720002e407a3a097baf302de5fa4ca9c1bJim Ingham    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
1231586d9720002e407a3a097baf302de5fa4ca9c1bJim Ingham                         "attribute")) {
12452f792329be5db8e38961350589e97e8f2823acdGreg Clayton      SkipUntil(tok::r_paren, true); // skip until ) or ;
12552f792329be5db8e38961350589e97e8f2823acdGreg Clayton      return;
1261586d9720002e407a3a097baf302de5fa4ca9c1bJim Ingham    }
12752f792329be5db8e38961350589e97e8f2823acdGreg Clayton    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
1281586d9720002e407a3a097baf302de5fa4ca9c1bJim Ingham      SkipUntil(tok::r_paren, true); // skip until ) or ;
1291586d9720002e407a3a097baf302de5fa4ca9c1bJim Ingham      return;
13052f792329be5db8e38961350589e97e8f2823acdGreg Clayton    }
13152f792329be5db8e38961350589e97e8f2823acdGreg Clayton    // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
13252f792329be5db8e38961350589e97e8f2823acdGreg Clayton    while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
13352f792329be5db8e38961350589e97e8f2823acdGreg Clayton           Tok.is(tok::comma)) {
13452f792329be5db8e38961350589e97e8f2823acdGreg Clayton      if (Tok.is(tok::comma)) {
13552f792329be5db8e38961350589e97e8f2823acdGreg Clayton        // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
13652f792329be5db8e38961350589e97e8f2823acdGreg Clayton        ConsumeToken();
137fa3a16a2ea380ef38388ebe323817bd1b32c20cdJim Ingham        continue;
138427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton      }
139915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata      // we have an identifier or declaration specifier (const, int, etc.)
140915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
14166ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton      SourceLocation AttrNameLoc = ConsumeToken();
14266ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton
14366ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton      if (Tok.is(tok::l_paren)) {
14466ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton        // handle "parameterized" attributes
14566ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton        if (LateAttrs && isAttributeLateParsed(*AttrName)) {
14666ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton          LateParsedAttribute *LA =
14752f792329be5db8e38961350589e97e8f2823acdGreg Clayton            new LateParsedAttribute(this, *AttrName, AttrNameLoc);
14852f792329be5db8e38961350589e97e8f2823acdGreg Clayton          LateAttrs->push_back(LA);
14966ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton
150d171972ecc7788bdb02d3e81420a24841e09a2bfGreg Clayton          // Attributes in a class are parsed at the end of the class, along
15180c1f6f4de8655f80d3bb4fc29c4e69528285aa7Jim Ingham          // with other late-parsed declarations.
152915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata          if (!ClassStack.empty() && !LateAttrs->parseSoon())
153427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton            getCurrentClass().LateParsedDeclarations.push_back(LA);
154427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton
15547da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham          // consume everything up to and including the matching right parens
15652f792329be5db8e38961350589e97e8f2823acdGreg Clayton          ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false);
15752f792329be5db8e38961350589e97e8f2823acdGreg Clayton
15852f792329be5db8e38961350589e97e8f2823acdGreg Clayton          Token Eof;
15952f792329be5db8e38961350589e97e8f2823acdGreg Clayton          Eof.startToken();
16052f792329be5db8e38961350589e97e8f2823acdGreg Clayton          Eof.setLocation(Tok.getLocation());
16152f792329be5db8e38961350589e97e8f2823acdGreg Clayton          LA->Toks.push_back(Eof);
16247da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham        } else {
16347da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham          ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc,
16447da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham                                0, SourceLocation(), AttributeList::AS_GNU);
16547da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham        }
16647da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham      } else {
16747da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham        attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
16847da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham                     0, SourceLocation(), 0, 0, AttributeList::AS_GNU);
16947da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham      }
17047da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham    }
17152f792329be5db8e38961350589e97e8f2823acdGreg Clayton    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
17252f792329be5db8e38961350589e97e8f2823acdGreg Clayton      SkipUntil(tok::r_paren, false);
17352f792329be5db8e38961350589e97e8f2823acdGreg Clayton    SourceLocation Loc = Tok.getLocation();
17452f792329be5db8e38961350589e97e8f2823acdGreg Clayton    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
17552f792329be5db8e38961350589e97e8f2823acdGreg Clayton      SkipUntil(tok::r_paren, false);
17652f792329be5db8e38961350589e97e8f2823acdGreg Clayton    }
177fa3a16a2ea380ef38388ebe323817bd1b32c20cdJim Ingham    if (endLoc)
178427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton      *endLoc = Loc;
179915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata  }
180915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata}
181427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton
182427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton/// \brief Determine whether the given attribute has all expression arguments.
183427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Claytonstatic bool attributeHasExprArgs(const IdentifierInfo &II) {
184427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton  return llvm::StringSwitch<bool>(II.getName())
185427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton#include "clang/Parse/AttrExprArgs.inc"
186427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton           .Default(false);
187427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton}
188427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton
189427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton/// Parse the arguments to a parameterized GNU attribute or
190427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton/// a C++11 attribute in "gnu" namespace.
191427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Claytonvoid Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
192427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton                                   SourceLocation AttrNameLoc,
19352f792329be5db8e38961350589e97e8f2823acdGreg Clayton                                   ParsedAttributes &Attrs,
19452f792329be5db8e38961350589e97e8f2823acdGreg Clayton                                   SourceLocation *EndLoc,
195427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton                                   IdentifierInfo *ScopeName,
196427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton                                   SourceLocation ScopeLoc,
197427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton                                   AttributeList::Syntax Syntax) {
198915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata
199d171972ecc7788bdb02d3e81420a24841e09a2bfGreg Clayton  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
200d171972ecc7788bdb02d3e81420a24841e09a2bfGreg Clayton
20147da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham  // Availability attributes have their own grammar.
20247da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham  if (AttrName->isStr("availability")) {
20347da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham    ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
20447da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham    return;
20547da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham  }
20647da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham  // Thread safety attributes fit into the FIXME case above, so we
20747da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham  // just parse the arguments as a list of expressions
20847da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham  if (IsThreadSafetyAttribute(AttrName->getName())) {
20947da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham    ParseThreadSafetyAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
21047da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham    return;
21147da810225d8674eb9158bcf5f1f5b847cbaeedfJim Ingham  }
21252f792329be5db8e38961350589e97e8f2823acdGreg Clayton  // Type safety attributes have their own grammar.
21352f792329be5db8e38961350589e97e8f2823acdGreg Clayton  if (AttrName->isStr("type_tag_for_datatype")) {
214fa3a16a2ea380ef38388ebe323817bd1b32c20cdJim Ingham    ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
215427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton    return;
216915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata  }
217915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata
218d171972ecc7788bdb02d3e81420a24841e09a2bfGreg Clayton  ConsumeParen(); // ignore the left paren loc for now
219d171972ecc7788bdb02d3e81420a24841e09a2bfGreg Clayton
220d171972ecc7788bdb02d3e81420a24841e09a2bfGreg Clayton  IdentifierInfo *ParmName = 0;
22166ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  SourceLocation ParmLoc;
22266ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  bool BuiltinType = false;
22352f792329be5db8e38961350589e97e8f2823acdGreg Clayton
22452f792329be5db8e38961350589e97e8f2823acdGreg Clayton  TypeResult T;
22552f792329be5db8e38961350589e97e8f2823acdGreg Clayton  SourceRange TypeRange;
2261586d9720002e407a3a097baf302de5fa4ca9c1bJim Ingham  bool TypeParsed = false;
2271586d9720002e407a3a097baf302de5fa4ca9c1bJim Ingham
2281586d9720002e407a3a097baf302de5fa4ca9c1bJim Ingham  switch (Tok.getKind()) {
2291586d9720002e407a3a097baf302de5fa4ca9c1bJim Ingham  case tok::kw_char:
2301586d9720002e407a3a097baf302de5fa4ca9c1bJim Ingham  case tok::kw_wchar_t:
2311586d9720002e407a3a097baf302de5fa4ca9c1bJim Ingham  case tok::kw_char16_t:
2321586d9720002e407a3a097baf302de5fa4ca9c1bJim Ingham  case tok::kw_char32_t:
2331586d9720002e407a3a097baf302de5fa4ca9c1bJim Ingham  case tok::kw_bool:
2341586d9720002e407a3a097baf302de5fa4ca9c1bJim Ingham  case tok::kw_short:
23566ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  case tok::kw_int:
23666ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  case tok::kw_long:
23766ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  case tok::kw___int64:
23866ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  case tok::kw___int128:
23952f792329be5db8e38961350589e97e8f2823acdGreg Clayton  case tok::kw_signed:
240931acecd4e3af534028936431dc0f75a9fd6eb02Sean Callanan  case tok::kw_unsigned:
24166ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  case tok::kw_float:
24266ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  case tok::kw_double:
24366ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  case tok::kw_void:
24466ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  case tok::kw_typeof:
24566ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton    // __attribute__(( vec_type_hint(char) ))
24666ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton    BuiltinType = true;
24766ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton    T = ParseTypeName(&TypeRange);
24866ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton    TypeParsed = true;
24966ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton    break;
25066ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton
251fe6dc6e241c52822710380cec0931351a1d7b2d3Greg Clayton  case tok::identifier:
25266ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton    if (AttrName->isStr("vec_type_hint")) {
25366ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton      T = ParseTypeName(&TypeRange);
254427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton      TypeParsed = true;
25552f792329be5db8e38961350589e97e8f2823acdGreg Clayton      break;
256427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton    }
257427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton    // If the attribute has all expression arguments, and not a "parameter",
258427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton    // break out to handle it below.
259427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton    if (attributeHasExprArgs(*AttrName))
260427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton      break;
261427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton    ParmName = Tok.getIdentifierInfo();
262427f290ff96f3ab9f2cf3a1af7001d2c560424c7Greg Clayton    ParmLoc = ConsumeToken();
26366ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton    break;
26466ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton
26536da2aa6dc5ad9994b638ed09eb81c44cc05540bGreg Clayton  default:
26666ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton    break;
26766ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  }
26852f792329be5db8e38961350589e97e8f2823acdGreg Clayton
26966ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  ExprVector ArgExprs;
27066ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  bool isInvalid = false;
27166ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  bool isParmType = false;
27266ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton
27366ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  if (!BuiltinType && !AttrName->isStr("vec_type_hint") &&
27466ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton      (ParmLoc.isValid() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren))) {
27552f792329be5db8e38961350589e97e8f2823acdGreg Clayton    // Eat the comma.
27666ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton    if (ParmLoc.isValid())
27766ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton      ConsumeToken();
27866ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton
279fa3a16a2ea380ef38388ebe323817bd1b32c20cdJim Ingham    // Parse the non-empty comma-separated list of expressions.
280fa3a16a2ea380ef38388ebe323817bd1b32c20cdJim Ingham    while (1) {
28166ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton      ExprResult ArgExpr(ParseAssignmentExpression());
28266ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton      if (ArgExpr.isInvalid()) {
28366ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton        SkipUntil(tok::r_paren);
284fa3a16a2ea380ef38388ebe323817bd1b32c20cdJim Ingham        return;
28566ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton      }
28666ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton      ArgExprs.push_back(ArgExpr.release());
28766ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton      if (Tok.isNot(tok::comma))
28866ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton        break;
289fa3a16a2ea380ef38388ebe323817bd1b32c20cdJim Ingham      ConsumeToken(); // Eat the comma, move to the next argument
29066ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton    }
29166ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  }
29266ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton  else if (Tok.is(tok::less) && AttrName->isStr("iboutletcollection")) {
29366ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton    if (!ExpectAndConsume(tok::less, diag::err_expected_less_after, "<",
29466ed2fbeaf588fe4105a1305f7e956dcf9fbe299Greg Clayton                          tok::greater)) {
295915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata      while (Tok.is(tok::identifier)) {
296915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata        ConsumeToken();
297915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata        if (Tok.is(tok::greater))
298915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata          break;
299915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata        if (Tok.is(tok::comma)) {
300915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata          ConsumeToken();
301915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata          continue;
302915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata        }
303915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata      }
304915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata      if (Tok.isNot(tok::greater))
305915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata        Diag(Tok, diag::err_iboutletcollection_with_protocol);
306915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata      SkipUntil(tok::r_paren, false, true); // skip until ')'
307915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata    }
308915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata  } else if (AttrName->isStr("vec_type_hint")) {
309915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata    if (T.get() && !T.isInvalid())
310915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata      isParmType = true;
311915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata    else {
312915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata      if (Tok.is(tok::identifier))
313915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata        ConsumeToken();
314dfafa141aa9d0dd0596bf08b3f941be8c308316dJohnny Chen      if (TypeParsed)
315dfafa141aa9d0dd0596bf08b3f941be8c308316dJohnny Chen        isInvalid = true;
316dfafa141aa9d0dd0596bf08b3f941be8c308316dJohnny Chen    }
317dfafa141aa9d0dd0596bf08b3f941be8c308316dJohnny Chen  }
318dfafa141aa9d0dd0596bf08b3f941be8c308316dJohnny Chen
319dfafa141aa9d0dd0596bf08b3f941be8c308316dJohnny Chen  SourceLocation RParen = Tok.getLocation();
320dfafa141aa9d0dd0596bf08b3f941be8c308316dJohnny Chen  if (!ExpectAndConsume(tok::r_paren, diag::err_expected_rparen) &&
321915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata      !isInvalid) {
32236da2aa6dc5ad9994b638ed09eb81c44cc05540bGreg Clayton    SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
323915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata    if (isParmType) {
324915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata      Attrs.addNewTypeAttr(AttrName, SourceRange(AttrLoc, RParen), ScopeName,
325915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata                           ScopeLoc, ParmName, ParmLoc, T.get(), Syntax);
326915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata    } else {
327915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata      AttributeList *attr = Attrs.addNew(
328915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata          AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc, ParmName,
329915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata          ParmLoc, ArgExprs.data(), ArgExprs.size(), Syntax);
330915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata      if (BuiltinType &&
331915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata          attr->getKind() == AttributeList::AT_IBOutletCollection)
332915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata        Diag(Tok, diag::err_iboutletcollection_builtintype);
333915448044bac6fdac22a33cc46697dcb771a8df2Enrico Granata    }
3340d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton  }
3350d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton}
3360d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton
3370d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton/// \brief Parses a single argument for a declspec, including the
3380d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton/// surrounding parens.
3390d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Claytonvoid Parser::ParseMicrosoftDeclSpecWithSingleArg(IdentifierInfo *AttrName,
3400d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton                                                 SourceLocation AttrNameLoc,
3410d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton                                                 ParsedAttributes &Attrs)
3420d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton{
3430d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton  BalancedDelimiterTracker T(*this, tok::l_paren);
3440d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton  if (T.expectAndConsume(diag::err_expected_lparen_after,
3450d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton                         AttrName->getNameStart(), tok::r_paren))
3460d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton    return;
3470d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton
3480d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton  ExprResult ArgExpr(ParseConstantExpression());
3490d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton  if (ArgExpr.isInvalid()) {
3500d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton    T.skipToEnd();
3510d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton    return;
3520d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton  }
3530d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton  Expr *ExprList = ArgExpr.take();
3540d0f56d5b81afb0f3d2e71c53947658a4c667f35Greg Clayton  Attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
355               &ExprList, 1, AttributeList::AS_Declspec);
356
357  T.consumeClose();
358}
359
360/// \brief Determines whether a declspec is a "simple" one requiring no
361/// arguments.
362bool Parser::IsSimpleMicrosoftDeclSpec(IdentifierInfo *Ident) {
363  return llvm::StringSwitch<bool>(Ident->getName())
364    .Case("dllimport", true)
365    .Case("dllexport", true)
366    .Case("noreturn", true)
367    .Case("nothrow", true)
368    .Case("noinline", true)
369    .Case("naked", true)
370    .Case("appdomain", true)
371    .Case("process", true)
372    .Case("jitintrinsic", true)
373    .Case("noalias", true)
374    .Case("restrict", true)
375    .Case("novtable", true)
376    .Case("selectany", true)
377    .Case("thread", true)
378    .Case("safebuffers", true )
379    .Default(false);
380}
381
382/// \brief Attempts to parse a declspec which is not simple (one that takes
383/// parameters).  Will return false if we properly handled the declspec, or
384/// true if it is an unknown declspec.
385void Parser::ParseComplexMicrosoftDeclSpec(IdentifierInfo *Ident,
386                                           SourceLocation Loc,
387                                           ParsedAttributes &Attrs) {
388  // Try to handle the easy case first -- these declspecs all take a single
389  // parameter as their argument.
390  if (llvm::StringSwitch<bool>(Ident->getName())
391      .Case("uuid", true)
392      .Case("align", true)
393      .Case("allocate", true)
394      .Default(false)) {
395    ParseMicrosoftDeclSpecWithSingleArg(Ident, Loc, Attrs);
396  } else if (Ident->getName() == "deprecated") {
397    // The deprecated declspec has an optional single argument, so we will
398    // check for a l-paren to decide whether we should parse an argument or
399    // not.
400    if (Tok.getKind() == tok::l_paren)
401      ParseMicrosoftDeclSpecWithSingleArg(Ident, Loc, Attrs);
402    else
403      Attrs.addNew(Ident, Loc, 0, Loc, 0, SourceLocation(), 0, 0,
404                   AttributeList::AS_Declspec);
405  } else if (Ident->getName() == "property") {
406    // The property declspec is more complex in that it can take one or two
407    // assignment expressions as a parameter, but the lhs of the assignment
408    // must be named get or put.
409    if (Tok.isNot(tok::l_paren)) {
410      Diag(Tok.getLocation(), diag::err_expected_lparen_after)
411        << Ident->getNameStart();
412      return;
413    }
414    BalancedDelimiterTracker T(*this, tok::l_paren);
415    T.expectAndConsume(diag::err_expected_lparen_after,
416                       Ident->getNameStart(), tok::r_paren);
417
418    enum AccessorKind {
419      AK_Invalid = -1,
420      AK_Put = 0, AK_Get = 1 // indices into AccessorNames
421    };
422    IdentifierInfo *AccessorNames[] = { 0, 0 };
423    bool HasInvalidAccessor = false;
424
425    // Parse the accessor specifications.
426    while (true) {
427      // Stop if this doesn't look like an accessor spec.
428      if (!Tok.is(tok::identifier)) {
429        // If the user wrote a completely empty list, use a special diagnostic.
430        if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
431            AccessorNames[AK_Put] == 0 && AccessorNames[AK_Get] == 0) {
432          Diag(Loc, diag::err_ms_property_no_getter_or_putter);
433          break;
434        }
435
436        Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
437        break;
438      }
439
440      AccessorKind Kind;
441      SourceLocation KindLoc = Tok.getLocation();
442      StringRef KindStr = Tok.getIdentifierInfo()->getName();
443      if (KindStr == "get") {
444        Kind = AK_Get;
445      } else if (KindStr == "put") {
446        Kind = AK_Put;
447
448      // Recover from the common mistake of using 'set' instead of 'put'.
449      } else if (KindStr == "set") {
450        Diag(KindLoc, diag::err_ms_property_has_set_accessor)
451          << FixItHint::CreateReplacement(KindLoc, "put");
452        Kind = AK_Put;
453
454      // Handle the mistake of forgetting the accessor kind by skipping
455      // this accessor.
456      } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
457        Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
458        ConsumeToken();
459        HasInvalidAccessor = true;
460        goto next_property_accessor;
461
462      // Otherwise, complain about the unknown accessor kind.
463      } else {
464        Diag(KindLoc, diag::err_ms_property_unknown_accessor);
465        HasInvalidAccessor = true;
466        Kind = AK_Invalid;
467
468        // Try to keep parsing unless it doesn't look like an accessor spec.
469        if (!NextToken().is(tok::equal)) break;
470      }
471
472      // Consume the identifier.
473      ConsumeToken();
474
475      // Consume the '='.
476      if (Tok.is(tok::equal)) {
477        ConsumeToken();
478      } else {
479        Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
480          << KindStr;
481        break;
482      }
483
484      // Expect the method name.
485      if (!Tok.is(tok::identifier)) {
486        Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
487        break;
488      }
489
490      if (Kind == AK_Invalid) {
491        // Just drop invalid accessors.
492      } else if (AccessorNames[Kind] != NULL) {
493        // Complain about the repeated accessor, ignore it, and keep parsing.
494        Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
495      } else {
496        AccessorNames[Kind] = Tok.getIdentifierInfo();
497      }
498      ConsumeToken();
499
500    next_property_accessor:
501      // Keep processing accessors until we run out.
502      if (Tok.is(tok::comma)) {
503        ConsumeAnyToken();
504        continue;
505
506      // If we run into the ')', stop without consuming it.
507      } else if (Tok.is(tok::r_paren)) {
508        break;
509      } else {
510        Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
511        break;
512      }
513    }
514
515    // Only add the property attribute if it was well-formed.
516    if (!HasInvalidAccessor) {
517      Attrs.addNewPropertyAttr(Ident, Loc, 0, SourceLocation(), 0,
518                               SourceLocation(),
519                               AccessorNames[AK_Get], AccessorNames[AK_Put],
520                               AttributeList::AS_Declspec);
521    }
522    T.skipToEnd();
523  } else {
524    // We don't recognize this as a valid declspec, but instead of creating the
525    // attribute and allowing sema to warn about it, we will warn here instead.
526    // This is because some attributes have multiple spellings, but we need to
527    // disallow that for declspecs (such as align vs aligned).  If we made the
528    // attribute, we'd have to split the valid declspec spelling logic into
529    // both locations.
530    Diag(Loc, diag::warn_ms_declspec_unknown) << Ident;
531
532    // If there's an open paren, we should eat the open and close parens under
533    // the assumption that this unknown declspec has parameters.
534    BalancedDelimiterTracker T(*this, tok::l_paren);
535    if (!T.consumeOpen())
536      T.skipToEnd();
537  }
538}
539
540/// [MS] decl-specifier:
541///             __declspec ( extended-decl-modifier-seq )
542///
543/// [MS] extended-decl-modifier-seq:
544///             extended-decl-modifier[opt]
545///             extended-decl-modifier extended-decl-modifier-seq
546void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &Attrs) {
547  assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
548
549  ConsumeToken();
550  BalancedDelimiterTracker T(*this, tok::l_paren);
551  if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
552                         tok::r_paren))
553    return;
554
555  // An empty declspec is perfectly legal and should not warn.  Additionally,
556  // you can specify multiple attributes per declspec.
557  while (Tok.getKind() != tok::r_paren) {
558    // We expect either a well-known identifier or a generic string.  Anything
559    // else is a malformed declspec.
560    bool IsString = Tok.getKind() == tok::string_literal ? true : false;
561    if (!IsString && Tok.getKind() != tok::identifier &&
562        Tok.getKind() != tok::kw_restrict) {
563      Diag(Tok, diag::err_ms_declspec_type);
564      T.skipToEnd();
565      return;
566    }
567
568    IdentifierInfo *AttrName;
569    SourceLocation AttrNameLoc;
570    if (IsString) {
571      SmallString<8> StrBuffer;
572      bool Invalid = false;
573      StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
574      if (Invalid) {
575        T.skipToEnd();
576        return;
577      }
578      AttrName = PP.getIdentifierInfo(Str);
579      AttrNameLoc = ConsumeStringToken();
580    } else {
581      AttrName = Tok.getIdentifierInfo();
582      AttrNameLoc = ConsumeToken();
583    }
584
585    if (IsString || IsSimpleMicrosoftDeclSpec(AttrName))
586      // If we have a generic string, we will allow it because there is no
587      // documented list of allowable string declspecs, but we know they exist
588      // (for instance, SAL declspecs in older versions of MSVC).
589      //
590      // Alternatively, if the identifier is a simple one, then it requires no
591      // arguments and can be turned into an attribute directly.
592      Attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
593                   0, 0, AttributeList::AS_Declspec);
594    else
595      ParseComplexMicrosoftDeclSpec(AttrName, AttrNameLoc, Attrs);
596  }
597  T.consumeClose();
598}
599
600void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
601  // Treat these like attributes
602  while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
603         Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl)   ||
604         Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) ||
605         Tok.is(tok::kw___ptr32) || Tok.is(tok::kw___unaligned) ||
606         Tok.is(tok::kw___sptr) || Tok.is(tok::kw___uptr)) {
607    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
608    SourceLocation AttrNameLoc = ConsumeToken();
609    attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
610                 SourceLocation(), 0, 0, AttributeList::AS_Keyword);
611  }
612}
613
614void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
615  // Treat these like attributes
616  while (Tok.is(tok::kw___pascal)) {
617    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
618    SourceLocation AttrNameLoc = ConsumeToken();
619    attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
620                 SourceLocation(), 0, 0, AttributeList::AS_Keyword);
621  }
622}
623
624void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
625  // Treat these like attributes
626  while (Tok.is(tok::kw___kernel)) {
627    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
628    SourceLocation AttrNameLoc = ConsumeToken();
629    attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
630                 SourceLocation(), 0, 0, AttributeList::AS_Keyword);
631  }
632}
633
634void Parser::ParseOpenCLQualifiers(DeclSpec &DS) {
635  // FIXME: The mapping from attribute spelling to semantics should be
636  //        performed in Sema, not here.
637  SourceLocation Loc = Tok.getLocation();
638  switch(Tok.getKind()) {
639    // OpenCL qualifiers:
640    case tok::kw___private:
641    case tok::kw_private:
642      DS.getAttributes().addNewInteger(
643          Actions.getASTContext(),
644          PP.getIdentifierInfo("address_space"), Loc, 0);
645      break;
646
647    case tok::kw___global:
648      DS.getAttributes().addNewInteger(
649          Actions.getASTContext(),
650          PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global);
651      break;
652
653    case tok::kw___local:
654      DS.getAttributes().addNewInteger(
655          Actions.getASTContext(),
656          PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local);
657      break;
658
659    case tok::kw___constant:
660      DS.getAttributes().addNewInteger(
661          Actions.getASTContext(),
662          PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant);
663      break;
664
665    case tok::kw___read_only:
666      DS.getAttributes().addNewInteger(
667          Actions.getASTContext(),
668          PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only);
669      break;
670
671    case tok::kw___write_only:
672      DS.getAttributes().addNewInteger(
673          Actions.getASTContext(),
674          PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only);
675      break;
676
677    case tok::kw___read_write:
678      DS.getAttributes().addNewInteger(
679          Actions.getASTContext(),
680          PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write);
681      break;
682    default: break;
683  }
684}
685
686/// \brief Parse a version number.
687///
688/// version:
689///   simple-integer
690///   simple-integer ',' simple-integer
691///   simple-integer ',' simple-integer ',' simple-integer
692VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
693  Range = Tok.getLocation();
694
695  if (!Tok.is(tok::numeric_constant)) {
696    Diag(Tok, diag::err_expected_version);
697    SkipUntil(tok::comma, tok::r_paren, true, true, true);
698    return VersionTuple();
699  }
700
701  // Parse the major (and possibly minor and subminor) versions, which
702  // are stored in the numeric constant. We utilize a quirk of the
703  // lexer, which is that it handles something like 1.2.3 as a single
704  // numeric constant, rather than two separate tokens.
705  SmallString<512> Buffer;
706  Buffer.resize(Tok.getLength()+1);
707  const char *ThisTokBegin = &Buffer[0];
708
709  // Get the spelling of the token, which eliminates trigraphs, etc.
710  bool Invalid = false;
711  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
712  if (Invalid)
713    return VersionTuple();
714
715  // Parse the major version.
716  unsigned AfterMajor = 0;
717  unsigned Major = 0;
718  while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
719    Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
720    ++AfterMajor;
721  }
722
723  if (AfterMajor == 0) {
724    Diag(Tok, diag::err_expected_version);
725    SkipUntil(tok::comma, tok::r_paren, true, true, true);
726    return VersionTuple();
727  }
728
729  if (AfterMajor == ActualLength) {
730    ConsumeToken();
731
732    // We only had a single version component.
733    if (Major == 0) {
734      Diag(Tok, diag::err_zero_version);
735      return VersionTuple();
736    }
737
738    return VersionTuple(Major);
739  }
740
741  if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) {
742    Diag(Tok, diag::err_expected_version);
743    SkipUntil(tok::comma, tok::r_paren, true, true, true);
744    return VersionTuple();
745  }
746
747  // Parse the minor version.
748  unsigned AfterMinor = AfterMajor + 1;
749  unsigned Minor = 0;
750  while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
751    Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
752    ++AfterMinor;
753  }
754
755  if (AfterMinor == ActualLength) {
756    ConsumeToken();
757
758    // We had major.minor.
759    if (Major == 0 && Minor == 0) {
760      Diag(Tok, diag::err_zero_version);
761      return VersionTuple();
762    }
763
764    return VersionTuple(Major, Minor);
765  }
766
767  // If what follows is not a '.', we have a problem.
768  if (ThisTokBegin[AfterMinor] != '.') {
769    Diag(Tok, diag::err_expected_version);
770    SkipUntil(tok::comma, tok::r_paren, true, true, true);
771    return VersionTuple();
772  }
773
774  // Parse the subminor version.
775  unsigned AfterSubminor = AfterMinor + 1;
776  unsigned Subminor = 0;
777  while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
778    Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
779    ++AfterSubminor;
780  }
781
782  if (AfterSubminor != ActualLength) {
783    Diag(Tok, diag::err_expected_version);
784    SkipUntil(tok::comma, tok::r_paren, true, true, true);
785    return VersionTuple();
786  }
787  ConsumeToken();
788  return VersionTuple(Major, Minor, Subminor);
789}
790
791/// \brief Parse the contents of the "availability" attribute.
792///
793/// availability-attribute:
794///   'availability' '(' platform ',' version-arg-list, opt-message')'
795///
796/// platform:
797///   identifier
798///
799/// version-arg-list:
800///   version-arg
801///   version-arg ',' version-arg-list
802///
803/// version-arg:
804///   'introduced' '=' version
805///   'deprecated' '=' version
806///   'obsoleted' = version
807///   'unavailable'
808/// opt-message:
809///   'message' '=' <string>
810void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
811                                        SourceLocation AvailabilityLoc,
812                                        ParsedAttributes &attrs,
813                                        SourceLocation *endLoc) {
814  SourceLocation PlatformLoc;
815  IdentifierInfo *Platform = 0;
816
817  enum { Introduced, Deprecated, Obsoleted, Unknown };
818  AvailabilityChange Changes[Unknown];
819  ExprResult MessageExpr;
820
821  // Opening '('.
822  BalancedDelimiterTracker T(*this, tok::l_paren);
823  if (T.consumeOpen()) {
824    Diag(Tok, diag::err_expected_lparen);
825    return;
826  }
827
828  // Parse the platform name,
829  if (Tok.isNot(tok::identifier)) {
830    Diag(Tok, diag::err_availability_expected_platform);
831    SkipUntil(tok::r_paren);
832    return;
833  }
834  Platform = Tok.getIdentifierInfo();
835  PlatformLoc = ConsumeToken();
836
837  // Parse the ',' following the platform name.
838  if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren))
839    return;
840
841  // If we haven't grabbed the pointers for the identifiers
842  // "introduced", "deprecated", and "obsoleted", do so now.
843  if (!Ident_introduced) {
844    Ident_introduced = PP.getIdentifierInfo("introduced");
845    Ident_deprecated = PP.getIdentifierInfo("deprecated");
846    Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
847    Ident_unavailable = PP.getIdentifierInfo("unavailable");
848    Ident_message = PP.getIdentifierInfo("message");
849  }
850
851  // Parse the set of introductions/deprecations/removals.
852  SourceLocation UnavailableLoc;
853  do {
854    if (Tok.isNot(tok::identifier)) {
855      Diag(Tok, diag::err_availability_expected_change);
856      SkipUntil(tok::r_paren);
857      return;
858    }
859    IdentifierInfo *Keyword = Tok.getIdentifierInfo();
860    SourceLocation KeywordLoc = ConsumeToken();
861
862    if (Keyword == Ident_unavailable) {
863      if (UnavailableLoc.isValid()) {
864        Diag(KeywordLoc, diag::err_availability_redundant)
865          << Keyword << SourceRange(UnavailableLoc);
866      }
867      UnavailableLoc = KeywordLoc;
868
869      if (Tok.isNot(tok::comma))
870        break;
871
872      ConsumeToken();
873      continue;
874    }
875
876    if (Tok.isNot(tok::equal)) {
877      Diag(Tok, diag::err_expected_equal_after)
878        << Keyword;
879      SkipUntil(tok::r_paren);
880      return;
881    }
882    ConsumeToken();
883    if (Keyword == Ident_message) {
884      if (!isTokenStringLiteral()) {
885        Diag(Tok, diag::err_expected_string_literal)
886          << /*Source='availability attribute'*/2;
887        SkipUntil(tok::r_paren);
888        return;
889      }
890      MessageExpr = ParseStringLiteralExpression();
891      break;
892    }
893
894    SourceRange VersionRange;
895    VersionTuple Version = ParseVersionTuple(VersionRange);
896
897    if (Version.empty()) {
898      SkipUntil(tok::r_paren);
899      return;
900    }
901
902    unsigned Index;
903    if (Keyword == Ident_introduced)
904      Index = Introduced;
905    else if (Keyword == Ident_deprecated)
906      Index = Deprecated;
907    else if (Keyword == Ident_obsoleted)
908      Index = Obsoleted;
909    else
910      Index = Unknown;
911
912    if (Index < Unknown) {
913      if (!Changes[Index].KeywordLoc.isInvalid()) {
914        Diag(KeywordLoc, diag::err_availability_redundant)
915          << Keyword
916          << SourceRange(Changes[Index].KeywordLoc,
917                         Changes[Index].VersionRange.getEnd());
918      }
919
920      Changes[Index].KeywordLoc = KeywordLoc;
921      Changes[Index].Version = Version;
922      Changes[Index].VersionRange = VersionRange;
923    } else {
924      Diag(KeywordLoc, diag::err_availability_unknown_change)
925        << Keyword << VersionRange;
926    }
927
928    if (Tok.isNot(tok::comma))
929      break;
930
931    ConsumeToken();
932  } while (true);
933
934  // Closing ')'.
935  if (T.consumeClose())
936    return;
937
938  if (endLoc)
939    *endLoc = T.getCloseLocation();
940
941  // The 'unavailable' availability cannot be combined with any other
942  // availability changes. Make sure that hasn't happened.
943  if (UnavailableLoc.isValid()) {
944    bool Complained = false;
945    for (unsigned Index = Introduced; Index != Unknown; ++Index) {
946      if (Changes[Index].KeywordLoc.isValid()) {
947        if (!Complained) {
948          Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
949            << SourceRange(Changes[Index].KeywordLoc,
950                           Changes[Index].VersionRange.getEnd());
951          Complained = true;
952        }
953
954        // Clear out the availability.
955        Changes[Index] = AvailabilityChange();
956      }
957    }
958  }
959
960  // Record this attribute
961  attrs.addNew(&Availability,
962               SourceRange(AvailabilityLoc, T.getCloseLocation()),
963               0, AvailabilityLoc,
964               Platform, PlatformLoc,
965               Changes[Introduced],
966               Changes[Deprecated],
967               Changes[Obsoleted],
968               UnavailableLoc, MessageExpr.take(),
969               AttributeList::AS_GNU);
970}
971
972
973// Late Parsed Attributes:
974// See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
975
976void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
977
978void Parser::LateParsedClass::ParseLexedAttributes() {
979  Self->ParseLexedAttributes(*Class);
980}
981
982void Parser::LateParsedAttribute::ParseLexedAttributes() {
983  Self->ParseLexedAttribute(*this, true, false);
984}
985
986/// Wrapper class which calls ParseLexedAttribute, after setting up the
987/// scope appropriately.
988void Parser::ParseLexedAttributes(ParsingClass &Class) {
989  // Deal with templates
990  // FIXME: Test cases to make sure this does the right thing for templates.
991  bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
992  ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
993                                HasTemplateScope);
994  if (HasTemplateScope)
995    Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
996
997  // Set or update the scope flags.
998  bool AlreadyHasClassScope = Class.TopLevelClass;
999  unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
1000  ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1001  ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1002
1003  // Enter the scope of nested classes
1004  if (!AlreadyHasClassScope)
1005    Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1006                                                Class.TagOrTemplate);
1007  if (!Class.LateParsedDeclarations.empty()) {
1008    for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1009      Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1010    }
1011  }
1012
1013  if (!AlreadyHasClassScope)
1014    Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1015                                                 Class.TagOrTemplate);
1016}
1017
1018
1019/// \brief Parse all attributes in LAs, and attach them to Decl D.
1020void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1021                                     bool EnterScope, bool OnDefinition) {
1022  assert(LAs.parseSoon() &&
1023         "Attribute list should be marked for immediate parsing.");
1024  for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1025    if (D)
1026      LAs[i]->addDecl(D);
1027    ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1028    delete LAs[i];
1029  }
1030  LAs.clear();
1031}
1032
1033
1034/// \brief Finish parsing an attribute for which parsing was delayed.
1035/// This will be called at the end of parsing a class declaration
1036/// for each LateParsedAttribute. We consume the saved tokens and
1037/// create an attribute with the arguments filled in. We add this
1038/// to the Attribute list for the decl.
1039void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1040                                 bool EnterScope, bool OnDefinition) {
1041  // Save the current token position.
1042  SourceLocation OrigLoc = Tok.getLocation();
1043
1044  // Append the current token at the end of the new token stream so that it
1045  // doesn't get lost.
1046  LA.Toks.push_back(Tok);
1047  PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false);
1048  // Consume the previously pushed token.
1049  ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1050
1051  if (OnDefinition && !IsThreadSafetyAttribute(LA.AttrName.getName())) {
1052    // FIXME: Do not warn on C++11 attributes, once we start supporting
1053    // them here.
1054    Diag(Tok, diag::warn_attribute_on_function_definition)
1055      << LA.AttrName.getName();
1056  }
1057
1058  ParsedAttributes Attrs(AttrFactory);
1059  SourceLocation endLoc;
1060
1061  if (LA.Decls.size() > 0) {
1062    Decl *D = LA.Decls[0];
1063    NamedDecl *ND  = dyn_cast<NamedDecl>(D);
1064    RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1065
1066    // Allow 'this' within late-parsed attributes.
1067    Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0,
1068                                     ND && ND->isCXXInstanceMember());
1069
1070    if (LA.Decls.size() == 1) {
1071      // If the Decl is templatized, add template parameters to scope.
1072      bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1073      ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1074      if (HasTemplateScope)
1075        Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1076
1077      // If the Decl is on a function, add function parameters to the scope.
1078      bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1079      ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunScope);
1080      if (HasFunScope)
1081        Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1082
1083      ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1084                            0, SourceLocation(), AttributeList::AS_GNU);
1085
1086      if (HasFunScope) {
1087        Actions.ActOnExitFunctionContext();
1088        FnScope.Exit();  // Pop scope, and remove Decls from IdResolver
1089      }
1090      if (HasTemplateScope) {
1091        TempScope.Exit();
1092      }
1093    } else {
1094      // If there are multiple decls, then the decl cannot be within the
1095      // function scope.
1096      ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1097                            0, SourceLocation(), AttributeList::AS_GNU);
1098    }
1099  } else {
1100    Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1101  }
1102
1103  for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i) {
1104    Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1105  }
1106
1107  if (Tok.getLocation() != OrigLoc) {
1108    // Due to a parsing error, we either went over the cached tokens or
1109    // there are still cached tokens left, so we skip the leftover tokens.
1110    // Since this is an uncommon situation that should be avoided, use the
1111    // expensive isBeforeInTranslationUnit call.
1112    if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
1113                                                        OrigLoc))
1114    while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
1115      ConsumeAnyToken();
1116  }
1117}
1118
1119/// \brief Wrapper around a case statement checking if AttrName is
1120/// one of the thread safety attributes
1121bool Parser::IsThreadSafetyAttribute(StringRef AttrName) {
1122  return llvm::StringSwitch<bool>(AttrName)
1123      .Case("guarded_by", true)
1124      .Case("guarded_var", true)
1125      .Case("pt_guarded_by", true)
1126      .Case("pt_guarded_var", true)
1127      .Case("lockable", true)
1128      .Case("scoped_lockable", true)
1129      .Case("no_thread_safety_analysis", true)
1130      .Case("acquired_after", true)
1131      .Case("acquired_before", true)
1132      .Case("exclusive_lock_function", true)
1133      .Case("shared_lock_function", true)
1134      .Case("exclusive_trylock_function", true)
1135      .Case("shared_trylock_function", true)
1136      .Case("unlock_function", true)
1137      .Case("lock_returned", true)
1138      .Case("locks_excluded", true)
1139      .Case("exclusive_locks_required", true)
1140      .Case("shared_locks_required", true)
1141      .Default(false);
1142}
1143
1144/// \brief Parse the contents of thread safety attributes. These
1145/// should always be parsed as an expression list.
1146///
1147/// We need to special case the parsing due to the fact that if the first token
1148/// of the first argument is an identifier, the main parse loop will store
1149/// that token as a "parameter" and the rest of
1150/// the arguments will be added to a list of "arguments". However,
1151/// subsequent tokens in the first argument are lost. We instead parse each
1152/// argument as an expression and add all arguments to the list of "arguments".
1153/// In future, we will take advantage of this special case to also
1154/// deal with some argument scoping issues here (for example, referring to a
1155/// function parameter in the attribute on that function).
1156void Parser::ParseThreadSafetyAttribute(IdentifierInfo &AttrName,
1157                                        SourceLocation AttrNameLoc,
1158                                        ParsedAttributes &Attrs,
1159                                        SourceLocation *EndLoc) {
1160  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1161
1162  BalancedDelimiterTracker T(*this, tok::l_paren);
1163  T.consumeOpen();
1164
1165  ExprVector ArgExprs;
1166  bool ArgExprsOk = true;
1167
1168  // now parse the list of expressions
1169  while (Tok.isNot(tok::r_paren)) {
1170    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1171    ExprResult ArgExpr(ParseAssignmentExpression());
1172    if (ArgExpr.isInvalid()) {
1173      ArgExprsOk = false;
1174      T.consumeClose();
1175      break;
1176    } else {
1177      ArgExprs.push_back(ArgExpr.release());
1178    }
1179    if (Tok.isNot(tok::comma))
1180      break;
1181    ConsumeToken(); // Eat the comma, move to the next argument
1182  }
1183  // Match the ')'.
1184  if (ArgExprsOk && !T.consumeClose()) {
1185    Attrs.addNew(&AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
1186                 ArgExprs.data(), ArgExprs.size(), AttributeList::AS_GNU);
1187  }
1188  if (EndLoc)
1189    *EndLoc = T.getCloseLocation();
1190}
1191
1192void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1193                                              SourceLocation AttrNameLoc,
1194                                              ParsedAttributes &Attrs,
1195                                              SourceLocation *EndLoc) {
1196  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1197
1198  BalancedDelimiterTracker T(*this, tok::l_paren);
1199  T.consumeOpen();
1200
1201  if (Tok.isNot(tok::identifier)) {
1202    Diag(Tok, diag::err_expected_ident);
1203    T.skipToEnd();
1204    return;
1205  }
1206  IdentifierInfo *ArgumentKind = Tok.getIdentifierInfo();
1207  SourceLocation ArgumentKindLoc = ConsumeToken();
1208
1209  if (Tok.isNot(tok::comma)) {
1210    Diag(Tok, diag::err_expected_comma);
1211    T.skipToEnd();
1212    return;
1213  }
1214  ConsumeToken();
1215
1216  SourceRange MatchingCTypeRange;
1217  TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1218  if (MatchingCType.isInvalid()) {
1219    T.skipToEnd();
1220    return;
1221  }
1222
1223  bool LayoutCompatible = false;
1224  bool MustBeNull = false;
1225  while (Tok.is(tok::comma)) {
1226    ConsumeToken();
1227    if (Tok.isNot(tok::identifier)) {
1228      Diag(Tok, diag::err_expected_ident);
1229      T.skipToEnd();
1230      return;
1231    }
1232    IdentifierInfo *Flag = Tok.getIdentifierInfo();
1233    if (Flag->isStr("layout_compatible"))
1234      LayoutCompatible = true;
1235    else if (Flag->isStr("must_be_null"))
1236      MustBeNull = true;
1237    else {
1238      Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1239      T.skipToEnd();
1240      return;
1241    }
1242    ConsumeToken(); // consume flag
1243  }
1244
1245  if (!T.consumeClose()) {
1246    Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, 0, AttrNameLoc,
1247                                   ArgumentKind, ArgumentKindLoc,
1248                                   MatchingCType.release(), LayoutCompatible,
1249                                   MustBeNull, AttributeList::AS_GNU);
1250  }
1251
1252  if (EndLoc)
1253    *EndLoc = T.getCloseLocation();
1254}
1255
1256/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1257/// of a C++11 attribute-specifier in a location where an attribute is not
1258/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1259/// situation.
1260///
1261/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1262/// this doesn't appear to actually be an attribute-specifier, and the caller
1263/// should try to parse it.
1264bool Parser::DiagnoseProhibitedCXX11Attribute() {
1265  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1266
1267  switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1268  case CAK_NotAttributeSpecifier:
1269    // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1270    return false;
1271
1272  case CAK_InvalidAttributeSpecifier:
1273    Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1274    return false;
1275
1276  case CAK_AttributeSpecifier:
1277    // Parse and discard the attributes.
1278    SourceLocation BeginLoc = ConsumeBracket();
1279    ConsumeBracket();
1280    SkipUntil(tok::r_square, /*StopAtSemi*/ false);
1281    assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1282    SourceLocation EndLoc = ConsumeBracket();
1283    Diag(BeginLoc, diag::err_attributes_not_allowed)
1284      << SourceRange(BeginLoc, EndLoc);
1285    return true;
1286  }
1287  llvm_unreachable("All cases handled above.");
1288}
1289
1290/// \brief We have found the opening square brackets of a C++11
1291/// attribute-specifier in a location where an attribute is not permitted, but
1292/// we know where the attributes ought to be written. Parse them anyway, and
1293/// provide a fixit moving them to the right place.
1294void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1295                                             SourceLocation CorrectLocation) {
1296  assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1297         Tok.is(tok::kw_alignas));
1298
1299  // Consume the attributes.
1300  SourceLocation Loc = Tok.getLocation();
1301  ParseCXX11Attributes(Attrs);
1302  CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1303
1304  Diag(Loc, diag::err_attributes_not_allowed)
1305    << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1306    << FixItHint::CreateRemoval(AttrRange);
1307}
1308
1309void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
1310  Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
1311    << attrs.Range;
1312}
1313
1314void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs) {
1315  AttributeList *AttrList = attrs.getList();
1316  while (AttrList) {
1317    if (AttrList->isCXX11Attribute()) {
1318      Diag(AttrList->getLoc(), diag::err_attribute_not_type_attr)
1319        << AttrList->getName();
1320      AttrList->setInvalid();
1321    }
1322    AttrList = AttrList->getNext();
1323  }
1324}
1325
1326/// ParseDeclaration - Parse a full 'declaration', which consists of
1327/// declaration-specifiers, some number of declarators, and a semicolon.
1328/// 'Context' should be a Declarator::TheContext value.  This returns the
1329/// location of the semicolon in DeclEnd.
1330///
1331///       declaration: [C99 6.7]
1332///         block-declaration ->
1333///           simple-declaration
1334///           others                   [FIXME]
1335/// [C++]   template-declaration
1336/// [C++]   namespace-definition
1337/// [C++]   using-directive
1338/// [C++]   using-declaration
1339/// [C++11/C11] static_assert-declaration
1340///         others... [FIXME]
1341///
1342Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts,
1343                                                unsigned Context,
1344                                                SourceLocation &DeclEnd,
1345                                          ParsedAttributesWithRange &attrs) {
1346  ParenBraceBracketBalancer BalancerRAIIObj(*this);
1347  // Must temporarily exit the objective-c container scope for
1348  // parsing c none objective-c decls.
1349  ObjCDeclContextSwitch ObjCDC(*this);
1350
1351  Decl *SingleDecl = 0;
1352  Decl *OwnedType = 0;
1353  switch (Tok.getKind()) {
1354  case tok::kw_template:
1355  case tok::kw_export:
1356    ProhibitAttributes(attrs);
1357    SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
1358    break;
1359  case tok::kw_inline:
1360    // Could be the start of an inline namespace. Allowed as an ext in C++03.
1361    if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1362      ProhibitAttributes(attrs);
1363      SourceLocation InlineLoc = ConsumeToken();
1364      SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc);
1365      break;
1366    }
1367    return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs,
1368                                  true);
1369  case tok::kw_namespace:
1370    ProhibitAttributes(attrs);
1371    SingleDecl = ParseNamespace(Context, DeclEnd);
1372    break;
1373  case tok::kw_using:
1374    SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1375                                                  DeclEnd, attrs, &OwnedType);
1376    break;
1377  case tok::kw_static_assert:
1378  case tok::kw__Static_assert:
1379    ProhibitAttributes(attrs);
1380    SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1381    break;
1382  default:
1383    return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true);
1384  }
1385
1386  // This routine returns a DeclGroup, if the thing we parsed only contains a
1387  // single decl, convert it now. Alias declarations can also declare a type;
1388  // include that too if it is present.
1389  return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType);
1390}
1391
1392///       simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1393///         declaration-specifiers init-declarator-list[opt] ';'
1394/// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1395///             init-declarator-list ';'
1396///[C90/C++]init-declarator-list ';'                             [TODO]
1397/// [OMP]   threadprivate-directive                              [TODO]
1398///
1399///       for-range-declaration: [C++11 6.5p1: stmt.ranged]
1400///         attribute-specifier-seq[opt] type-specifier-seq declarator
1401///
1402/// If RequireSemi is false, this does not check for a ';' at the end of the
1403/// declaration.  If it is true, it checks for and eats it.
1404///
1405/// If FRI is non-null, we might be parsing a for-range-declaration instead
1406/// of a simple-declaration. If we find that we are, we also parse the
1407/// for-range-initializer, and place it here.
1408Parser::DeclGroupPtrTy
1409Parser::ParseSimpleDeclaration(StmtVector &Stmts, unsigned Context,
1410                               SourceLocation &DeclEnd,
1411                               ParsedAttributesWithRange &Attrs,
1412                               bool RequireSemi, ForRangeInit *FRI) {
1413  // Parse the common declaration-specifiers piece.
1414  ParsingDeclSpec DS(*this);
1415
1416  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
1417                             getDeclSpecContextFromDeclaratorContext(Context));
1418
1419  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1420  // declaration-specifiers init-declarator-list[opt] ';'
1421  if (Tok.is(tok::semi)) {
1422    ProhibitAttributes(Attrs);
1423    DeclEnd = Tok.getLocation();
1424    if (RequireSemi) ConsumeToken();
1425    Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1426                                                       DS);
1427    DS.complete(TheDecl);
1428    return Actions.ConvertDeclToDeclGroup(TheDecl);
1429  }
1430
1431  DS.takeAttributesFrom(Attrs);
1432  return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI);
1433}
1434
1435/// Returns true if this might be the start of a declarator, or a common typo
1436/// for a declarator.
1437bool Parser::MightBeDeclarator(unsigned Context) {
1438  switch (Tok.getKind()) {
1439  case tok::annot_cxxscope:
1440  case tok::annot_template_id:
1441  case tok::caret:
1442  case tok::code_completion:
1443  case tok::coloncolon:
1444  case tok::ellipsis:
1445  case tok::kw___attribute:
1446  case tok::kw_operator:
1447  case tok::l_paren:
1448  case tok::star:
1449    return true;
1450
1451  case tok::amp:
1452  case tok::ampamp:
1453    return getLangOpts().CPlusPlus;
1454
1455  case tok::l_square: // Might be an attribute on an unnamed bit-field.
1456    return Context == Declarator::MemberContext && getLangOpts().CPlusPlus11 &&
1457           NextToken().is(tok::l_square);
1458
1459  case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1460    return Context == Declarator::MemberContext || getLangOpts().CPlusPlus;
1461
1462  case tok::identifier:
1463    switch (NextToken().getKind()) {
1464    case tok::code_completion:
1465    case tok::coloncolon:
1466    case tok::comma:
1467    case tok::equal:
1468    case tok::equalequal: // Might be a typo for '='.
1469    case tok::kw_alignas:
1470    case tok::kw_asm:
1471    case tok::kw___attribute:
1472    case tok::l_brace:
1473    case tok::l_paren:
1474    case tok::l_square:
1475    case tok::less:
1476    case tok::r_brace:
1477    case tok::r_paren:
1478    case tok::r_square:
1479    case tok::semi:
1480      return true;
1481
1482    case tok::colon:
1483      // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1484      // and in block scope it's probably a label. Inside a class definition,
1485      // this is a bit-field.
1486      return Context == Declarator::MemberContext ||
1487             (getLangOpts().CPlusPlus && Context == Declarator::FileContext);
1488
1489    case tok::identifier: // Possible virt-specifier.
1490      return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1491
1492    default:
1493      return false;
1494    }
1495
1496  default:
1497    return false;
1498  }
1499}
1500
1501/// Skip until we reach something which seems like a sensible place to pick
1502/// up parsing after a malformed declaration. This will sometimes stop sooner
1503/// than SkipUntil(tok::r_brace) would, but will never stop later.
1504void Parser::SkipMalformedDecl() {
1505  while (true) {
1506    switch (Tok.getKind()) {
1507    case tok::l_brace:
1508      // Skip until matching }, then stop. We've probably skipped over
1509      // a malformed class or function definition or similar.
1510      ConsumeBrace();
1511      SkipUntil(tok::r_brace, /*StopAtSemi*/false);
1512      if (Tok.is(tok::comma) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try)) {
1513        // This declaration isn't over yet. Keep skipping.
1514        continue;
1515      }
1516      if (Tok.is(tok::semi))
1517        ConsumeToken();
1518      return;
1519
1520    case tok::l_square:
1521      ConsumeBracket();
1522      SkipUntil(tok::r_square, /*StopAtSemi*/false);
1523      continue;
1524
1525    case tok::l_paren:
1526      ConsumeParen();
1527      SkipUntil(tok::r_paren, /*StopAtSemi*/false);
1528      continue;
1529
1530    case tok::r_brace:
1531      return;
1532
1533    case tok::semi:
1534      ConsumeToken();
1535      return;
1536
1537    case tok::kw_inline:
1538      // 'inline namespace' at the start of a line is almost certainly
1539      // a good place to pick back up parsing, except in an Objective-C
1540      // @interface context.
1541      if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1542          (!ParsingInObjCContainer || CurParsedObjCImpl))
1543        return;
1544      break;
1545
1546    case tok::kw_namespace:
1547      // 'namespace' at the start of a line is almost certainly a good
1548      // place to pick back up parsing, except in an Objective-C
1549      // @interface context.
1550      if (Tok.isAtStartOfLine() &&
1551          (!ParsingInObjCContainer || CurParsedObjCImpl))
1552        return;
1553      break;
1554
1555    case tok::at:
1556      // @end is very much like } in Objective-C contexts.
1557      if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1558          ParsingInObjCContainer)
1559        return;
1560      break;
1561
1562    case tok::minus:
1563    case tok::plus:
1564      // - and + probably start new method declarations in Objective-C contexts.
1565      if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1566        return;
1567      break;
1568
1569    case tok::eof:
1570      return;
1571
1572    default:
1573      break;
1574    }
1575
1576    ConsumeAnyToken();
1577  }
1578}
1579
1580/// ParseDeclGroup - Having concluded that this is either a function
1581/// definition or a group of object declarations, actually parse the
1582/// result.
1583Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1584                                              unsigned Context,
1585                                              bool AllowFunctionDefinitions,
1586                                              SourceLocation *DeclEnd,
1587                                              ForRangeInit *FRI) {
1588  // Parse the first declarator.
1589  ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
1590  ParseDeclarator(D);
1591
1592  // Bail out if the first declarator didn't seem well-formed.
1593  if (!D.hasName() && !D.mayOmitIdentifier()) {
1594    SkipMalformedDecl();
1595    return DeclGroupPtrTy();
1596  }
1597
1598  // Save late-parsed attributes for now; they need to be parsed in the
1599  // appropriate function scope after the function Decl has been constructed.
1600  // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1601  LateParsedAttrList LateParsedAttrs(true);
1602  if (D.isFunctionDeclarator())
1603    MaybeParseGNUAttributes(D, &LateParsedAttrs);
1604
1605  // Check to see if we have a function *definition* which must have a body.
1606  if (D.isFunctionDeclarator() &&
1607      // Look at the next token to make sure that this isn't a function
1608      // declaration.  We have to check this because __attribute__ might be the
1609      // start of a function definition in GCC-extended K&R C.
1610      !isDeclarationAfterDeclarator()) {
1611
1612    if (AllowFunctionDefinitions) {
1613      if (isStartOfFunctionDefinition(D)) {
1614        if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1615          Diag(Tok, diag::err_function_declared_typedef);
1616
1617          // Recover by treating the 'typedef' as spurious.
1618          DS.ClearStorageClassSpecs();
1619        }
1620
1621        Decl *TheDecl =
1622          ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1623        return Actions.ConvertDeclToDeclGroup(TheDecl);
1624      }
1625
1626      if (isDeclarationSpecifier()) {
1627        // If there is an invalid declaration specifier right after the function
1628        // prototype, then we must be in a missing semicolon case where this isn't
1629        // actually a body.  Just fall through into the code that handles it as a
1630        // prototype, and let the top-level code handle the erroneous declspec
1631        // where it would otherwise expect a comma or semicolon.
1632      } else {
1633        Diag(Tok, diag::err_expected_fn_body);
1634        SkipUntil(tok::semi);
1635        return DeclGroupPtrTy();
1636      }
1637    } else {
1638      if (Tok.is(tok::l_brace)) {
1639        Diag(Tok, diag::err_function_definition_not_allowed);
1640        SkipUntil(tok::r_brace, true, true);
1641      }
1642    }
1643  }
1644
1645  if (ParseAsmAttributesAfterDeclarator(D))
1646    return DeclGroupPtrTy();
1647
1648  // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1649  // must parse and analyze the for-range-initializer before the declaration is
1650  // analyzed.
1651  //
1652  // Handle the Objective-C for-in loop variable similarly, although we
1653  // don't need to parse the container in advance.
1654  if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
1655    bool IsForRangeLoop = false;
1656    if (Tok.is(tok::colon)) {
1657      IsForRangeLoop = true;
1658      FRI->ColonLoc = ConsumeToken();
1659      if (Tok.is(tok::l_brace))
1660        FRI->RangeExpr = ParseBraceInitializer();
1661      else
1662        FRI->RangeExpr = ParseExpression();
1663    }
1664
1665    Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1666    if (IsForRangeLoop)
1667      Actions.ActOnCXXForRangeDecl(ThisDecl);
1668    Actions.FinalizeDeclaration(ThisDecl);
1669    D.complete(ThisDecl);
1670    return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
1671  }
1672
1673  SmallVector<Decl *, 8> DeclsInGroup;
1674  Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(D);
1675  if (LateParsedAttrs.size() > 0)
1676    ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
1677  D.complete(FirstDecl);
1678  if (FirstDecl)
1679    DeclsInGroup.push_back(FirstDecl);
1680
1681  bool ExpectSemi = Context != Declarator::ForContext;
1682
1683  // If we don't have a comma, it is either the end of the list (a ';') or an
1684  // error, bail out.
1685  while (Tok.is(tok::comma)) {
1686    SourceLocation CommaLoc = ConsumeToken();
1687
1688    if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
1689      // This comma was followed by a line-break and something which can't be
1690      // the start of a declarator. The comma was probably a typo for a
1691      // semicolon.
1692      Diag(CommaLoc, diag::err_expected_semi_declaration)
1693        << FixItHint::CreateReplacement(CommaLoc, ";");
1694      ExpectSemi = false;
1695      break;
1696    }
1697
1698    // Parse the next declarator.
1699    D.clear();
1700    D.setCommaLoc(CommaLoc);
1701
1702    // Accept attributes in an init-declarator.  In the first declarator in a
1703    // declaration, these would be part of the declspec.  In subsequent
1704    // declarators, they become part of the declarator itself, so that they
1705    // don't apply to declarators after *this* one.  Examples:
1706    //    short __attribute__((common)) var;    -> declspec
1707    //    short var __attribute__((common));    -> declarator
1708    //    short x, __attribute__((common)) var;    -> declarator
1709    MaybeParseGNUAttributes(D);
1710
1711    ParseDeclarator(D);
1712    if (!D.isInvalidType()) {
1713      Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
1714      D.complete(ThisDecl);
1715      if (ThisDecl)
1716        DeclsInGroup.push_back(ThisDecl);
1717    }
1718  }
1719
1720  if (DeclEnd)
1721    *DeclEnd = Tok.getLocation();
1722
1723  if (ExpectSemi &&
1724      ExpectAndConsumeSemi(Context == Declarator::FileContext
1725                           ? diag::err_invalid_token_after_toplevel_declarator
1726                           : diag::err_expected_semi_declaration)) {
1727    // Okay, there was no semicolon and one was expected.  If we see a
1728    // declaration specifier, just assume it was missing and continue parsing.
1729    // Otherwise things are very confused and we skip to recover.
1730    if (!isDeclarationSpecifier()) {
1731      SkipUntil(tok::r_brace, true, true);
1732      if (Tok.is(tok::semi))
1733        ConsumeToken();
1734    }
1735  }
1736
1737  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
1738}
1739
1740/// Parse an optional simple-asm-expr and attributes, and attach them to a
1741/// declarator. Returns true on an error.
1742bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
1743  // If a simple-asm-expr is present, parse it.
1744  if (Tok.is(tok::kw_asm)) {
1745    SourceLocation Loc;
1746    ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1747    if (AsmLabel.isInvalid()) {
1748      SkipUntil(tok::semi, true, true);
1749      return true;
1750    }
1751
1752    D.setAsmLabel(AsmLabel.release());
1753    D.SetRangeEnd(Loc);
1754  }
1755
1756  MaybeParseGNUAttributes(D);
1757  return false;
1758}
1759
1760/// \brief Parse 'declaration' after parsing 'declaration-specifiers
1761/// declarator'. This method parses the remainder of the declaration
1762/// (including any attributes or initializer, among other things) and
1763/// finalizes the declaration.
1764///
1765///       init-declarator: [C99 6.7]
1766///         declarator
1767///         declarator '=' initializer
1768/// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
1769/// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
1770/// [C++]   declarator initializer[opt]
1771///
1772/// [C++] initializer:
1773/// [C++]   '=' initializer-clause
1774/// [C++]   '(' expression-list ')'
1775/// [C++0x] '=' 'default'                                                [TODO]
1776/// [C++0x] '=' 'delete'
1777/// [C++0x] braced-init-list
1778///
1779/// According to the standard grammar, =default and =delete are function
1780/// definitions, but that definitely doesn't fit with the parser here.
1781///
1782Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D,
1783                                     const ParsedTemplateInfo &TemplateInfo) {
1784  if (ParseAsmAttributesAfterDeclarator(D))
1785    return 0;
1786
1787  return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
1788}
1789
1790Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
1791                                     const ParsedTemplateInfo &TemplateInfo) {
1792  // Inform the current actions module that we just parsed this declarator.
1793  Decl *ThisDecl = 0;
1794  switch (TemplateInfo.Kind) {
1795  case ParsedTemplateInfo::NonTemplate:
1796    ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1797    break;
1798
1799  case ParsedTemplateInfo::Template:
1800  case ParsedTemplateInfo::ExplicitSpecialization: {
1801    ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
1802                                               *TemplateInfo.TemplateParams,
1803                                               D);
1804    if (Tok.is(tok::semi) &&
1805	Actions.HandleVariableRedeclaration(ThisDecl, D.getCXXScopeSpec())) {
1806      SkipUntil(tok::semi, true, true);
1807      return 0;
1808    }
1809    if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
1810      // Re-direct this decl to refer to the templated decl so that we can
1811      // initialize it.
1812      ThisDecl = VT->getTemplatedDecl();
1813    break;
1814  }
1815  case ParsedTemplateInfo::ExplicitInstantiation: {
1816    if (Tok.is(tok::semi)) {
1817      DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
1818          getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
1819      if (ThisRes.isInvalid()) {
1820        SkipUntil(tok::semi, true, true);
1821        return 0;
1822      }
1823      ThisDecl = ThisRes.get();
1824    } else {
1825      // FIXME: This check should be for a variable template instantiation only.
1826
1827      // Check that this is a valid instantiation
1828      if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
1829        // If the declarator-id is not a template-id, issue a diagnostic and
1830        // recover by ignoring the 'template' keyword.
1831        Diag(Tok, diag::err_template_defn_explicit_instantiation)
1832            << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1833        ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1834      } else {
1835        SourceLocation LAngleLoc =
1836            PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1837        Diag(D.getIdentifierLoc(),
1838             diag::err_explicit_instantiation_with_definition)
1839            << SourceRange(TemplateInfo.TemplateLoc)
1840            << FixItHint::CreateInsertion(LAngleLoc, "<>");
1841
1842        // Recover as if it were an explicit specialization.
1843        TemplateParameterLists FakedParamLists;
1844        FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1845            0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, 0, 0,
1846            LAngleLoc));
1847
1848        ThisDecl =
1849            Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
1850      }
1851    }
1852    break;
1853    }
1854  }
1855
1856  bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
1857
1858  // Parse declarator '=' initializer.
1859  // If a '==' or '+=' is found, suggest a fixit to '='.
1860  if (isTokenEqualOrEqualTypo()) {
1861    ConsumeToken();
1862
1863    if (Tok.is(tok::kw_delete)) {
1864      if (D.isFunctionDeclarator())
1865        Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1866          << 1 /* delete */;
1867      else
1868        Diag(ConsumeToken(), diag::err_deleted_non_function);
1869    } else if (Tok.is(tok::kw_default)) {
1870      if (D.isFunctionDeclarator())
1871        Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1872          << 0 /* default */;
1873      else
1874        Diag(ConsumeToken(), diag::err_default_special_members);
1875    } else {
1876      if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1877        EnterScope(0);
1878        Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1879      }
1880
1881      if (Tok.is(tok::code_completion)) {
1882        Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
1883        Actions.FinalizeDeclaration(ThisDecl);
1884        cutOffParsing();
1885        return 0;
1886      }
1887
1888      ExprResult Init(ParseInitializer());
1889
1890      if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1891        Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1892        ExitScope();
1893      }
1894
1895      if (Init.isInvalid()) {
1896        SkipUntil(tok::comma, true, true);
1897        Actions.ActOnInitializerError(ThisDecl);
1898      } else
1899        Actions.AddInitializerToDecl(ThisDecl, Init.take(),
1900                                     /*DirectInit=*/false, TypeContainsAuto);
1901    }
1902  } else if (Tok.is(tok::l_paren)) {
1903    // Parse C++ direct initializer: '(' expression-list ')'
1904    BalancedDelimiterTracker T(*this, tok::l_paren);
1905    T.consumeOpen();
1906
1907    ExprVector Exprs;
1908    CommaLocsTy CommaLocs;
1909
1910    if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1911      EnterScope(0);
1912      Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1913    }
1914
1915    if (ParseExpressionList(Exprs, CommaLocs)) {
1916      Actions.ActOnInitializerError(ThisDecl);
1917      SkipUntil(tok::r_paren);
1918
1919      if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1920        Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1921        ExitScope();
1922      }
1923    } else {
1924      // Match the ')'.
1925      T.consumeClose();
1926
1927      assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
1928             "Unexpected number of commas!");
1929
1930      if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1931        Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1932        ExitScope();
1933      }
1934
1935      ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
1936                                                          T.getCloseLocation(),
1937                                                          Exprs);
1938      Actions.AddInitializerToDecl(ThisDecl, Initializer.take(),
1939                                   /*DirectInit=*/true, TypeContainsAuto);
1940    }
1941  } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
1942             (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
1943    // Parse C++0x braced-init-list.
1944    Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1945
1946    if (D.getCXXScopeSpec().isSet()) {
1947      EnterScope(0);
1948      Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1949    }
1950
1951    ExprResult Init(ParseBraceInitializer());
1952
1953    if (D.getCXXScopeSpec().isSet()) {
1954      Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1955      ExitScope();
1956    }
1957
1958    if (Init.isInvalid()) {
1959      Actions.ActOnInitializerError(ThisDecl);
1960    } else
1961      Actions.AddInitializerToDecl(ThisDecl, Init.take(),
1962                                   /*DirectInit=*/true, TypeContainsAuto);
1963
1964  } else {
1965    Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
1966  }
1967
1968  Actions.FinalizeDeclaration(ThisDecl);
1969
1970  return ThisDecl;
1971}
1972
1973/// ParseSpecifierQualifierList
1974///        specifier-qualifier-list:
1975///          type-specifier specifier-qualifier-list[opt]
1976///          type-qualifier specifier-qualifier-list[opt]
1977/// [GNU]    attributes     specifier-qualifier-list[opt]
1978///
1979void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
1980                                         DeclSpecContext DSC) {
1981  /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
1982  /// parse declaration-specifiers and complain about extra stuff.
1983  /// TODO: diagnose attribute-specifiers and alignment-specifiers.
1984  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
1985
1986  // Validate declspec for type-name.
1987  unsigned Specs = DS.getParsedSpecifiers();
1988  if ((DSC == DSC_type_specifier || DSC == DSC_trailing) &&
1989      !DS.hasTypeSpecifier()) {
1990    Diag(Tok, diag::err_expected_type);
1991    DS.SetTypeSpecError();
1992  } else if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
1993             !DS.hasAttributes()) {
1994    Diag(Tok, diag::err_typename_requires_specqual);
1995    if (!DS.hasTypeSpecifier())
1996      DS.SetTypeSpecError();
1997  }
1998
1999  // Issue diagnostic and remove storage class if present.
2000  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2001    if (DS.getStorageClassSpecLoc().isValid())
2002      Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2003    else
2004      Diag(DS.getThreadStorageClassSpecLoc(),
2005           diag::err_typename_invalid_storageclass);
2006    DS.ClearStorageClassSpecs();
2007  }
2008
2009  // Issue diagnostic and remove function specfier if present.
2010  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2011    if (DS.isInlineSpecified())
2012      Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2013    if (DS.isVirtualSpecified())
2014      Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2015    if (DS.isExplicitSpecified())
2016      Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2017    DS.ClearFunctionSpecs();
2018  }
2019
2020  // Issue diagnostic and remove constexpr specfier if present.
2021  if (DS.isConstexprSpecified()) {
2022    Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2023    DS.ClearConstexprSpec();
2024  }
2025}
2026
2027/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2028/// specified token is valid after the identifier in a declarator which
2029/// immediately follows the declspec.  For example, these things are valid:
2030///
2031///      int x   [             4];         // direct-declarator
2032///      int x   (             int y);     // direct-declarator
2033///  int(int x   )                         // direct-declarator
2034///      int x   ;                         // simple-declaration
2035///      int x   =             17;         // init-declarator-list
2036///      int x   ,             y;          // init-declarator-list
2037///      int x   __asm__       ("foo");    // init-declarator-list
2038///      int x   :             4;          // struct-declarator
2039///      int x   {             5};         // C++'0x unified initializers
2040///
2041/// This is not, because 'x' does not immediately follow the declspec (though
2042/// ')' happens to be valid anyway).
2043///    int (x)
2044///
2045static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2046  return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
2047         T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
2048         T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
2049}
2050
2051
2052/// ParseImplicitInt - This method is called when we have an non-typename
2053/// identifier in a declspec (which normally terminates the decl spec) when
2054/// the declspec has no type specifier.  In this case, the declspec is either
2055/// malformed or is "implicit int" (in K&R and C89).
2056///
2057/// This method handles diagnosing this prettily and returns false if the
2058/// declspec is done being processed.  If it recovers and thinks there may be
2059/// other pieces of declspec after it, it returns true.
2060///
2061bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2062                              const ParsedTemplateInfo &TemplateInfo,
2063                              AccessSpecifier AS, DeclSpecContext DSC,
2064                              ParsedAttributesWithRange &Attrs) {
2065  assert(Tok.is(tok::identifier) && "should have identifier");
2066
2067  SourceLocation Loc = Tok.getLocation();
2068  // If we see an identifier that is not a type name, we normally would
2069  // parse it as the identifer being declared.  However, when a typename
2070  // is typo'd or the definition is not included, this will incorrectly
2071  // parse the typename as the identifier name and fall over misparsing
2072  // later parts of the diagnostic.
2073  //
2074  // As such, we try to do some look-ahead in cases where this would
2075  // otherwise be an "implicit-int" case to see if this is invalid.  For
2076  // example: "static foo_t x = 4;"  In this case, if we parsed foo_t as
2077  // an identifier with implicit int, we'd get a parse error because the
2078  // next token is obviously invalid for a type.  Parse these as a case
2079  // with an invalid type specifier.
2080  assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2081
2082  // Since we know that this either implicit int (which is rare) or an
2083  // error, do lookahead to try to do better recovery. This never applies
2084  // within a type specifier. Outside of C++, we allow this even if the
2085  // language doesn't "officially" support implicit int -- we support
2086  // implicit int as an extension in C99 and C11.
2087  if (DSC != DSC_type_specifier && DSC != DSC_trailing &&
2088      !getLangOpts().CPlusPlus &&
2089      isValidAfterIdentifierInDeclarator(NextToken())) {
2090    // If this token is valid for implicit int, e.g. "static x = 4", then
2091    // we just avoid eating the identifier, so it will be parsed as the
2092    // identifier in the declarator.
2093    return false;
2094  }
2095
2096  if (getLangOpts().CPlusPlus &&
2097      DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2098    // Don't require a type specifier if we have the 'auto' storage class
2099    // specifier in C++98 -- we'll promote it to a type specifier.
2100    return false;
2101  }
2102
2103  // Otherwise, if we don't consume this token, we are going to emit an
2104  // error anyway.  Try to recover from various common problems.  Check
2105  // to see if this was a reference to a tag name without a tag specified.
2106  // This is a common problem in C (saying 'foo' instead of 'struct foo').
2107  //
2108  // C++ doesn't need this, and isTagName doesn't take SS.
2109  if (SS == 0) {
2110    const char *TagName = 0, *FixitTagName = 0;
2111    tok::TokenKind TagKind = tok::unknown;
2112
2113    switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2114      default: break;
2115      case DeclSpec::TST_enum:
2116        TagName="enum"  ; FixitTagName = "enum "  ; TagKind=tok::kw_enum ;break;
2117      case DeclSpec::TST_union:
2118        TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2119      case DeclSpec::TST_struct:
2120        TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2121      case DeclSpec::TST_interface:
2122        TagName="__interface"; FixitTagName = "__interface ";
2123        TagKind=tok::kw___interface;break;
2124      case DeclSpec::TST_class:
2125        TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2126    }
2127
2128    if (TagName) {
2129      IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2130      LookupResult R(Actions, TokenName, SourceLocation(),
2131                     Sema::LookupOrdinaryName);
2132
2133      Diag(Loc, diag::err_use_of_tag_name_without_tag)
2134        << TokenName << TagName << getLangOpts().CPlusPlus
2135        << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2136
2137      if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2138        for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2139             I != IEnd; ++I)
2140          Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2141            << TokenName << TagName;
2142      }
2143
2144      // Parse this as a tag as if the missing tag were present.
2145      if (TagKind == tok::kw_enum)
2146        ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
2147      else
2148        ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2149                            /*EnteringContext*/ false, DSC_normal, Attrs);
2150      return true;
2151    }
2152  }
2153
2154  // Determine whether this identifier could plausibly be the name of something
2155  // being declared (with a missing type).
2156  if (DSC != DSC_type_specifier && DSC != DSC_trailing &&
2157      (!SS || DSC == DSC_top_level || DSC == DSC_class)) {
2158    // Look ahead to the next token to try to figure out what this declaration
2159    // was supposed to be.
2160    switch (NextToken().getKind()) {
2161    case tok::comma:
2162    case tok::equal:
2163    case tok::kw_asm:
2164    case tok::l_brace:
2165    case tok::l_square:
2166    case tok::semi:
2167      // This looks like a variable declaration. The type is probably missing.
2168      // We're done parsing decl-specifiers.
2169      return false;
2170
2171    case tok::l_paren: {
2172      // static x(4); // 'x' is not a type
2173      // x(int n);    // 'x' is not a type
2174      // x (*p)[];    // 'x' is a type
2175      //
2176      // Since we're in an error case (or the rare 'implicit int in C++' MS
2177      // extension), we can afford to perform a tentative parse to determine
2178      // which case we're in.
2179      TentativeParsingAction PA(*this);
2180      ConsumeToken();
2181      TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2182      PA.Revert();
2183      if (TPR == TPResult::False())
2184        return false;
2185      // The identifier is followed by a parenthesized declarator.
2186      // It's supposed to be a type.
2187      break;
2188    }
2189
2190    default:
2191      // This is probably supposed to be a type. This includes cases like:
2192      //   int f(itn);
2193      //   struct S { unsinged : 4; };
2194      break;
2195    }
2196  }
2197
2198  // This is almost certainly an invalid type name. Let the action emit a
2199  // diagnostic and attempt to recover.
2200  ParsedType T;
2201  IdentifierInfo *II = Tok.getIdentifierInfo();
2202  if (Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T)) {
2203    // The action emitted a diagnostic, so we don't have to.
2204    if (T) {
2205      // The action has suggested that the type T could be used. Set that as
2206      // the type in the declaration specifiers, consume the would-be type
2207      // name token, and we're done.
2208      const char *PrevSpec;
2209      unsigned DiagID;
2210      DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T);
2211      DS.SetRangeEnd(Tok.getLocation());
2212      ConsumeToken();
2213      // There may be other declaration specifiers after this.
2214      return true;
2215    } else if (II != Tok.getIdentifierInfo()) {
2216      // If no type was suggested, the correction is to a keyword
2217      Tok.setKind(II->getTokenID());
2218      // There may be other declaration specifiers after this.
2219      return true;
2220    }
2221
2222    // Fall through; the action had no suggestion for us.
2223  } else {
2224    // The action did not emit a diagnostic, so emit one now.
2225    SourceRange R;
2226    if (SS) R = SS->getRange();
2227    Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
2228  }
2229
2230  // Mark this as an error.
2231  DS.SetTypeSpecError();
2232  DS.SetRangeEnd(Tok.getLocation());
2233  ConsumeToken();
2234
2235  // TODO: Could inject an invalid typedef decl in an enclosing scope to
2236  // avoid rippling error messages on subsequent uses of the same type,
2237  // could be useful if #include was forgotten.
2238  return false;
2239}
2240
2241/// \brief Determine the declaration specifier context from the declarator
2242/// context.
2243///
2244/// \param Context the declarator context, which is one of the
2245/// Declarator::TheContext enumerator values.
2246Parser::DeclSpecContext
2247Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
2248  if (Context == Declarator::MemberContext)
2249    return DSC_class;
2250  if (Context == Declarator::FileContext)
2251    return DSC_top_level;
2252  if (Context == Declarator::TrailingReturnContext)
2253    return DSC_trailing;
2254  return DSC_normal;
2255}
2256
2257/// ParseAlignArgument - Parse the argument to an alignment-specifier.
2258///
2259/// FIXME: Simply returns an alignof() expression if the argument is a
2260/// type. Ideally, the type should be propagated directly into Sema.
2261///
2262/// [C11]   type-id
2263/// [C11]   constant-expression
2264/// [C++0x] type-id ...[opt]
2265/// [C++0x] assignment-expression ...[opt]
2266ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2267                                      SourceLocation &EllipsisLoc) {
2268  ExprResult ER;
2269  if (isTypeIdInParens()) {
2270    SourceLocation TypeLoc = Tok.getLocation();
2271    ParsedType Ty = ParseTypeName().get();
2272    SourceRange TypeRange(Start, Tok.getLocation());
2273    ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2274                                               Ty.getAsOpaquePtr(), TypeRange);
2275  } else
2276    ER = ParseConstantExpression();
2277
2278  if (getLangOpts().CPlusPlus11 && Tok.is(tok::ellipsis))
2279    EllipsisLoc = ConsumeToken();
2280
2281  return ER;
2282}
2283
2284/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2285/// attribute to Attrs.
2286///
2287/// alignment-specifier:
2288/// [C11]   '_Alignas' '(' type-id ')'
2289/// [C11]   '_Alignas' '(' constant-expression ')'
2290/// [C++11] 'alignas' '(' type-id ...[opt] ')'
2291/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2292void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2293                                     SourceLocation *EndLoc) {
2294  assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) &&
2295         "Not an alignment-specifier!");
2296
2297  IdentifierInfo *KWName = Tok.getIdentifierInfo();
2298  SourceLocation KWLoc = ConsumeToken();
2299
2300  BalancedDelimiterTracker T(*this, tok::l_paren);
2301  if (T.expectAndConsume(diag::err_expected_lparen))
2302    return;
2303
2304  SourceLocation EllipsisLoc;
2305  ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2306  if (ArgExpr.isInvalid()) {
2307    SkipUntil(tok::r_paren);
2308    return;
2309  }
2310
2311  T.consumeClose();
2312  if (EndLoc)
2313    *EndLoc = T.getCloseLocation();
2314
2315  ExprVector ArgExprs;
2316  ArgExprs.push_back(ArgExpr.release());
2317  Attrs.addNew(KWName, KWLoc, 0, KWLoc, 0, T.getOpenLocation(),
2318               ArgExprs.data(), 1, AttributeList::AS_Keyword, EllipsisLoc);
2319}
2320
2321/// ParseDeclarationSpecifiers
2322///       declaration-specifiers: [C99 6.7]
2323///         storage-class-specifier declaration-specifiers[opt]
2324///         type-specifier declaration-specifiers[opt]
2325/// [C99]   function-specifier declaration-specifiers[opt]
2326/// [C11]   alignment-specifier declaration-specifiers[opt]
2327/// [GNU]   attributes declaration-specifiers[opt]
2328/// [Clang] '__module_private__' declaration-specifiers[opt]
2329///
2330///       storage-class-specifier: [C99 6.7.1]
2331///         'typedef'
2332///         'extern'
2333///         'static'
2334///         'auto'
2335///         'register'
2336/// [C++]   'mutable'
2337/// [C++11] 'thread_local'
2338/// [C11]   '_Thread_local'
2339/// [GNU]   '__thread'
2340///       function-specifier: [C99 6.7.4]
2341/// [C99]   'inline'
2342/// [C++]   'virtual'
2343/// [C++]   'explicit'
2344/// [OpenCL] '__kernel'
2345///       'friend': [C++ dcl.friend]
2346///       'constexpr': [C++0x dcl.constexpr]
2347
2348///
2349void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2350                                        const ParsedTemplateInfo &TemplateInfo,
2351                                        AccessSpecifier AS,
2352                                        DeclSpecContext DSContext,
2353                                        LateParsedAttrList *LateAttrs) {
2354  if (DS.getSourceRange().isInvalid()) {
2355    DS.SetRangeStart(Tok.getLocation());
2356    DS.SetRangeEnd(Tok.getLocation());
2357  }
2358
2359  bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2360  bool AttrsLastTime = false;
2361  ParsedAttributesWithRange attrs(AttrFactory);
2362  while (1) {
2363    bool isInvalid = false;
2364    const char *PrevSpec = 0;
2365    unsigned DiagID = 0;
2366
2367    SourceLocation Loc = Tok.getLocation();
2368
2369    switch (Tok.getKind()) {
2370    default:
2371    DoneWithDeclSpec:
2372      if (!AttrsLastTime)
2373        ProhibitAttributes(attrs);
2374      else {
2375        // Reject C++11 attributes that appertain to decl specifiers as
2376        // we don't support any C++11 attributes that appertain to decl
2377        // specifiers. This also conforms to what g++ 4.8 is doing.
2378        ProhibitCXX11Attributes(attrs);
2379
2380        DS.takeAttributesFrom(attrs);
2381      }
2382
2383      // If this is not a declaration specifier token, we're done reading decl
2384      // specifiers.  First verify that DeclSpec's are consistent.
2385      DS.Finish(Diags, PP);
2386      return;
2387
2388    case tok::l_square:
2389    case tok::kw_alignas:
2390      if (!getLangOpts().CPlusPlus11 || !isCXX11AttributeSpecifier())
2391        goto DoneWithDeclSpec;
2392
2393      ProhibitAttributes(attrs);
2394      // FIXME: It would be good to recover by accepting the attributes,
2395      //        but attempting to do that now would cause serious
2396      //        madness in terms of diagnostics.
2397      attrs.clear();
2398      attrs.Range = SourceRange();
2399
2400      ParseCXX11Attributes(attrs);
2401      AttrsLastTime = true;
2402      continue;
2403
2404    case tok::code_completion: {
2405      Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2406      if (DS.hasTypeSpecifier()) {
2407        bool AllowNonIdentifiers
2408          = (getCurScope()->getFlags() & (Scope::ControlScope |
2409                                          Scope::BlockScope |
2410                                          Scope::TemplateParamScope |
2411                                          Scope::FunctionPrototypeScope |
2412                                          Scope::AtCatchScope)) == 0;
2413        bool AllowNestedNameSpecifiers
2414          = DSContext == DSC_top_level ||
2415            (DSContext == DSC_class && DS.isFriendSpecified());
2416
2417        Actions.CodeCompleteDeclSpec(getCurScope(), DS,
2418                                     AllowNonIdentifiers,
2419                                     AllowNestedNameSpecifiers);
2420        return cutOffParsing();
2421      }
2422
2423      if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
2424        CCC = Sema::PCC_LocalDeclarationSpecifiers;
2425      else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
2426        CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
2427                                    : Sema::PCC_Template;
2428      else if (DSContext == DSC_class)
2429        CCC = Sema::PCC_Class;
2430      else if (CurParsedObjCImpl)
2431        CCC = Sema::PCC_ObjCImplementation;
2432
2433      Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
2434      return cutOffParsing();
2435    }
2436
2437    case tok::coloncolon: // ::foo::bar
2438      // C++ scope specifier.  Annotate and loop, or bail out on error.
2439      if (TryAnnotateCXXScopeToken(EnteringContext)) {
2440        if (!DS.hasTypeSpecifier())
2441          DS.SetTypeSpecError();
2442        goto DoneWithDeclSpec;
2443      }
2444      if (Tok.is(tok::coloncolon)) // ::new or ::delete
2445        goto DoneWithDeclSpec;
2446      continue;
2447
2448    case tok::annot_cxxscope: {
2449      if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
2450        goto DoneWithDeclSpec;
2451
2452      CXXScopeSpec SS;
2453      Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2454                                                   Tok.getAnnotationRange(),
2455                                                   SS);
2456
2457      // We are looking for a qualified typename.
2458      Token Next = NextToken();
2459      if (Next.is(tok::annot_template_id) &&
2460          static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
2461            ->Kind == TNK_Type_template) {
2462        // We have a qualified template-id, e.g., N::A<int>
2463
2464        // C++ [class.qual]p2:
2465        //   In a lookup in which the constructor is an acceptable lookup
2466        //   result and the nested-name-specifier nominates a class C:
2467        //
2468        //     - if the name specified after the
2469        //       nested-name-specifier, when looked up in C, is the
2470        //       injected-class-name of C (Clause 9), or
2471        //
2472        //     - if the name specified after the nested-name-specifier
2473        //       is the same as the identifier or the
2474        //       simple-template-id's template-name in the last
2475        //       component of the nested-name-specifier,
2476        //
2477        //   the name is instead considered to name the constructor of
2478        //   class C.
2479        //
2480        // Thus, if the template-name is actually the constructor
2481        // name, then the code is ill-formed; this interpretation is
2482        // reinforced by the NAD status of core issue 635.
2483        TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
2484        if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2485            TemplateId->Name &&
2486            Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2487          if (isConstructorDeclarator()) {
2488            // The user meant this to be an out-of-line constructor
2489            // definition, but template arguments are not allowed
2490            // there.  Just allow this as a constructor; we'll
2491            // complain about it later.
2492            goto DoneWithDeclSpec;
2493          }
2494
2495          // The user meant this to name a type, but it actually names
2496          // a constructor with some extraneous template
2497          // arguments. Complain, then parse it as a type as the user
2498          // intended.
2499          Diag(TemplateId->TemplateNameLoc,
2500               diag::err_out_of_line_template_id_names_constructor)
2501            << TemplateId->Name;
2502        }
2503
2504        DS.getTypeSpecScope() = SS;
2505        ConsumeToken(); // The C++ scope.
2506        assert(Tok.is(tok::annot_template_id) &&
2507               "ParseOptionalCXXScopeSpecifier not working");
2508        AnnotateTemplateIdTokenAsType();
2509        continue;
2510      }
2511
2512      if (Next.is(tok::annot_typename)) {
2513        DS.getTypeSpecScope() = SS;
2514        ConsumeToken(); // The C++ scope.
2515        if (Tok.getAnnotationValue()) {
2516          ParsedType T = getTypeAnnotation(Tok);
2517          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
2518                                         Tok.getAnnotationEndLoc(),
2519                                         PrevSpec, DiagID, T);
2520          if (isInvalid)
2521            break;
2522        }
2523        else
2524          DS.SetTypeSpecError();
2525        DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2526        ConsumeToken(); // The typename
2527      }
2528
2529      if (Next.isNot(tok::identifier))
2530        goto DoneWithDeclSpec;
2531
2532      // If we're in a context where the identifier could be a class name,
2533      // check whether this is a constructor declaration.
2534      if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2535          Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
2536                                     &SS)) {
2537        if (isConstructorDeclarator())
2538          goto DoneWithDeclSpec;
2539
2540        // As noted in C++ [class.qual]p2 (cited above), when the name
2541        // of the class is qualified in a context where it could name
2542        // a constructor, its a constructor name. However, we've
2543        // looked at the declarator, and the user probably meant this
2544        // to be a type. Complain that it isn't supposed to be treated
2545        // as a type, then proceed to parse it as a type.
2546        Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
2547          << Next.getIdentifierInfo();
2548      }
2549
2550      ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
2551                                               Next.getLocation(),
2552                                               getCurScope(), &SS,
2553                                               false, false, ParsedType(),
2554                                               /*IsCtorOrDtorName=*/false,
2555                                               /*NonTrivialSourceInfo=*/true);
2556
2557      // If the referenced identifier is not a type, then this declspec is
2558      // erroneous: We already checked about that it has no type specifier, and
2559      // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
2560      // typename.
2561      if (!TypeRep) {
2562        ConsumeToken();   // Eat the scope spec so the identifier is current.
2563        ParsedAttributesWithRange Attrs(AttrFactory);
2564        if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
2565          if (!Attrs.empty()) {
2566            AttrsLastTime = true;
2567            attrs.takeAllFrom(Attrs);
2568          }
2569          continue;
2570        }
2571        goto DoneWithDeclSpec;
2572      }
2573
2574      DS.getTypeSpecScope() = SS;
2575      ConsumeToken(); // The C++ scope.
2576
2577      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2578                                     DiagID, TypeRep);
2579      if (isInvalid)
2580        break;
2581
2582      DS.SetRangeEnd(Tok.getLocation());
2583      ConsumeToken(); // The typename.
2584
2585      continue;
2586    }
2587
2588    case tok::annot_typename: {
2589      if (Tok.getAnnotationValue()) {
2590        ParsedType T = getTypeAnnotation(Tok);
2591        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2592                                       DiagID, T);
2593      } else
2594        DS.SetTypeSpecError();
2595
2596      if (isInvalid)
2597        break;
2598
2599      DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2600      ConsumeToken(); // The typename
2601
2602      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2603      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2604      // Objective-C interface.
2605      if (Tok.is(tok::less) && getLangOpts().ObjC1)
2606        ParseObjCProtocolQualifiers(DS);
2607
2608      continue;
2609    }
2610
2611    case tok::kw___is_signed:
2612      // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
2613      // typically treats it as a trait. If we see __is_signed as it appears
2614      // in libstdc++, e.g.,
2615      //
2616      //   static const bool __is_signed;
2617      //
2618      // then treat __is_signed as an identifier rather than as a keyword.
2619      if (DS.getTypeSpecType() == TST_bool &&
2620          DS.getTypeQualifiers() == DeclSpec::TQ_const &&
2621          DS.getStorageClassSpec() == DeclSpec::SCS_static) {
2622        Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
2623        Tok.setKind(tok::identifier);
2624      }
2625
2626      // We're done with the declaration-specifiers.
2627      goto DoneWithDeclSpec;
2628
2629      // typedef-name
2630    case tok::kw_decltype:
2631    case tok::identifier: {
2632      // In C++, check to see if this is a scope specifier like foo::bar::, if
2633      // so handle it as such.  This is important for ctor parsing.
2634      if (getLangOpts().CPlusPlus) {
2635        if (TryAnnotateCXXScopeToken(EnteringContext)) {
2636          if (!DS.hasTypeSpecifier())
2637            DS.SetTypeSpecError();
2638          goto DoneWithDeclSpec;
2639        }
2640        if (!Tok.is(tok::identifier))
2641          continue;
2642      }
2643
2644      // This identifier can only be a typedef name if we haven't already seen
2645      // a type-specifier.  Without this check we misparse:
2646      //  typedef int X; struct Y { short X; };  as 'short int'.
2647      if (DS.hasTypeSpecifier())
2648        goto DoneWithDeclSpec;
2649
2650      // Check for need to substitute AltiVec keyword tokens.
2651      if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
2652        break;
2653
2654      // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
2655      //                allow the use of a typedef name as a type specifier.
2656      if (DS.isTypeAltiVecVector())
2657        goto DoneWithDeclSpec;
2658
2659      ParsedType TypeRep =
2660        Actions.getTypeName(*Tok.getIdentifierInfo(),
2661                            Tok.getLocation(), getCurScope());
2662
2663      // If this is not a typedef name, don't parse it as part of the declspec,
2664      // it must be an implicit int or an error.
2665      if (!TypeRep) {
2666        ParsedAttributesWithRange Attrs(AttrFactory);
2667        if (ParseImplicitInt(DS, 0, TemplateInfo, AS, DSContext, Attrs)) {
2668          if (!Attrs.empty()) {
2669            AttrsLastTime = true;
2670            attrs.takeAllFrom(Attrs);
2671          }
2672          continue;
2673        }
2674        goto DoneWithDeclSpec;
2675      }
2676
2677      // If we're in a context where the identifier could be a class name,
2678      // check whether this is a constructor declaration.
2679      if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2680          Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
2681          isConstructorDeclarator())
2682        goto DoneWithDeclSpec;
2683
2684      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2685                                     DiagID, TypeRep);
2686      if (isInvalid)
2687        break;
2688
2689      DS.SetRangeEnd(Tok.getLocation());
2690      ConsumeToken(); // The identifier
2691
2692      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2693      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2694      // Objective-C interface.
2695      if (Tok.is(tok::less) && getLangOpts().ObjC1)
2696        ParseObjCProtocolQualifiers(DS);
2697
2698      // Need to support trailing type qualifiers (e.g. "id<p> const").
2699      // If a type specifier follows, it will be diagnosed elsewhere.
2700      continue;
2701    }
2702
2703      // type-name
2704    case tok::annot_template_id: {
2705      TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2706      if (TemplateId->Kind != TNK_Type_template) {
2707        // This template-id does not refer to a type name, so we're
2708        // done with the type-specifiers.
2709        goto DoneWithDeclSpec;
2710      }
2711
2712      // If we're in a context where the template-id could be a
2713      // constructor name or specialization, check whether this is a
2714      // constructor declaration.
2715      if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2716          Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
2717          isConstructorDeclarator())
2718        goto DoneWithDeclSpec;
2719
2720      // Turn the template-id annotation token into a type annotation
2721      // token, then try again to parse it as a type-specifier.
2722      AnnotateTemplateIdTokenAsType();
2723      continue;
2724    }
2725
2726    // GNU attributes support.
2727    case tok::kw___attribute:
2728      ParseGNUAttributes(DS.getAttributes(), 0, LateAttrs);
2729      continue;
2730
2731    // Microsoft declspec support.
2732    case tok::kw___declspec:
2733      ParseMicrosoftDeclSpec(DS.getAttributes());
2734      continue;
2735
2736    // Microsoft single token adornments.
2737    case tok::kw___forceinline: {
2738      isInvalid = DS.setFunctionSpecInline(Loc);
2739      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
2740      SourceLocation AttrNameLoc = Tok.getLocation();
2741      // FIXME: This does not work correctly if it is set to be a declspec
2742      //        attribute, and a GNU attribute is simply incorrect.
2743      DS.getAttributes().addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
2744                                SourceLocation(), 0, 0, AttributeList::AS_GNU);
2745      break;
2746    }
2747
2748    case tok::kw___sptr:
2749    case tok::kw___uptr:
2750    case tok::kw___ptr64:
2751    case tok::kw___ptr32:
2752    case tok::kw___w64:
2753    case tok::kw___cdecl:
2754    case tok::kw___stdcall:
2755    case tok::kw___fastcall:
2756    case tok::kw___thiscall:
2757    case tok::kw___unaligned:
2758      ParseMicrosoftTypeAttributes(DS.getAttributes());
2759      continue;
2760
2761    // Borland single token adornments.
2762    case tok::kw___pascal:
2763      ParseBorlandTypeAttributes(DS.getAttributes());
2764      continue;
2765
2766    // OpenCL single token adornments.
2767    case tok::kw___kernel:
2768      ParseOpenCLAttributes(DS.getAttributes());
2769      continue;
2770
2771    // storage-class-specifier
2772    case tok::kw_typedef:
2773      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
2774                                         PrevSpec, DiagID);
2775      break;
2776    case tok::kw_extern:
2777      if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
2778        Diag(Tok, diag::ext_thread_before) << "extern";
2779      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
2780                                         PrevSpec, DiagID);
2781      break;
2782    case tok::kw___private_extern__:
2783      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
2784                                         Loc, PrevSpec, DiagID);
2785      break;
2786    case tok::kw_static:
2787      if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
2788        Diag(Tok, diag::ext_thread_before) << "static";
2789      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
2790                                         PrevSpec, DiagID);
2791      break;
2792    case tok::kw_auto:
2793      if (getLangOpts().CPlusPlus11) {
2794        if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
2795          isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
2796                                             PrevSpec, DiagID);
2797          if (!isInvalid)
2798            Diag(Tok, diag::ext_auto_storage_class)
2799              << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
2800        } else
2801          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
2802                                         DiagID);
2803      } else
2804        isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
2805                                           PrevSpec, DiagID);
2806      break;
2807    case tok::kw_register:
2808      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
2809                                         PrevSpec, DiagID);
2810      break;
2811    case tok::kw_mutable:
2812      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
2813                                         PrevSpec, DiagID);
2814      break;
2815    case tok::kw___thread:
2816      isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
2817                                               PrevSpec, DiagID);
2818      break;
2819    case tok::kw_thread_local:
2820      isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
2821                                               PrevSpec, DiagID);
2822      break;
2823    case tok::kw__Thread_local:
2824      isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
2825                                               Loc, PrevSpec, DiagID);
2826      break;
2827
2828    // function-specifier
2829    case tok::kw_inline:
2830      isInvalid = DS.setFunctionSpecInline(Loc);
2831      break;
2832    case tok::kw_virtual:
2833      isInvalid = DS.setFunctionSpecVirtual(Loc);
2834      break;
2835    case tok::kw_explicit:
2836      isInvalid = DS.setFunctionSpecExplicit(Loc);
2837      break;
2838    case tok::kw__Noreturn:
2839      if (!getLangOpts().C11)
2840        Diag(Loc, diag::ext_c11_noreturn);
2841      isInvalid = DS.setFunctionSpecNoreturn(Loc);
2842      break;
2843
2844    // alignment-specifier
2845    case tok::kw__Alignas:
2846      if (!getLangOpts().C11)
2847        Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
2848      ParseAlignmentSpecifier(DS.getAttributes());
2849      continue;
2850
2851    // friend
2852    case tok::kw_friend:
2853      if (DSContext == DSC_class)
2854        isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
2855      else {
2856        PrevSpec = ""; // not actually used by the diagnostic
2857        DiagID = diag::err_friend_invalid_in_context;
2858        isInvalid = true;
2859      }
2860      break;
2861
2862    // Modules
2863    case tok::kw___module_private__:
2864      isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
2865      break;
2866
2867    // constexpr
2868    case tok::kw_constexpr:
2869      isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
2870      break;
2871
2872    // type-specifier
2873    case tok::kw_short:
2874      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
2875                                      DiagID);
2876      break;
2877    case tok::kw_long:
2878      if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
2879        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
2880                                        DiagID);
2881      else
2882        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2883                                        DiagID);
2884      break;
2885    case tok::kw___int64:
2886        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2887                                        DiagID);
2888      break;
2889    case tok::kw_signed:
2890      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
2891                                     DiagID);
2892      break;
2893    case tok::kw_unsigned:
2894      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
2895                                     DiagID);
2896      break;
2897    case tok::kw__Complex:
2898      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
2899                                        DiagID);
2900      break;
2901    case tok::kw__Imaginary:
2902      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
2903                                        DiagID);
2904      break;
2905    case tok::kw_void:
2906      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
2907                                     DiagID);
2908      break;
2909    case tok::kw_char:
2910      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
2911                                     DiagID);
2912      break;
2913    case tok::kw_int:
2914      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
2915                                     DiagID);
2916      break;
2917    case tok::kw___int128:
2918      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
2919                                     DiagID);
2920      break;
2921    case tok::kw_half:
2922      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
2923                                     DiagID);
2924      break;
2925    case tok::kw_float:
2926      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
2927                                     DiagID);
2928      break;
2929    case tok::kw_double:
2930      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
2931                                     DiagID);
2932      break;
2933    case tok::kw_wchar_t:
2934      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
2935                                     DiagID);
2936      break;
2937    case tok::kw_char16_t:
2938      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
2939                                     DiagID);
2940      break;
2941    case tok::kw_char32_t:
2942      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
2943                                     DiagID);
2944      break;
2945    case tok::kw_bool:
2946    case tok::kw__Bool:
2947      if (Tok.is(tok::kw_bool) &&
2948          DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
2949          DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2950        PrevSpec = ""; // Not used by the diagnostic.
2951        DiagID = diag::err_bool_redeclaration;
2952        // For better error recovery.
2953        Tok.setKind(tok::identifier);
2954        isInvalid = true;
2955      } else {
2956        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
2957                                       DiagID);
2958      }
2959      break;
2960    case tok::kw__Decimal32:
2961      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
2962                                     DiagID);
2963      break;
2964    case tok::kw__Decimal64:
2965      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
2966                                     DiagID);
2967      break;
2968    case tok::kw__Decimal128:
2969      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
2970                                     DiagID);
2971      break;
2972    case tok::kw___vector:
2973      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
2974      break;
2975    case tok::kw___pixel:
2976      isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
2977      break;
2978    case tok::kw_image1d_t:
2979       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image1d_t, Loc,
2980                                      PrevSpec, DiagID);
2981      break;
2982    case tok::kw_image1d_array_t:
2983       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image1d_array_t, Loc,
2984                                      PrevSpec, DiagID);
2985      break;
2986    case tok::kw_image1d_buffer_t:
2987       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image1d_buffer_t, Loc,
2988                                      PrevSpec, DiagID);
2989      break;
2990    case tok::kw_image2d_t:
2991       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image2d_t, Loc,
2992                                      PrevSpec, DiagID);
2993      break;
2994    case tok::kw_image2d_array_t:
2995       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image2d_array_t, Loc,
2996                                      PrevSpec, DiagID);
2997      break;
2998    case tok::kw_image3d_t:
2999      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image3d_t, Loc,
3000                                     PrevSpec, DiagID);
3001      break;
3002    case tok::kw_sampler_t:
3003      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_sampler_t, Loc,
3004                                     PrevSpec, DiagID);
3005      break;
3006    case tok::kw_event_t:
3007      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_event_t, Loc,
3008                                     PrevSpec, DiagID);
3009      break;
3010    case tok::kw___unknown_anytype:
3011      isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3012                                     PrevSpec, DiagID);
3013      break;
3014
3015    // class-specifier:
3016    case tok::kw_class:
3017    case tok::kw_struct:
3018    case tok::kw___interface:
3019    case tok::kw_union: {
3020      tok::TokenKind Kind = Tok.getKind();
3021      ConsumeToken();
3022
3023      // These are attributes following class specifiers.
3024      // To produce better diagnostic, we parse them when
3025      // parsing class specifier.
3026      ParsedAttributesWithRange Attributes(AttrFactory);
3027      ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3028                          EnteringContext, DSContext, Attributes);
3029
3030      // If there are attributes following class specifier,
3031      // take them over and handle them here.
3032      if (!Attributes.empty()) {
3033        AttrsLastTime = true;
3034        attrs.takeAllFrom(Attributes);
3035      }
3036      continue;
3037    }
3038
3039    // enum-specifier:
3040    case tok::kw_enum:
3041      ConsumeToken();
3042      ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3043      continue;
3044
3045    // cv-qualifier:
3046    case tok::kw_const:
3047      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3048                                 getLangOpts());
3049      break;
3050    case tok::kw_volatile:
3051      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3052                                 getLangOpts());
3053      break;
3054    case tok::kw_restrict:
3055      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3056                                 getLangOpts());
3057      break;
3058
3059    // C++ typename-specifier:
3060    case tok::kw_typename:
3061      if (TryAnnotateTypeOrScopeToken()) {
3062        DS.SetTypeSpecError();
3063        goto DoneWithDeclSpec;
3064      }
3065      if (!Tok.is(tok::kw_typename))
3066        continue;
3067      break;
3068
3069    // GNU typeof support.
3070    case tok::kw_typeof:
3071      ParseTypeofSpecifier(DS);
3072      continue;
3073
3074    case tok::annot_decltype:
3075      ParseDecltypeSpecifier(DS);
3076      continue;
3077
3078    case tok::kw___underlying_type:
3079      ParseUnderlyingTypeSpecifier(DS);
3080      continue;
3081
3082    case tok::kw__Atomic:
3083      // C11 6.7.2.4/4:
3084      //   If the _Atomic keyword is immediately followed by a left parenthesis,
3085      //   it is interpreted as a type specifier (with a type name), not as a
3086      //   type qualifier.
3087      if (NextToken().is(tok::l_paren)) {
3088        ParseAtomicSpecifier(DS);
3089        continue;
3090      }
3091      isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3092                                 getLangOpts());
3093      break;
3094
3095    // OpenCL qualifiers:
3096    case tok::kw_private:
3097      if (!getLangOpts().OpenCL)
3098        goto DoneWithDeclSpec;
3099    case tok::kw___private:
3100    case tok::kw___global:
3101    case tok::kw___local:
3102    case tok::kw___constant:
3103    case tok::kw___read_only:
3104    case tok::kw___write_only:
3105    case tok::kw___read_write:
3106      ParseOpenCLQualifiers(DS);
3107      break;
3108
3109    case tok::less:
3110      // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3111      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
3112      // but we support it.
3113      if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
3114        goto DoneWithDeclSpec;
3115
3116      if (!ParseObjCProtocolQualifiers(DS))
3117        Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
3118          << FixItHint::CreateInsertion(Loc, "id")
3119          << SourceRange(Loc, DS.getSourceRange().getEnd());
3120
3121      // Need to support trailing type qualifiers (e.g. "id<p> const").
3122      // If a type specifier follows, it will be diagnosed elsewhere.
3123      continue;
3124    }
3125    // If the specifier wasn't legal, issue a diagnostic.
3126    if (isInvalid) {
3127      assert(PrevSpec && "Method did not return previous specifier!");
3128      assert(DiagID);
3129
3130      if (DiagID == diag::ext_duplicate_declspec)
3131        Diag(Tok, DiagID)
3132          << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
3133      else
3134        Diag(Tok, DiagID) << PrevSpec;
3135    }
3136
3137    DS.SetRangeEnd(Tok.getLocation());
3138    if (DiagID != diag::err_bool_redeclaration)
3139      ConsumeToken();
3140
3141    AttrsLastTime = false;
3142  }
3143}
3144
3145/// ParseStructDeclaration - Parse a struct declaration without the terminating
3146/// semicolon.
3147///
3148///       struct-declaration:
3149///         specifier-qualifier-list struct-declarator-list
3150/// [GNU]   __extension__ struct-declaration
3151/// [GNU]   specifier-qualifier-list
3152///       struct-declarator-list:
3153///         struct-declarator
3154///         struct-declarator-list ',' struct-declarator
3155/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
3156///       struct-declarator:
3157///         declarator
3158/// [GNU]   declarator attributes[opt]
3159///         declarator[opt] ':' constant-expression
3160/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
3161///
3162void Parser::
3163ParseStructDeclaration(ParsingDeclSpec &DS, FieldCallback &Fields) {
3164
3165  if (Tok.is(tok::kw___extension__)) {
3166    // __extension__ silences extension warnings in the subexpression.
3167    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
3168    ConsumeToken();
3169    return ParseStructDeclaration(DS, Fields);
3170  }
3171
3172  // Parse the common specifier-qualifiers-list piece.
3173  ParseSpecifierQualifierList(DS);
3174
3175  // If there are no declarators, this is a free-standing declaration
3176  // specifier. Let the actions module cope with it.
3177  if (Tok.is(tok::semi)) {
3178    Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
3179                                                       DS);
3180    DS.complete(TheDecl);
3181    return;
3182  }
3183
3184  // Read struct-declarators until we find the semicolon.
3185  bool FirstDeclarator = true;
3186  SourceLocation CommaLoc;
3187  while (1) {
3188    ParsingFieldDeclarator DeclaratorInfo(*this, DS);
3189    DeclaratorInfo.D.setCommaLoc(CommaLoc);
3190
3191    // Attributes are only allowed here on successive declarators.
3192    if (!FirstDeclarator)
3193      MaybeParseGNUAttributes(DeclaratorInfo.D);
3194
3195    /// struct-declarator: declarator
3196    /// struct-declarator: declarator[opt] ':' constant-expression
3197    if (Tok.isNot(tok::colon)) {
3198      // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3199      ColonProtectionRAIIObject X(*this);
3200      ParseDeclarator(DeclaratorInfo.D);
3201    }
3202
3203    if (Tok.is(tok::colon)) {
3204      ConsumeToken();
3205      ExprResult Res(ParseConstantExpression());
3206      if (Res.isInvalid())
3207        SkipUntil(tok::semi, true, true);
3208      else
3209        DeclaratorInfo.BitfieldSize = Res.release();
3210    }
3211
3212    // If attributes exist after the declarator, parse them.
3213    MaybeParseGNUAttributes(DeclaratorInfo.D);
3214
3215    // We're done with this declarator;  invoke the callback.
3216    Fields.invoke(DeclaratorInfo);
3217
3218    // If we don't have a comma, it is either the end of the list (a ';')
3219    // or an error, bail out.
3220    if (Tok.isNot(tok::comma))
3221      return;
3222
3223    // Consume the comma.
3224    CommaLoc = ConsumeToken();
3225
3226    FirstDeclarator = false;
3227  }
3228}
3229
3230/// ParseStructUnionBody
3231///       struct-contents:
3232///         struct-declaration-list
3233/// [EXT]   empty
3234/// [GNU]   "struct-declaration-list" without terminatoring ';'
3235///       struct-declaration-list:
3236///         struct-declaration
3237///         struct-declaration-list struct-declaration
3238/// [OBC]   '@' 'defs' '(' class-name ')'
3239///
3240void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
3241                                  unsigned TagType, Decl *TagDecl) {
3242  PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3243                                      "parsing struct/union body");
3244  assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
3245
3246  BalancedDelimiterTracker T(*this, tok::l_brace);
3247  if (T.consumeOpen())
3248    return;
3249
3250  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
3251  Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3252
3253  SmallVector<Decl *, 32> FieldDecls;
3254
3255  // While we still have something to read, read the declarations in the struct.
3256  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
3257    // Each iteration of this loop reads one struct-declaration.
3258
3259    // Check for extraneous top-level semicolon.
3260    if (Tok.is(tok::semi)) {
3261      ConsumeExtraSemi(InsideStruct, TagType);
3262      continue;
3263    }
3264
3265    // Parse _Static_assert declaration.
3266    if (Tok.is(tok::kw__Static_assert)) {
3267      SourceLocation DeclEnd;
3268      ParseStaticAssertDeclaration(DeclEnd);
3269      continue;
3270    }
3271
3272    if (Tok.is(tok::annot_pragma_pack)) {
3273      HandlePragmaPack();
3274      continue;
3275    }
3276
3277    if (Tok.is(tok::annot_pragma_align)) {
3278      HandlePragmaAlign();
3279      continue;
3280    }
3281
3282    if (!Tok.is(tok::at)) {
3283      struct CFieldCallback : FieldCallback {
3284        Parser &P;
3285        Decl *TagDecl;
3286        SmallVectorImpl<Decl *> &FieldDecls;
3287
3288        CFieldCallback(Parser &P, Decl *TagDecl,
3289                       SmallVectorImpl<Decl *> &FieldDecls) :
3290          P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
3291
3292        void invoke(ParsingFieldDeclarator &FD) {
3293          // Install the declarator into the current TagDecl.
3294          Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl,
3295                              FD.D.getDeclSpec().getSourceRange().getBegin(),
3296                                                 FD.D, FD.BitfieldSize);
3297          FieldDecls.push_back(Field);
3298          FD.complete(Field);
3299        }
3300      } Callback(*this, TagDecl, FieldDecls);
3301
3302      // Parse all the comma separated declarators.
3303      ParsingDeclSpec DS(*this);
3304      ParseStructDeclaration(DS, Callback);
3305    } else { // Handle @defs
3306      ConsumeToken();
3307      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
3308        Diag(Tok, diag::err_unexpected_at);
3309        SkipUntil(tok::semi, true);
3310        continue;
3311      }
3312      ConsumeToken();
3313      ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
3314      if (!Tok.is(tok::identifier)) {
3315        Diag(Tok, diag::err_expected_ident);
3316        SkipUntil(tok::semi, true);
3317        continue;
3318      }
3319      SmallVector<Decl *, 16> Fields;
3320      Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
3321                        Tok.getIdentifierInfo(), Fields);
3322      FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
3323      ConsumeToken();
3324      ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
3325    }
3326
3327    if (Tok.is(tok::semi)) {
3328      ConsumeToken();
3329    } else if (Tok.is(tok::r_brace)) {
3330      ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
3331      break;
3332    } else {
3333      ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
3334      // Skip to end of block or statement to avoid ext-warning on extra ';'.
3335      SkipUntil(tok::r_brace, true, true);
3336      // If we stopped at a ';', eat it.
3337      if (Tok.is(tok::semi)) ConsumeToken();
3338    }
3339  }
3340
3341  T.consumeClose();
3342
3343  ParsedAttributes attrs(AttrFactory);
3344  // If attributes exist after struct contents, parse them.
3345  MaybeParseGNUAttributes(attrs);
3346
3347  Actions.ActOnFields(getCurScope(),
3348                      RecordLoc, TagDecl, FieldDecls,
3349                      T.getOpenLocation(), T.getCloseLocation(),
3350                      attrs.getList());
3351  StructScope.Exit();
3352  Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
3353                                   T.getCloseLocation());
3354}
3355
3356/// ParseEnumSpecifier
3357///       enum-specifier: [C99 6.7.2.2]
3358///         'enum' identifier[opt] '{' enumerator-list '}'
3359///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
3360/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
3361///                                                 '}' attributes[opt]
3362/// [MS]    'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
3363///                                                 '}'
3364///         'enum' identifier
3365/// [GNU]   'enum' attributes[opt] identifier
3366///
3367/// [C++11] enum-head '{' enumerator-list[opt] '}'
3368/// [C++11] enum-head '{' enumerator-list ','  '}'
3369///
3370///       enum-head: [C++11]
3371///         enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
3372///         enum-key attribute-specifier-seq[opt] nested-name-specifier
3373///             identifier enum-base[opt]
3374///
3375///       enum-key: [C++11]
3376///         'enum'
3377///         'enum' 'class'
3378///         'enum' 'struct'
3379///
3380///       enum-base: [C++11]
3381///         ':' type-specifier-seq
3382///
3383/// [C++] elaborated-type-specifier:
3384/// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
3385///
3386void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
3387                                const ParsedTemplateInfo &TemplateInfo,
3388                                AccessSpecifier AS, DeclSpecContext DSC) {
3389  // Parse the tag portion of this.
3390  if (Tok.is(tok::code_completion)) {
3391    // Code completion for an enum name.
3392    Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
3393    return cutOffParsing();
3394  }
3395
3396  // If attributes exist after tag, parse them.
3397  ParsedAttributesWithRange attrs(AttrFactory);
3398  MaybeParseGNUAttributes(attrs);
3399  MaybeParseCXX11Attributes(attrs);
3400
3401  // If declspecs exist after tag, parse them.
3402  while (Tok.is(tok::kw___declspec))
3403    ParseMicrosoftDeclSpec(attrs);
3404
3405  SourceLocation ScopedEnumKWLoc;
3406  bool IsScopedUsingClassTag = false;
3407
3408  // In C++11, recognize 'enum class' and 'enum struct'.
3409  if (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct)) {
3410    Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
3411                                        : diag::ext_scoped_enum);
3412    IsScopedUsingClassTag = Tok.is(tok::kw_class);
3413    ScopedEnumKWLoc = ConsumeToken();
3414
3415    // Attributes are not allowed between these keywords.  Diagnose,
3416    // but then just treat them like they appeared in the right place.
3417    ProhibitAttributes(attrs);
3418
3419    // They are allowed afterwards, though.
3420    MaybeParseGNUAttributes(attrs);
3421    MaybeParseCXX11Attributes(attrs);
3422    while (Tok.is(tok::kw___declspec))
3423      ParseMicrosoftDeclSpec(attrs);
3424  }
3425
3426  // C++11 [temp.explicit]p12:
3427  //   The usual access controls do not apply to names used to specify
3428  //   explicit instantiations.
3429  // We extend this to also cover explicit specializations.  Note that
3430  // we don't suppress if this turns out to be an elaborated type
3431  // specifier.
3432  bool shouldDelayDiagsInTag =
3433    (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3434     TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3435  SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
3436
3437  // Enum definitions should not be parsed in a trailing-return-type.
3438  bool AllowDeclaration = DSC != DSC_trailing;
3439
3440  bool AllowFixedUnderlyingType = AllowDeclaration &&
3441    (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
3442     getLangOpts().ObjC2);
3443
3444  CXXScopeSpec &SS = DS.getTypeSpecScope();
3445  if (getLangOpts().CPlusPlus) {
3446    // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
3447    // if a fixed underlying type is allowed.
3448    ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
3449
3450    if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
3451                                       /*EnteringContext=*/true))
3452      return;
3453
3454    if (SS.isSet() && Tok.isNot(tok::identifier)) {
3455      Diag(Tok, diag::err_expected_ident);
3456      if (Tok.isNot(tok::l_brace)) {
3457        // Has no name and is not a definition.
3458        // Skip the rest of this declarator, up until the comma or semicolon.
3459        SkipUntil(tok::comma, true);
3460        return;
3461      }
3462    }
3463  }
3464
3465  // Must have either 'enum name' or 'enum {...}'.
3466  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
3467      !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
3468    Diag(Tok, diag::err_expected_ident_lbrace);
3469
3470    // Skip the rest of this declarator, up until the comma or semicolon.
3471    SkipUntil(tok::comma, true);
3472    return;
3473  }
3474
3475  // If an identifier is present, consume and remember it.
3476  IdentifierInfo *Name = 0;
3477  SourceLocation NameLoc;
3478  if (Tok.is(tok::identifier)) {
3479    Name = Tok.getIdentifierInfo();
3480    NameLoc = ConsumeToken();
3481  }
3482
3483  if (!Name && ScopedEnumKWLoc.isValid()) {
3484    // C++0x 7.2p2: The optional identifier shall not be omitted in the
3485    // declaration of a scoped enumeration.
3486    Diag(Tok, diag::err_scoped_enum_missing_identifier);
3487    ScopedEnumKWLoc = SourceLocation();
3488    IsScopedUsingClassTag = false;
3489  }
3490
3491  // Okay, end the suppression area.  We'll decide whether to emit the
3492  // diagnostics in a second.
3493  if (shouldDelayDiagsInTag)
3494    diagsFromTag.done();
3495
3496  TypeResult BaseType;
3497
3498  // Parse the fixed underlying type.
3499  bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
3500  if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
3501    bool PossibleBitfield = false;
3502    if (CanBeBitfield) {
3503      // If we're in class scope, this can either be an enum declaration with
3504      // an underlying type, or a declaration of a bitfield member. We try to
3505      // use a simple disambiguation scheme first to catch the common cases
3506      // (integer literal, sizeof); if it's still ambiguous, we then consider
3507      // anything that's a simple-type-specifier followed by '(' as an
3508      // expression. This suffices because function types are not valid
3509      // underlying types anyway.
3510      EnterExpressionEvaluationContext Unevaluated(Actions,
3511                                                   Sema::ConstantEvaluated);
3512      TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
3513      // If the next token starts an expression, we know we're parsing a
3514      // bit-field. This is the common case.
3515      if (TPR == TPResult::True())
3516        PossibleBitfield = true;
3517      // If the next token starts a type-specifier-seq, it may be either a
3518      // a fixed underlying type or the start of a function-style cast in C++;
3519      // lookahead one more token to see if it's obvious that we have a
3520      // fixed underlying type.
3521      else if (TPR == TPResult::False() &&
3522               GetLookAheadToken(2).getKind() == tok::semi) {
3523        // Consume the ':'.
3524        ConsumeToken();
3525      } else {
3526        // We have the start of a type-specifier-seq, so we have to perform
3527        // tentative parsing to determine whether we have an expression or a
3528        // type.
3529        TentativeParsingAction TPA(*this);
3530
3531        // Consume the ':'.
3532        ConsumeToken();
3533
3534        // If we see a type specifier followed by an open-brace, we have an
3535        // ambiguity between an underlying type and a C++11 braced
3536        // function-style cast. Resolve this by always treating it as an
3537        // underlying type.
3538        // FIXME: The standard is not entirely clear on how to disambiguate in
3539        // this case.
3540        if ((getLangOpts().CPlusPlus &&
3541             isCXXDeclarationSpecifier(TPResult::True()) != TPResult::True()) ||
3542            (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
3543          // We'll parse this as a bitfield later.
3544          PossibleBitfield = true;
3545          TPA.Revert();
3546        } else {
3547          // We have a type-specifier-seq.
3548          TPA.Commit();
3549        }
3550      }
3551    } else {
3552      // Consume the ':'.
3553      ConsumeToken();
3554    }
3555
3556    if (!PossibleBitfield) {
3557      SourceRange Range;
3558      BaseType = ParseTypeName(&Range);
3559
3560      if (getLangOpts().CPlusPlus11) {
3561        Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
3562      } else if (!getLangOpts().ObjC2) {
3563        if (getLangOpts().CPlusPlus)
3564          Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
3565        else
3566          Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
3567      }
3568    }
3569  }
3570
3571  // There are four options here.  If we have 'friend enum foo;' then this is a
3572  // friend declaration, and cannot have an accompanying definition. If we have
3573  // 'enum foo;', then this is a forward declaration.  If we have
3574  // 'enum foo {...' then this is a definition. Otherwise we have something
3575  // like 'enum foo xyz', a reference.
3576  //
3577  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
3578  // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
3579  // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
3580  //
3581  Sema::TagUseKind TUK;
3582  if (!AllowDeclaration) {
3583    TUK = Sema::TUK_Reference;
3584  } else if (Tok.is(tok::l_brace)) {
3585    if (DS.isFriendSpecified()) {
3586      Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
3587        << SourceRange(DS.getFriendSpecLoc());
3588      ConsumeBrace();
3589      SkipUntil(tok::r_brace);
3590      TUK = Sema::TUK_Friend;
3591    } else {
3592      TUK = Sema::TUK_Definition;
3593    }
3594  } else if (DSC != DSC_type_specifier &&
3595             (Tok.is(tok::semi) ||
3596              (Tok.isAtStartOfLine() &&
3597               !isValidAfterTypeSpecifier(CanBeBitfield)))) {
3598    TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
3599    if (Tok.isNot(tok::semi)) {
3600      // A semicolon was missing after this declaration. Diagnose and recover.
3601      ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
3602                       "enum");
3603      PP.EnterToken(Tok);
3604      Tok.setKind(tok::semi);
3605    }
3606  } else {
3607    TUK = Sema::TUK_Reference;
3608  }
3609
3610  // If this is an elaborated type specifier, and we delayed
3611  // diagnostics before, just merge them into the current pool.
3612  if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
3613    diagsFromTag.redelay();
3614  }
3615
3616  MultiTemplateParamsArg TParams;
3617  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
3618      TUK != Sema::TUK_Reference) {
3619    if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
3620      // Skip the rest of this declarator, up until the comma or semicolon.
3621      Diag(Tok, diag::err_enum_template);
3622      SkipUntil(tok::comma, true);
3623      return;
3624    }
3625
3626    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
3627      // Enumerations can't be explicitly instantiated.
3628      DS.SetTypeSpecError();
3629      Diag(StartLoc, diag::err_explicit_instantiation_enum);
3630      return;
3631    }
3632
3633    assert(TemplateInfo.TemplateParams && "no template parameters");
3634    TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
3635                                     TemplateInfo.TemplateParams->size());
3636  }
3637
3638  if (TUK == Sema::TUK_Reference)
3639    ProhibitAttributes(attrs);
3640
3641  if (!Name && TUK != Sema::TUK_Definition) {
3642    Diag(Tok, diag::err_enumerator_unnamed_no_def);
3643
3644    // Skip the rest of this declarator, up until the comma or semicolon.
3645    SkipUntil(tok::comma, true);
3646    return;
3647  }
3648
3649  bool Owned = false;
3650  bool IsDependent = false;
3651  const char *PrevSpec = 0;
3652  unsigned DiagID;
3653  Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
3654                                   StartLoc, SS, Name, NameLoc, attrs.getList(),
3655                                   AS, DS.getModulePrivateSpecLoc(), TParams,
3656                                   Owned, IsDependent, ScopedEnumKWLoc,
3657                                   IsScopedUsingClassTag, BaseType);
3658
3659  if (IsDependent) {
3660    // This enum has a dependent nested-name-specifier. Handle it as a
3661    // dependent tag.
3662    if (!Name) {
3663      DS.SetTypeSpecError();
3664      Diag(Tok, diag::err_expected_type_name_after_typename);
3665      return;
3666    }
3667
3668    TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum,
3669                                                TUK, SS, Name, StartLoc,
3670                                                NameLoc);
3671    if (Type.isInvalid()) {
3672      DS.SetTypeSpecError();
3673      return;
3674    }
3675
3676    if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
3677                           NameLoc.isValid() ? NameLoc : StartLoc,
3678                           PrevSpec, DiagID, Type.get()))
3679      Diag(StartLoc, DiagID) << PrevSpec;
3680
3681    return;
3682  }
3683
3684  if (!TagDecl) {
3685    // The action failed to produce an enumeration tag. If this is a
3686    // definition, consume the entire definition.
3687    if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
3688      ConsumeBrace();
3689      SkipUntil(tok::r_brace);
3690    }
3691
3692    DS.SetTypeSpecError();
3693    return;
3694  }
3695
3696  if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference)
3697    ParseEnumBody(StartLoc, TagDecl);
3698
3699  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
3700                         NameLoc.isValid() ? NameLoc : StartLoc,
3701                         PrevSpec, DiagID, TagDecl, Owned))
3702    Diag(StartLoc, DiagID) << PrevSpec;
3703}
3704
3705/// ParseEnumBody - Parse a {} enclosed enumerator-list.
3706///       enumerator-list:
3707///         enumerator
3708///         enumerator-list ',' enumerator
3709///       enumerator:
3710///         enumeration-constant
3711///         enumeration-constant '=' constant-expression
3712///       enumeration-constant:
3713///         identifier
3714///
3715void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
3716  // Enter the scope of the enum body and start the definition.
3717  ParseScope EnumScope(this, Scope::DeclScope);
3718  Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
3719
3720  BalancedDelimiterTracker T(*this, tok::l_brace);
3721  T.consumeOpen();
3722
3723  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
3724  if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
3725    Diag(Tok, diag::error_empty_enum);
3726
3727  SmallVector<Decl *, 32> EnumConstantDecls;
3728
3729  Decl *LastEnumConstDecl = 0;
3730
3731  // Parse the enumerator-list.
3732  while (Tok.is(tok::identifier)) {
3733    IdentifierInfo *Ident = Tok.getIdentifierInfo();
3734    SourceLocation IdentLoc = ConsumeToken();
3735
3736    // If attributes exist after the enumerator, parse them.
3737    ParsedAttributesWithRange attrs(AttrFactory);
3738    MaybeParseGNUAttributes(attrs);
3739    MaybeParseCXX11Attributes(attrs);
3740    ProhibitAttributes(attrs);
3741
3742    SourceLocation EqualLoc;
3743    ExprResult AssignedVal;
3744    ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
3745
3746    if (Tok.is(tok::equal)) {
3747      EqualLoc = ConsumeToken();
3748      AssignedVal = ParseConstantExpression();
3749      if (AssignedVal.isInvalid())
3750        SkipUntil(tok::comma, tok::r_brace, true, true);
3751    }
3752
3753    // Install the enumerator constant into EnumDecl.
3754    Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
3755                                                    LastEnumConstDecl,
3756                                                    IdentLoc, Ident,
3757                                                    attrs.getList(), EqualLoc,
3758                                                    AssignedVal.release());
3759    PD.complete(EnumConstDecl);
3760
3761    EnumConstantDecls.push_back(EnumConstDecl);
3762    LastEnumConstDecl = EnumConstDecl;
3763
3764    if (Tok.is(tok::identifier)) {
3765      // We're missing a comma between enumerators.
3766      SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3767      Diag(Loc, diag::err_enumerator_list_missing_comma)
3768        << FixItHint::CreateInsertion(Loc, ", ");
3769      continue;
3770    }
3771
3772    if (Tok.isNot(tok::comma))
3773      break;
3774    SourceLocation CommaLoc = ConsumeToken();
3775
3776    if (Tok.isNot(tok::identifier)) {
3777      if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
3778        Diag(CommaLoc, getLangOpts().CPlusPlus ?
3779               diag::ext_enumerator_list_comma_cxx :
3780               diag::ext_enumerator_list_comma_c)
3781          << FixItHint::CreateRemoval(CommaLoc);
3782      else if (getLangOpts().CPlusPlus11)
3783        Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
3784          << FixItHint::CreateRemoval(CommaLoc);
3785    }
3786  }
3787
3788  // Eat the }.
3789  T.consumeClose();
3790
3791  // If attributes exist after the identifier list, parse them.
3792  ParsedAttributes attrs(AttrFactory);
3793  MaybeParseGNUAttributes(attrs);
3794
3795  Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(),
3796                        EnumDecl, EnumConstantDecls,
3797                        getCurScope(),
3798                        attrs.getList());
3799
3800  EnumScope.Exit();
3801  Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl,
3802                                   T.getCloseLocation());
3803
3804  // The next token must be valid after an enum definition. If not, a ';'
3805  // was probably forgotten.
3806  bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
3807  if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
3808    ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, "enum");
3809    // Push this token back into the preprocessor and change our current token
3810    // to ';' so that the rest of the code recovers as though there were an
3811    // ';' after the definition.
3812    PP.EnterToken(Tok);
3813    Tok.setKind(tok::semi);
3814  }
3815}
3816
3817/// isTypeSpecifierQualifier - Return true if the current token could be the
3818/// start of a type-qualifier-list.
3819bool Parser::isTypeQualifier() const {
3820  switch (Tok.getKind()) {
3821  default: return false;
3822
3823    // type-qualifier only in OpenCL
3824  case tok::kw_private:
3825    return getLangOpts().OpenCL;
3826
3827    // type-qualifier
3828  case tok::kw_const:
3829  case tok::kw_volatile:
3830  case tok::kw_restrict:
3831  case tok::kw___private:
3832  case tok::kw___local:
3833  case tok::kw___global:
3834  case tok::kw___constant:
3835  case tok::kw___read_only:
3836  case tok::kw___read_write:
3837  case tok::kw___write_only:
3838    return true;
3839  }
3840}
3841
3842/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
3843/// is definitely a type-specifier.  Return false if it isn't part of a type
3844/// specifier or if we're not sure.
3845bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
3846  switch (Tok.getKind()) {
3847  default: return false;
3848    // type-specifiers
3849  case tok::kw_short:
3850  case tok::kw_long:
3851  case tok::kw___int64:
3852  case tok::kw___int128:
3853  case tok::kw_signed:
3854  case tok::kw_unsigned:
3855  case tok::kw__Complex:
3856  case tok::kw__Imaginary:
3857  case tok::kw_void:
3858  case tok::kw_char:
3859  case tok::kw_wchar_t:
3860  case tok::kw_char16_t:
3861  case tok::kw_char32_t:
3862  case tok::kw_int:
3863  case tok::kw_half:
3864  case tok::kw_float:
3865  case tok::kw_double:
3866  case tok::kw_bool:
3867  case tok::kw__Bool:
3868  case tok::kw__Decimal32:
3869  case tok::kw__Decimal64:
3870  case tok::kw__Decimal128:
3871  case tok::kw___vector:
3872
3873    // OpenCL specific types:
3874  case tok::kw_image1d_t:
3875  case tok::kw_image1d_array_t:
3876  case tok::kw_image1d_buffer_t:
3877  case tok::kw_image2d_t:
3878  case tok::kw_image2d_array_t:
3879  case tok::kw_image3d_t:
3880  case tok::kw_sampler_t:
3881  case tok::kw_event_t:
3882
3883    // struct-or-union-specifier (C99) or class-specifier (C++)
3884  case tok::kw_class:
3885  case tok::kw_struct:
3886  case tok::kw___interface:
3887  case tok::kw_union:
3888    // enum-specifier
3889  case tok::kw_enum:
3890
3891    // typedef-name
3892  case tok::annot_typename:
3893    return true;
3894  }
3895}
3896
3897/// isTypeSpecifierQualifier - Return true if the current token could be the
3898/// start of a specifier-qualifier-list.
3899bool Parser::isTypeSpecifierQualifier() {
3900  switch (Tok.getKind()) {
3901  default: return false;
3902
3903  case tok::identifier:   // foo::bar
3904    if (TryAltiVecVectorToken())
3905      return true;
3906    // Fall through.
3907  case tok::kw_typename:  // typename T::type
3908    // Annotate typenames and C++ scope specifiers.  If we get one, just
3909    // recurse to handle whatever we get.
3910    if (TryAnnotateTypeOrScopeToken())
3911      return true;
3912    if (Tok.is(tok::identifier))
3913      return false;
3914    return isTypeSpecifierQualifier();
3915
3916  case tok::coloncolon:   // ::foo::bar
3917    if (NextToken().is(tok::kw_new) ||    // ::new
3918        NextToken().is(tok::kw_delete))   // ::delete
3919      return false;
3920
3921    if (TryAnnotateTypeOrScopeToken())
3922      return true;
3923    return isTypeSpecifierQualifier();
3924
3925    // GNU attributes support.
3926  case tok::kw___attribute:
3927    // GNU typeof support.
3928  case tok::kw_typeof:
3929
3930    // type-specifiers
3931  case tok::kw_short:
3932  case tok::kw_long:
3933  case tok::kw___int64:
3934  case tok::kw___int128:
3935  case tok::kw_signed:
3936  case tok::kw_unsigned:
3937  case tok::kw__Complex:
3938  case tok::kw__Imaginary:
3939  case tok::kw_void:
3940  case tok::kw_char:
3941  case tok::kw_wchar_t:
3942  case tok::kw_char16_t:
3943  case tok::kw_char32_t:
3944  case tok::kw_int:
3945  case tok::kw_half:
3946  case tok::kw_float:
3947  case tok::kw_double:
3948  case tok::kw_bool:
3949  case tok::kw__Bool:
3950  case tok::kw__Decimal32:
3951  case tok::kw__Decimal64:
3952  case tok::kw__Decimal128:
3953  case tok::kw___vector:
3954
3955    // OpenCL specific types:
3956  case tok::kw_image1d_t:
3957  case tok::kw_image1d_array_t:
3958  case tok::kw_image1d_buffer_t:
3959  case tok::kw_image2d_t:
3960  case tok::kw_image2d_array_t:
3961  case tok::kw_image3d_t:
3962  case tok::kw_sampler_t:
3963  case tok::kw_event_t:
3964
3965    // struct-or-union-specifier (C99) or class-specifier (C++)
3966  case tok::kw_class:
3967  case tok::kw_struct:
3968  case tok::kw___interface:
3969  case tok::kw_union:
3970    // enum-specifier
3971  case tok::kw_enum:
3972
3973    // type-qualifier
3974  case tok::kw_const:
3975  case tok::kw_volatile:
3976  case tok::kw_restrict:
3977
3978    // Debugger support.
3979  case tok::kw___unknown_anytype:
3980
3981    // typedef-name
3982  case tok::annot_typename:
3983    return true;
3984
3985    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
3986  case tok::less:
3987    return getLangOpts().ObjC1;
3988
3989  case tok::kw___cdecl:
3990  case tok::kw___stdcall:
3991  case tok::kw___fastcall:
3992  case tok::kw___thiscall:
3993  case tok::kw___w64:
3994  case tok::kw___ptr64:
3995  case tok::kw___ptr32:
3996  case tok::kw___pascal:
3997  case tok::kw___unaligned:
3998
3999  case tok::kw___private:
4000  case tok::kw___local:
4001  case tok::kw___global:
4002  case tok::kw___constant:
4003  case tok::kw___read_only:
4004  case tok::kw___read_write:
4005  case tok::kw___write_only:
4006
4007    return true;
4008
4009  case tok::kw_private:
4010    return getLangOpts().OpenCL;
4011
4012  // C11 _Atomic
4013  case tok::kw__Atomic:
4014    return true;
4015  }
4016}
4017
4018/// isDeclarationSpecifier() - Return true if the current token is part of a
4019/// declaration specifier.
4020///
4021/// \param DisambiguatingWithExpression True to indicate that the purpose of
4022/// this check is to disambiguate between an expression and a declaration.
4023bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4024  switch (Tok.getKind()) {
4025  default: return false;
4026
4027  case tok::kw_private:
4028    return getLangOpts().OpenCL;
4029
4030  case tok::identifier:   // foo::bar
4031    // Unfortunate hack to support "Class.factoryMethod" notation.
4032    if (getLangOpts().ObjC1 && NextToken().is(tok::period))
4033      return false;
4034    if (TryAltiVecVectorToken())
4035      return true;
4036    // Fall through.
4037  case tok::kw_decltype: // decltype(T())::type
4038  case tok::kw_typename: // typename T::type
4039    // Annotate typenames and C++ scope specifiers.  If we get one, just
4040    // recurse to handle whatever we get.
4041    if (TryAnnotateTypeOrScopeToken())
4042      return true;
4043    if (Tok.is(tok::identifier))
4044      return false;
4045
4046    // If we're in Objective-C and we have an Objective-C class type followed
4047    // by an identifier and then either ':' or ']', in a place where an
4048    // expression is permitted, then this is probably a class message send
4049    // missing the initial '['. In this case, we won't consider this to be
4050    // the start of a declaration.
4051    if (DisambiguatingWithExpression &&
4052        isStartOfObjCClassMessageMissingOpenBracket())
4053      return false;
4054
4055    return isDeclarationSpecifier();
4056
4057  case tok::coloncolon:   // ::foo::bar
4058    if (NextToken().is(tok::kw_new) ||    // ::new
4059        NextToken().is(tok::kw_delete))   // ::delete
4060      return false;
4061
4062    // Annotate typenames and C++ scope specifiers.  If we get one, just
4063    // recurse to handle whatever we get.
4064    if (TryAnnotateTypeOrScopeToken())
4065      return true;
4066    return isDeclarationSpecifier();
4067
4068    // storage-class-specifier
4069  case tok::kw_typedef:
4070  case tok::kw_extern:
4071  case tok::kw___private_extern__:
4072  case tok::kw_static:
4073  case tok::kw_auto:
4074  case tok::kw_register:
4075  case tok::kw___thread:
4076  case tok::kw_thread_local:
4077  case tok::kw__Thread_local:
4078
4079    // Modules
4080  case tok::kw___module_private__:
4081
4082    // Debugger support
4083  case tok::kw___unknown_anytype:
4084
4085    // type-specifiers
4086  case tok::kw_short:
4087  case tok::kw_long:
4088  case tok::kw___int64:
4089  case tok::kw___int128:
4090  case tok::kw_signed:
4091  case tok::kw_unsigned:
4092  case tok::kw__Complex:
4093  case tok::kw__Imaginary:
4094  case tok::kw_void:
4095  case tok::kw_char:
4096  case tok::kw_wchar_t:
4097  case tok::kw_char16_t:
4098  case tok::kw_char32_t:
4099
4100  case tok::kw_int:
4101  case tok::kw_half:
4102  case tok::kw_float:
4103  case tok::kw_double:
4104  case tok::kw_bool:
4105  case tok::kw__Bool:
4106  case tok::kw__Decimal32:
4107  case tok::kw__Decimal64:
4108  case tok::kw__Decimal128:
4109  case tok::kw___vector:
4110
4111    // OpenCL specific types:
4112  case tok::kw_image1d_t:
4113  case tok::kw_image1d_array_t:
4114  case tok::kw_image1d_buffer_t:
4115  case tok::kw_image2d_t:
4116  case tok::kw_image2d_array_t:
4117  case tok::kw_image3d_t:
4118  case tok::kw_sampler_t:
4119  case tok::kw_event_t:
4120
4121    // struct-or-union-specifier (C99) or class-specifier (C++)
4122  case tok::kw_class:
4123  case tok::kw_struct:
4124  case tok::kw_union:
4125  case tok::kw___interface:
4126    // enum-specifier
4127  case tok::kw_enum:
4128
4129    // type-qualifier
4130  case tok::kw_const:
4131  case tok::kw_volatile:
4132  case tok::kw_restrict:
4133
4134    // function-specifier
4135  case tok::kw_inline:
4136  case tok::kw_virtual:
4137  case tok::kw_explicit:
4138  case tok::kw__Noreturn:
4139
4140    // alignment-specifier
4141  case tok::kw__Alignas:
4142
4143    // friend keyword.
4144  case tok::kw_friend:
4145
4146    // static_assert-declaration
4147  case tok::kw__Static_assert:
4148
4149    // GNU typeof support.
4150  case tok::kw_typeof:
4151
4152    // GNU attributes.
4153  case tok::kw___attribute:
4154
4155    // C++11 decltype and constexpr.
4156  case tok::annot_decltype:
4157  case tok::kw_constexpr:
4158
4159    // C11 _Atomic
4160  case tok::kw__Atomic:
4161    return true;
4162
4163    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4164  case tok::less:
4165    return getLangOpts().ObjC1;
4166
4167    // typedef-name
4168  case tok::annot_typename:
4169    return !DisambiguatingWithExpression ||
4170           !isStartOfObjCClassMessageMissingOpenBracket();
4171
4172  case tok::kw___declspec:
4173  case tok::kw___cdecl:
4174  case tok::kw___stdcall:
4175  case tok::kw___fastcall:
4176  case tok::kw___thiscall:
4177  case tok::kw___w64:
4178  case tok::kw___sptr:
4179  case tok::kw___uptr:
4180  case tok::kw___ptr64:
4181  case tok::kw___ptr32:
4182  case tok::kw___forceinline:
4183  case tok::kw___pascal:
4184  case tok::kw___unaligned:
4185
4186  case tok::kw___private:
4187  case tok::kw___local:
4188  case tok::kw___global:
4189  case tok::kw___constant:
4190  case tok::kw___read_only:
4191  case tok::kw___read_write:
4192  case tok::kw___write_only:
4193
4194    return true;
4195  }
4196}
4197
4198bool Parser::isConstructorDeclarator() {
4199  TentativeParsingAction TPA(*this);
4200
4201  // Parse the C++ scope specifier.
4202  CXXScopeSpec SS;
4203  if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
4204                                     /*EnteringContext=*/true)) {
4205    TPA.Revert();
4206    return false;
4207  }
4208
4209  // Parse the constructor name.
4210  if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
4211    // We already know that we have a constructor name; just consume
4212    // the token.
4213    ConsumeToken();
4214  } else {
4215    TPA.Revert();
4216    return false;
4217  }
4218
4219  // Current class name must be followed by a left parenthesis.
4220  if (Tok.isNot(tok::l_paren)) {
4221    TPA.Revert();
4222    return false;
4223  }
4224  ConsumeParen();
4225
4226  // A right parenthesis, or ellipsis followed by a right parenthesis signals
4227  // that we have a constructor.
4228  if (Tok.is(tok::r_paren) ||
4229      (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
4230    TPA.Revert();
4231    return true;
4232  }
4233
4234  // If we need to, enter the specified scope.
4235  DeclaratorScopeObj DeclScopeObj(*this, SS);
4236  if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
4237    DeclScopeObj.EnterDeclaratorScope();
4238
4239  // Optionally skip Microsoft attributes.
4240  ParsedAttributes Attrs(AttrFactory);
4241  MaybeParseMicrosoftAttributes(Attrs);
4242
4243  // Check whether the next token(s) are part of a declaration
4244  // specifier, in which case we have the start of a parameter and,
4245  // therefore, we know that this is a constructor.
4246  bool IsConstructor = false;
4247  if (isDeclarationSpecifier())
4248    IsConstructor = true;
4249  else if (Tok.is(tok::identifier) ||
4250           (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
4251    // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
4252    // This might be a parenthesized member name, but is more likely to
4253    // be a constructor declaration with an invalid argument type. Keep
4254    // looking.
4255    if (Tok.is(tok::annot_cxxscope))
4256      ConsumeToken();
4257    ConsumeToken();
4258
4259    // If this is not a constructor, we must be parsing a declarator,
4260    // which must have one of the following syntactic forms (see the
4261    // grammar extract at the start of ParseDirectDeclarator):
4262    switch (Tok.getKind()) {
4263    case tok::l_paren:
4264      // C(X   (   int));
4265    case tok::l_square:
4266      // C(X   [   5]);
4267      // C(X   [   [attribute]]);
4268    case tok::coloncolon:
4269      // C(X   ::   Y);
4270      // C(X   ::   *p);
4271    case tok::r_paren:
4272      // C(X   )
4273      // Assume this isn't a constructor, rather than assuming it's a
4274      // constructor with an unnamed parameter of an ill-formed type.
4275      break;
4276
4277    default:
4278      IsConstructor = true;
4279      break;
4280    }
4281  }
4282
4283  TPA.Revert();
4284  return IsConstructor;
4285}
4286
4287/// ParseTypeQualifierListOpt
4288///          type-qualifier-list: [C99 6.7.5]
4289///            type-qualifier
4290/// [vendor]   attributes
4291///              [ only if VendorAttributesAllowed=true ]
4292///            type-qualifier-list type-qualifier
4293/// [vendor]   type-qualifier-list attributes
4294///              [ only if VendorAttributesAllowed=true ]
4295/// [C++0x]    attribute-specifier[opt] is allowed before cv-qualifier-seq
4296///              [ only if CXX11AttributesAllowed=true ]
4297/// Note: vendor can be GNU, MS, etc.
4298///
4299void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
4300                                       bool VendorAttributesAllowed,
4301                                       bool CXX11AttributesAllowed,
4302                                       bool AtomicAllowed) {
4303  if (getLangOpts().CPlusPlus11 && CXX11AttributesAllowed &&
4304      isCXX11AttributeSpecifier()) {
4305    ParsedAttributesWithRange attrs(AttrFactory);
4306    ParseCXX11Attributes(attrs);
4307    DS.takeAttributesFrom(attrs);
4308  }
4309
4310  SourceLocation EndLoc;
4311
4312  while (1) {
4313    bool isInvalid = false;
4314    const char *PrevSpec = 0;
4315    unsigned DiagID = 0;
4316    SourceLocation Loc = Tok.getLocation();
4317
4318    switch (Tok.getKind()) {
4319    case tok::code_completion:
4320      Actions.CodeCompleteTypeQualifiers(DS);
4321      return cutOffParsing();
4322
4323    case tok::kw_const:
4324      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec, DiagID,
4325                                 getLangOpts());
4326      break;
4327    case tok::kw_volatile:
4328      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4329                                 getLangOpts());
4330      break;
4331    case tok::kw_restrict:
4332      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4333                                 getLangOpts());
4334      break;
4335    case tok::kw__Atomic:
4336      if (!AtomicAllowed)
4337        goto DoneWithTypeQuals;
4338      isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4339                                 getLangOpts());
4340      break;
4341
4342    // OpenCL qualifiers:
4343    case tok::kw_private:
4344      if (!getLangOpts().OpenCL)
4345        goto DoneWithTypeQuals;
4346    case tok::kw___private:
4347    case tok::kw___global:
4348    case tok::kw___local:
4349    case tok::kw___constant:
4350    case tok::kw___read_only:
4351    case tok::kw___write_only:
4352    case tok::kw___read_write:
4353      ParseOpenCLQualifiers(DS);
4354      break;
4355
4356    case tok::kw___sptr:
4357    case tok::kw___uptr:
4358    case tok::kw___w64:
4359    case tok::kw___ptr64:
4360    case tok::kw___ptr32:
4361    case tok::kw___cdecl:
4362    case tok::kw___stdcall:
4363    case tok::kw___fastcall:
4364    case tok::kw___thiscall:
4365    case tok::kw___unaligned:
4366      if (VendorAttributesAllowed) {
4367        ParseMicrosoftTypeAttributes(DS.getAttributes());
4368        continue;
4369      }
4370      goto DoneWithTypeQuals;
4371    case tok::kw___pascal:
4372      if (VendorAttributesAllowed) {
4373        ParseBorlandTypeAttributes(DS.getAttributes());
4374        continue;
4375      }
4376      goto DoneWithTypeQuals;
4377    case tok::kw___attribute:
4378      if (VendorAttributesAllowed) {
4379        ParseGNUAttributes(DS.getAttributes());
4380        continue; // do *not* consume the next token!
4381      }
4382      // otherwise, FALL THROUGH!
4383    default:
4384      DoneWithTypeQuals:
4385      // If this is not a type-qualifier token, we're done reading type
4386      // qualifiers.  First verify that DeclSpec's are consistent.
4387      DS.Finish(Diags, PP);
4388      if (EndLoc.isValid())
4389        DS.SetRangeEnd(EndLoc);
4390      return;
4391    }
4392
4393    // If the specifier combination wasn't legal, issue a diagnostic.
4394    if (isInvalid) {
4395      assert(PrevSpec && "Method did not return previous specifier!");
4396      Diag(Tok, DiagID) << PrevSpec;
4397    }
4398    EndLoc = ConsumeToken();
4399  }
4400}
4401
4402
4403/// ParseDeclarator - Parse and verify a newly-initialized declarator.
4404///
4405void Parser::ParseDeclarator(Declarator &D) {
4406  /// This implements the 'declarator' production in the C grammar, then checks
4407  /// for well-formedness and issues diagnostics.
4408  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
4409}
4410
4411static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang) {
4412  if (Kind == tok::star || Kind == tok::caret)
4413    return true;
4414
4415  // We parse rvalue refs in C++03, because otherwise the errors are scary.
4416  if (!Lang.CPlusPlus)
4417    return false;
4418
4419  return Kind == tok::amp || Kind == tok::ampamp;
4420}
4421
4422/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
4423/// is parsed by the function passed to it. Pass null, and the direct-declarator
4424/// isn't parsed at all, making this function effectively parse the C++
4425/// ptr-operator production.
4426///
4427/// If the grammar of this construct is extended, matching changes must also be
4428/// made to TryParseDeclarator and MightBeDeclarator, and possibly to
4429/// isConstructorDeclarator.
4430///
4431///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
4432/// [C]     pointer[opt] direct-declarator
4433/// [C++]   direct-declarator
4434/// [C++]   ptr-operator declarator
4435///
4436///       pointer: [C99 6.7.5]
4437///         '*' type-qualifier-list[opt]
4438///         '*' type-qualifier-list[opt] pointer
4439///
4440///       ptr-operator:
4441///         '*' cv-qualifier-seq[opt]
4442///         '&'
4443/// [C++0x] '&&'
4444/// [GNU]   '&' restrict[opt] attributes[opt]
4445/// [GNU?]  '&&' restrict[opt] attributes[opt]
4446///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
4447void Parser::ParseDeclaratorInternal(Declarator &D,
4448                                     DirectDeclParseFunction DirectDeclParser) {
4449  if (Diags.hasAllExtensionsSilenced())
4450    D.setExtension();
4451
4452  // C++ member pointers start with a '::' or a nested-name.
4453  // Member pointers get special handling, since there's no place for the
4454  // scope spec in the generic path below.
4455  if (getLangOpts().CPlusPlus &&
4456      (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
4457       Tok.is(tok::annot_cxxscope))) {
4458    bool EnteringContext = D.getContext() == Declarator::FileContext ||
4459                           D.getContext() == Declarator::MemberContext;
4460    CXXScopeSpec SS;
4461    ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext);
4462
4463    if (SS.isNotEmpty()) {
4464      if (Tok.isNot(tok::star)) {
4465        // The scope spec really belongs to the direct-declarator.
4466        if (D.mayHaveIdentifier())
4467          D.getCXXScopeSpec() = SS;
4468        else
4469          AnnotateScopeToken(SS, true);
4470
4471        if (DirectDeclParser)
4472          (this->*DirectDeclParser)(D);
4473        return;
4474      }
4475
4476      SourceLocation Loc = ConsumeToken();
4477      D.SetRangeEnd(Loc);
4478      DeclSpec DS(AttrFactory);
4479      ParseTypeQualifierListOpt(DS);
4480      D.ExtendWithDeclSpec(DS);
4481
4482      // Recurse to parse whatever is left.
4483      ParseDeclaratorInternal(D, DirectDeclParser);
4484
4485      // Sema will have to catch (syntactically invalid) pointers into global
4486      // scope. It has to catch pointers into namespace scope anyway.
4487      D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
4488                                                      Loc),
4489                    DS.getAttributes(),
4490                    /* Don't replace range end. */SourceLocation());
4491      return;
4492    }
4493  }
4494
4495  tok::TokenKind Kind = Tok.getKind();
4496  // Not a pointer, C++ reference, or block.
4497  if (!isPtrOperatorToken(Kind, getLangOpts())) {
4498    if (DirectDeclParser)
4499      (this->*DirectDeclParser)(D);
4500    return;
4501  }
4502
4503  // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
4504  // '&&' -> rvalue reference
4505  SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
4506  D.SetRangeEnd(Loc);
4507
4508  if (Kind == tok::star || Kind == tok::caret) {
4509    // Is a pointer.
4510    DeclSpec DS(AttrFactory);
4511
4512    // FIXME: GNU attributes are not allowed here in a new-type-id.
4513    ParseTypeQualifierListOpt(DS);
4514    D.ExtendWithDeclSpec(DS);
4515
4516    // Recursively parse the declarator.
4517    ParseDeclaratorInternal(D, DirectDeclParser);
4518    if (Kind == tok::star)
4519      // Remember that we parsed a pointer type, and remember the type-quals.
4520      D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
4521                                                DS.getConstSpecLoc(),
4522                                                DS.getVolatileSpecLoc(),
4523                                                DS.getRestrictSpecLoc()),
4524                    DS.getAttributes(),
4525                    SourceLocation());
4526    else
4527      // Remember that we parsed a Block type, and remember the type-quals.
4528      D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
4529                                                     Loc),
4530                    DS.getAttributes(),
4531                    SourceLocation());
4532  } else {
4533    // Is a reference
4534    DeclSpec DS(AttrFactory);
4535
4536    // Complain about rvalue references in C++03, but then go on and build
4537    // the declarator.
4538    if (Kind == tok::ampamp)
4539      Diag(Loc, getLangOpts().CPlusPlus11 ?
4540           diag::warn_cxx98_compat_rvalue_reference :
4541           diag::ext_rvalue_reference);
4542
4543    // GNU-style and C++11 attributes are allowed here, as is restrict.
4544    ParseTypeQualifierListOpt(DS);
4545    D.ExtendWithDeclSpec(DS);
4546
4547    // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
4548    // cv-qualifiers are introduced through the use of a typedef or of a
4549    // template type argument, in which case the cv-qualifiers are ignored.
4550    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
4551      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4552        Diag(DS.getConstSpecLoc(),
4553             diag::err_invalid_reference_qualifier_application) << "const";
4554      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4555        Diag(DS.getVolatileSpecLoc(),
4556             diag::err_invalid_reference_qualifier_application) << "volatile";
4557      // 'restrict' is permitted as an extension.
4558      if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4559        Diag(DS.getAtomicSpecLoc(),
4560             diag::err_invalid_reference_qualifier_application) << "_Atomic";
4561    }
4562
4563    // Recursively parse the declarator.
4564    ParseDeclaratorInternal(D, DirectDeclParser);
4565
4566    if (D.getNumTypeObjects() > 0) {
4567      // C++ [dcl.ref]p4: There shall be no references to references.
4568      DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
4569      if (InnerChunk.Kind == DeclaratorChunk::Reference) {
4570        if (const IdentifierInfo *II = D.getIdentifier())
4571          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
4572           << II;
4573        else
4574          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
4575            << "type name";
4576
4577        // Once we've complained about the reference-to-reference, we
4578        // can go ahead and build the (technically ill-formed)
4579        // declarator: reference collapsing will take care of it.
4580      }
4581    }
4582
4583    // Remember that we parsed a reference type.
4584    D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
4585                                                Kind == tok::amp),
4586                  DS.getAttributes(),
4587                  SourceLocation());
4588  }
4589}
4590
4591static void diagnoseMisplacedEllipsis(Parser &P, Declarator &D,
4592                                      SourceLocation EllipsisLoc) {
4593  if (EllipsisLoc.isValid()) {
4594    FixItHint Insertion;
4595    if (!D.getEllipsisLoc().isValid()) {
4596      Insertion = FixItHint::CreateInsertion(D.getIdentifierLoc(), "...");
4597      D.setEllipsisLoc(EllipsisLoc);
4598    }
4599    P.Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
4600      << FixItHint::CreateRemoval(EllipsisLoc) << Insertion << !D.hasName();
4601  }
4602}
4603
4604/// ParseDirectDeclarator
4605///       direct-declarator: [C99 6.7.5]
4606/// [C99]   identifier
4607///         '(' declarator ')'
4608/// [GNU]   '(' attributes declarator ')'
4609/// [C90]   direct-declarator '[' constant-expression[opt] ']'
4610/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
4611/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
4612/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
4613/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
4614/// [C++11] direct-declarator '[' constant-expression[opt] ']'
4615///                    attribute-specifier-seq[opt]
4616///         direct-declarator '(' parameter-type-list ')'
4617///         direct-declarator '(' identifier-list[opt] ')'
4618/// [GNU]   direct-declarator '(' parameter-forward-declarations
4619///                    parameter-type-list[opt] ')'
4620/// [C++]   direct-declarator '(' parameter-declaration-clause ')'
4621///                    cv-qualifier-seq[opt] exception-specification[opt]
4622/// [C++11] direct-declarator '(' parameter-declaration-clause ')'
4623///                    attribute-specifier-seq[opt] cv-qualifier-seq[opt]
4624///                    ref-qualifier[opt] exception-specification[opt]
4625/// [C++]   declarator-id
4626/// [C++11] declarator-id attribute-specifier-seq[opt]
4627///
4628///       declarator-id: [C++ 8]
4629///         '...'[opt] id-expression
4630///         '::'[opt] nested-name-specifier[opt] type-name
4631///
4632///       id-expression: [C++ 5.1]
4633///         unqualified-id
4634///         qualified-id
4635///
4636///       unqualified-id: [C++ 5.1]
4637///         identifier
4638///         operator-function-id
4639///         conversion-function-id
4640///          '~' class-name
4641///         template-id
4642///
4643/// Note, any additional constructs added here may need corresponding changes
4644/// in isConstructorDeclarator.
4645void Parser::ParseDirectDeclarator(Declarator &D) {
4646  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
4647
4648  if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
4649    // ParseDeclaratorInternal might already have parsed the scope.
4650    if (D.getCXXScopeSpec().isEmpty()) {
4651      bool EnteringContext = D.getContext() == Declarator::FileContext ||
4652                             D.getContext() == Declarator::MemberContext;
4653      ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(),
4654                                     EnteringContext);
4655    }
4656
4657    if (D.getCXXScopeSpec().isValid()) {
4658      if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
4659        // Change the declaration context for name lookup, until this function
4660        // is exited (and the declarator has been parsed).
4661        DeclScopeObj.EnterDeclaratorScope();
4662    }
4663
4664    // C++0x [dcl.fct]p14:
4665    //   There is a syntactic ambiguity when an ellipsis occurs at the end
4666    //   of a parameter-declaration-clause without a preceding comma. In
4667    //   this case, the ellipsis is parsed as part of the
4668    //   abstract-declarator if the type of the parameter names a template
4669    //   parameter pack that has not been expanded; otherwise, it is parsed
4670    //   as part of the parameter-declaration-clause.
4671    if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
4672        !((D.getContext() == Declarator::PrototypeContext ||
4673           D.getContext() == Declarator::BlockLiteralContext) &&
4674          NextToken().is(tok::r_paren) &&
4675          !D.hasGroupingParens() &&
4676          !Actions.containsUnexpandedParameterPacks(D))) {
4677      SourceLocation EllipsisLoc = ConsumeToken();
4678      if (isPtrOperatorToken(Tok.getKind(), getLangOpts())) {
4679        // The ellipsis was put in the wrong place. Recover, and explain to
4680        // the user what they should have done.
4681        ParseDeclarator(D);
4682        diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
4683        return;
4684      } else
4685        D.setEllipsisLoc(EllipsisLoc);
4686
4687      // The ellipsis can't be followed by a parenthesized declarator. We
4688      // check for that in ParseParenDeclarator, after we have disambiguated
4689      // the l_paren token.
4690    }
4691
4692    if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
4693        Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
4694      // We found something that indicates the start of an unqualified-id.
4695      // Parse that unqualified-id.
4696      bool AllowConstructorName;
4697      if (D.getDeclSpec().hasTypeSpecifier())
4698        AllowConstructorName = false;
4699      else if (D.getCXXScopeSpec().isSet())
4700        AllowConstructorName =
4701          (D.getContext() == Declarator::FileContext ||
4702           D.getContext() == Declarator::MemberContext);
4703      else
4704        AllowConstructorName = (D.getContext() == Declarator::MemberContext);
4705
4706      SourceLocation TemplateKWLoc;
4707      if (ParseUnqualifiedId(D.getCXXScopeSpec(),
4708                             /*EnteringContext=*/true,
4709                             /*AllowDestructorName=*/true,
4710                             AllowConstructorName,
4711                             ParsedType(),
4712                             TemplateKWLoc,
4713                             D.getName()) ||
4714          // Once we're past the identifier, if the scope was bad, mark the
4715          // whole declarator bad.
4716          D.getCXXScopeSpec().isInvalid()) {
4717        D.SetIdentifier(0, Tok.getLocation());
4718        D.setInvalidType(true);
4719      } else {
4720        // Parsed the unqualified-id; update range information and move along.
4721        if (D.getSourceRange().getBegin().isInvalid())
4722          D.SetRangeBegin(D.getName().getSourceRange().getBegin());
4723        D.SetRangeEnd(D.getName().getSourceRange().getEnd());
4724      }
4725      goto PastIdentifier;
4726    }
4727  } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
4728    assert(!getLangOpts().CPlusPlus &&
4729           "There's a C++-specific check for tok::identifier above");
4730    assert(Tok.getIdentifierInfo() && "Not an identifier?");
4731    D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
4732    ConsumeToken();
4733    goto PastIdentifier;
4734  } else if (Tok.is(tok::identifier) && D.diagnoseIdentifier()) {
4735    Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
4736      << FixItHint::CreateRemoval(Tok.getLocation());
4737    D.SetIdentifier(0, Tok.getLocation());
4738    ConsumeToken();
4739    goto PastIdentifier;
4740  }
4741
4742  if (Tok.is(tok::l_paren)) {
4743    // direct-declarator: '(' declarator ')'
4744    // direct-declarator: '(' attributes declarator ')'
4745    // Example: 'char (*X)'   or 'int (*XX)(void)'
4746    ParseParenDeclarator(D);
4747
4748    // If the declarator was parenthesized, we entered the declarator
4749    // scope when parsing the parenthesized declarator, then exited
4750    // the scope already. Re-enter the scope, if we need to.
4751    if (D.getCXXScopeSpec().isSet()) {
4752      // If there was an error parsing parenthesized declarator, declarator
4753      // scope may have been entered before. Don't do it again.
4754      if (!D.isInvalidType() &&
4755          Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
4756        // Change the declaration context for name lookup, until this function
4757        // is exited (and the declarator has been parsed).
4758        DeclScopeObj.EnterDeclaratorScope();
4759    }
4760  } else if (D.mayOmitIdentifier()) {
4761    // This could be something simple like "int" (in which case the declarator
4762    // portion is empty), if an abstract-declarator is allowed.
4763    D.SetIdentifier(0, Tok.getLocation());
4764
4765    // The grammar for abstract-pack-declarator does not allow grouping parens.
4766    // FIXME: Revisit this once core issue 1488 is resolved.
4767    if (D.hasEllipsis() && D.hasGroupingParens())
4768      Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
4769           diag::ext_abstract_pack_declarator_parens);
4770  } else {
4771    if (Tok.getKind() == tok::annot_pragma_parser_crash)
4772      LLVM_BUILTIN_TRAP;
4773    if (D.getContext() == Declarator::MemberContext)
4774      Diag(Tok, diag::err_expected_member_name_or_semi)
4775        << D.getDeclSpec().getSourceRange();
4776    else if (getLangOpts().CPlusPlus) {
4777      if (Tok.is(tok::period) || Tok.is(tok::arrow))
4778        Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
4779      else
4780        Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus;
4781    } else
4782      Diag(Tok, diag::err_expected_ident_lparen);
4783    D.SetIdentifier(0, Tok.getLocation());
4784    D.setInvalidType(true);
4785  }
4786
4787 PastIdentifier:
4788  assert(D.isPastIdentifier() &&
4789         "Haven't past the location of the identifier yet?");
4790
4791  // Don't parse attributes unless we have parsed an unparenthesized name.
4792  if (D.hasName() && !D.getNumTypeObjects())
4793    MaybeParseCXX11Attributes(D);
4794
4795  while (1) {
4796    if (Tok.is(tok::l_paren)) {
4797      // Enter function-declaration scope, limiting any declarators to the
4798      // function prototype scope, including parameter declarators.
4799      ParseScope PrototypeScope(this,
4800                                Scope::FunctionPrototypeScope|Scope::DeclScope|
4801                                (D.isFunctionDeclaratorAFunctionDeclaration()
4802                                   ? Scope::FunctionDeclarationScope : 0));
4803
4804      // The paren may be part of a C++ direct initializer, eg. "int x(1);".
4805      // In such a case, check if we actually have a function declarator; if it
4806      // is not, the declarator has been fully parsed.
4807      bool IsAmbiguous = false;
4808      if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
4809        // The name of the declarator, if any, is tentatively declared within
4810        // a possible direct initializer.
4811        TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
4812        bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
4813        TentativelyDeclaredIdentifiers.pop_back();
4814        if (!IsFunctionDecl)
4815          break;
4816      }
4817      ParsedAttributes attrs(AttrFactory);
4818      BalancedDelimiterTracker T(*this, tok::l_paren);
4819      T.consumeOpen();
4820      ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
4821      PrototypeScope.Exit();
4822    } else if (Tok.is(tok::l_square)) {
4823      ParseBracketDeclarator(D);
4824    } else {
4825      break;
4826    }
4827  }
4828}
4829
4830/// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
4831/// only called before the identifier, so these are most likely just grouping
4832/// parens for precedence.  If we find that these are actually function
4833/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
4834///
4835///       direct-declarator:
4836///         '(' declarator ')'
4837/// [GNU]   '(' attributes declarator ')'
4838///         direct-declarator '(' parameter-type-list ')'
4839///         direct-declarator '(' identifier-list[opt] ')'
4840/// [GNU]   direct-declarator '(' parameter-forward-declarations
4841///                    parameter-type-list[opt] ')'
4842///
4843void Parser::ParseParenDeclarator(Declarator &D) {
4844  BalancedDelimiterTracker T(*this, tok::l_paren);
4845  T.consumeOpen();
4846
4847  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
4848
4849  // Eat any attributes before we look at whether this is a grouping or function
4850  // declarator paren.  If this is a grouping paren, the attribute applies to
4851  // the type being built up, for example:
4852  //     int (__attribute__(()) *x)(long y)
4853  // If this ends up not being a grouping paren, the attribute applies to the
4854  // first argument, for example:
4855  //     int (__attribute__(()) int x)
4856  // In either case, we need to eat any attributes to be able to determine what
4857  // sort of paren this is.
4858  //
4859  ParsedAttributes attrs(AttrFactory);
4860  bool RequiresArg = false;
4861  if (Tok.is(tok::kw___attribute)) {
4862    ParseGNUAttributes(attrs);
4863
4864    // We require that the argument list (if this is a non-grouping paren) be
4865    // present even if the attribute list was empty.
4866    RequiresArg = true;
4867  }
4868
4869  // Eat any Microsoft extensions.
4870  ParseMicrosoftTypeAttributes(attrs);
4871
4872  // Eat any Borland extensions.
4873  if  (Tok.is(tok::kw___pascal))
4874    ParseBorlandTypeAttributes(attrs);
4875
4876  // If we haven't past the identifier yet (or where the identifier would be
4877  // stored, if this is an abstract declarator), then this is probably just
4878  // grouping parens. However, if this could be an abstract-declarator, then
4879  // this could also be the start of function arguments (consider 'void()').
4880  bool isGrouping;
4881
4882  if (!D.mayOmitIdentifier()) {
4883    // If this can't be an abstract-declarator, this *must* be a grouping
4884    // paren, because we haven't seen the identifier yet.
4885    isGrouping = true;
4886  } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
4887             (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
4888              NextToken().is(tok::r_paren)) || // C++ int(...)
4889             isDeclarationSpecifier() ||       // 'int(int)' is a function.
4890             isCXX11AttributeSpecifier()) {    // 'int([[]]int)' is a function.
4891    // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
4892    // considered to be a type, not a K&R identifier-list.
4893    isGrouping = false;
4894  } else {
4895    // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
4896    isGrouping = true;
4897  }
4898
4899  // If this is a grouping paren, handle:
4900  // direct-declarator: '(' declarator ')'
4901  // direct-declarator: '(' attributes declarator ')'
4902  if (isGrouping) {
4903    SourceLocation EllipsisLoc = D.getEllipsisLoc();
4904    D.setEllipsisLoc(SourceLocation());
4905
4906    bool hadGroupingParens = D.hasGroupingParens();
4907    D.setGroupingParens(true);
4908    ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
4909    // Match the ')'.
4910    T.consumeClose();
4911    D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
4912                                            T.getCloseLocation()),
4913                  attrs, T.getCloseLocation());
4914
4915    D.setGroupingParens(hadGroupingParens);
4916
4917    // An ellipsis cannot be placed outside parentheses.
4918    if (EllipsisLoc.isValid())
4919      diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
4920
4921    return;
4922  }
4923
4924  // Okay, if this wasn't a grouping paren, it must be the start of a function
4925  // argument list.  Recognize that this declarator will never have an
4926  // identifier (and remember where it would have been), then call into
4927  // ParseFunctionDeclarator to handle of argument list.
4928  D.SetIdentifier(0, Tok.getLocation());
4929
4930  // Enter function-declaration scope, limiting any declarators to the
4931  // function prototype scope, including parameter declarators.
4932  ParseScope PrototypeScope(this,
4933                            Scope::FunctionPrototypeScope | Scope::DeclScope |
4934                            (D.isFunctionDeclaratorAFunctionDeclaration()
4935                               ? Scope::FunctionDeclarationScope : 0));
4936  ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
4937  PrototypeScope.Exit();
4938}
4939
4940/// ParseFunctionDeclarator - We are after the identifier and have parsed the
4941/// declarator D up to a paren, which indicates that we are parsing function
4942/// arguments.
4943///
4944/// If FirstArgAttrs is non-null, then the caller parsed those arguments
4945/// immediately after the open paren - they should be considered to be the
4946/// first argument of a parameter.
4947///
4948/// If RequiresArg is true, then the first argument of the function is required
4949/// to be present and required to not be an identifier list.
4950///
4951/// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
4952/// (C++11) ref-qualifier[opt], exception-specification[opt],
4953/// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
4954///
4955/// [C++11] exception-specification:
4956///           dynamic-exception-specification
4957///           noexcept-specification
4958///
4959void Parser::ParseFunctionDeclarator(Declarator &D,
4960                                     ParsedAttributes &FirstArgAttrs,
4961                                     BalancedDelimiterTracker &Tracker,
4962                                     bool IsAmbiguous,
4963                                     bool RequiresArg) {
4964  assert(getCurScope()->isFunctionPrototypeScope() &&
4965         "Should call from a Function scope");
4966  // lparen is already consumed!
4967  assert(D.isPastIdentifier() && "Should not call before identifier!");
4968
4969  // This should be true when the function has typed arguments.
4970  // Otherwise, it is treated as a K&R-style function.
4971  bool HasProto = false;
4972  // Build up an array of information about the parsed arguments.
4973  SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
4974  // Remember where we see an ellipsis, if any.
4975  SourceLocation EllipsisLoc;
4976
4977  DeclSpec DS(AttrFactory);
4978  bool RefQualifierIsLValueRef = true;
4979  SourceLocation RefQualifierLoc;
4980  SourceLocation ConstQualifierLoc;
4981  SourceLocation VolatileQualifierLoc;
4982  ExceptionSpecificationType ESpecType = EST_None;
4983  SourceRange ESpecRange;
4984  SmallVector<ParsedType, 2> DynamicExceptions;
4985  SmallVector<SourceRange, 2> DynamicExceptionRanges;
4986  ExprResult NoexceptExpr;
4987  ParsedAttributes FnAttrs(AttrFactory);
4988  TypeResult TrailingReturnType;
4989
4990  Actions.ActOnStartFunctionDeclarator();
4991
4992  /* LocalEndLoc is the end location for the local FunctionTypeLoc.
4993     EndLoc is the end location for the function declarator.
4994     They differ for trailing return types. */
4995  SourceLocation StartLoc, LocalEndLoc, EndLoc;
4996  SourceLocation LParenLoc, RParenLoc;
4997  LParenLoc = Tracker.getOpenLocation();
4998  StartLoc = LParenLoc;
4999
5000  if (isFunctionDeclaratorIdentifierList()) {
5001    if (RequiresArg)
5002      Diag(Tok, diag::err_argument_required_after_attribute);
5003
5004    ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
5005
5006    Tracker.consumeClose();
5007    RParenLoc = Tracker.getCloseLocation();
5008    LocalEndLoc = RParenLoc;
5009    EndLoc = RParenLoc;
5010  } else {
5011    if (Tok.isNot(tok::r_paren))
5012      ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc);
5013    else if (RequiresArg)
5014      Diag(Tok, diag::err_argument_required_after_attribute);
5015
5016    HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
5017
5018    // If we have the closing ')', eat it.
5019    Tracker.consumeClose();
5020    RParenLoc = Tracker.getCloseLocation();
5021    LocalEndLoc = RParenLoc;
5022    EndLoc = RParenLoc;
5023
5024    if (getLangOpts().CPlusPlus) {
5025      // FIXME: Accept these components in any order, and produce fixits to
5026      // correct the order if the user gets it wrong. Ideally we should deal
5027      // with the virt-specifier-seq and pure-specifier in the same way.
5028
5029      // Parse cv-qualifier-seq[opt].
5030      ParseTypeQualifierListOpt(DS, /*VendorAttributesAllowed*/ false,
5031                                /*CXX11AttributesAllowed*/ false,
5032                                /*AtomicAllowed*/ false);
5033      if (!DS.getSourceRange().getEnd().isInvalid()) {
5034        EndLoc = DS.getSourceRange().getEnd();
5035        ConstQualifierLoc = DS.getConstSpecLoc();
5036        VolatileQualifierLoc = DS.getVolatileSpecLoc();
5037      }
5038
5039      // Parse ref-qualifier[opt].
5040      if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
5041        Diag(Tok, getLangOpts().CPlusPlus11 ?
5042             diag::warn_cxx98_compat_ref_qualifier :
5043             diag::ext_ref_qualifier);
5044
5045        RefQualifierIsLValueRef = Tok.is(tok::amp);
5046        RefQualifierLoc = ConsumeToken();
5047        EndLoc = RefQualifierLoc;
5048      }
5049
5050      // C++11 [expr.prim.general]p3:
5051      //   If a declaration declares a member function or member function
5052      //   template of a class X, the expression this is a prvalue of type
5053      //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5054      //   and the end of the function-definition, member-declarator, or
5055      //   declarator.
5056      // FIXME: currently, "static" case isn't handled correctly.
5057      bool IsCXX11MemberFunction =
5058        getLangOpts().CPlusPlus11 &&
5059        (D.getContext() == Declarator::MemberContext
5060         ? !D.getDeclSpec().isFriendSpecified()
5061         : D.getContext() == Declarator::FileContext &&
5062           D.getCXXScopeSpec().isValid() &&
5063           Actions.CurContext->isRecord());
5064      Sema::CXXThisScopeRAII ThisScope(Actions,
5065                               dyn_cast<CXXRecordDecl>(Actions.CurContext),
5066                               DS.getTypeQualifiers() |
5067                               (D.getDeclSpec().isConstexprSpecified() &&
5068                                !getLangOpts().CPlusPlus1y
5069                                  ? Qualifiers::Const : 0),
5070                               IsCXX11MemberFunction);
5071
5072      // Parse exception-specification[opt].
5073      ESpecType = tryParseExceptionSpecification(ESpecRange,
5074                                                 DynamicExceptions,
5075                                                 DynamicExceptionRanges,
5076                                                 NoexceptExpr);
5077      if (ESpecType != EST_None)
5078        EndLoc = ESpecRange.getEnd();
5079
5080      // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
5081      // after the exception-specification.
5082      MaybeParseCXX11Attributes(FnAttrs);
5083
5084      // Parse trailing-return-type[opt].
5085      LocalEndLoc = EndLoc;
5086      if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
5087        Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
5088        if (D.getDeclSpec().getTypeSpecType() == TST_auto)
5089          StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5090        LocalEndLoc = Tok.getLocation();
5091        SourceRange Range;
5092        TrailingReturnType = ParseTrailingReturnType(Range);
5093        EndLoc = Range.getEnd();
5094      }
5095    }
5096  }
5097
5098  // Remember that we parsed a function type, and remember the attributes.
5099  D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
5100                                             IsAmbiguous,
5101                                             LParenLoc,
5102                                             ParamInfo.data(), ParamInfo.size(),
5103                                             EllipsisLoc, RParenLoc,
5104                                             DS.getTypeQualifiers(),
5105                                             RefQualifierIsLValueRef,
5106                                             RefQualifierLoc, ConstQualifierLoc,
5107                                             VolatileQualifierLoc,
5108                                             /*MutableLoc=*/SourceLocation(),
5109                                             ESpecType, ESpecRange.getBegin(),
5110                                             DynamicExceptions.data(),
5111                                             DynamicExceptionRanges.data(),
5112                                             DynamicExceptions.size(),
5113                                             NoexceptExpr.isUsable() ?
5114                                               NoexceptExpr.get() : 0,
5115                                             StartLoc, LocalEndLoc, D,
5116                                             TrailingReturnType),
5117                FnAttrs, EndLoc);
5118
5119  Actions.ActOnEndFunctionDeclarator();
5120}
5121
5122/// isFunctionDeclaratorIdentifierList - This parameter list may have an
5123/// identifier list form for a K&R-style function:  void foo(a,b,c)
5124///
5125/// Note that identifier-lists are only allowed for normal declarators, not for
5126/// abstract-declarators.
5127bool Parser::isFunctionDeclaratorIdentifierList() {
5128  return !getLangOpts().CPlusPlus
5129         && Tok.is(tok::identifier)
5130         && !TryAltiVecVectorToken()
5131         // K&R identifier lists can't have typedefs as identifiers, per C99
5132         // 6.7.5.3p11.
5133         && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
5134         // Identifier lists follow a really simple grammar: the identifiers can
5135         // be followed *only* by a ", identifier" or ")".  However, K&R
5136         // identifier lists are really rare in the brave new modern world, and
5137         // it is very common for someone to typo a type in a non-K&R style
5138         // list.  If we are presented with something like: "void foo(intptr x,
5139         // float y)", we don't want to start parsing the function declarator as
5140         // though it is a K&R style declarator just because intptr is an
5141         // invalid type.
5142         //
5143         // To handle this, we check to see if the token after the first
5144         // identifier is a "," or ")".  Only then do we parse it as an
5145         // identifier list.
5146         && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren));
5147}
5148
5149/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
5150/// we found a K&R-style identifier list instead of a typed parameter list.
5151///
5152/// After returning, ParamInfo will hold the parsed parameters.
5153///
5154///       identifier-list: [C99 6.7.5]
5155///         identifier
5156///         identifier-list ',' identifier
5157///
5158void Parser::ParseFunctionDeclaratorIdentifierList(
5159       Declarator &D,
5160       SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
5161  // If there was no identifier specified for the declarator, either we are in
5162  // an abstract-declarator, or we are in a parameter declarator which was found
5163  // to be abstract.  In abstract-declarators, identifier lists are not valid:
5164  // diagnose this.
5165  if (!D.getIdentifier())
5166    Diag(Tok, diag::ext_ident_list_in_param);
5167
5168  // Maintain an efficient lookup of params we have seen so far.
5169  llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
5170
5171  while (1) {
5172    // If this isn't an identifier, report the error and skip until ')'.
5173    if (Tok.isNot(tok::identifier)) {
5174      Diag(Tok, diag::err_expected_ident);
5175      SkipUntil(tok::r_paren, /*StopAtSemi=*/true, /*DontConsume=*/true);
5176      // Forget we parsed anything.
5177      ParamInfo.clear();
5178      return;
5179    }
5180
5181    IdentifierInfo *ParmII = Tok.getIdentifierInfo();
5182
5183    // Reject 'typedef int y; int test(x, y)', but continue parsing.
5184    if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
5185      Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
5186
5187    // Verify that the argument identifier has not already been mentioned.
5188    if (!ParamsSoFar.insert(ParmII)) {
5189      Diag(Tok, diag::err_param_redefinition) << ParmII;
5190    } else {
5191      // Remember this identifier in ParamInfo.
5192      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
5193                                                     Tok.getLocation(),
5194                                                     0));
5195    }
5196
5197    // Eat the identifier.
5198    ConsumeToken();
5199
5200    // The list continues if we see a comma.
5201    if (Tok.isNot(tok::comma))
5202      break;
5203    ConsumeToken();
5204  }
5205}
5206
5207/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
5208/// after the opening parenthesis. This function will not parse a K&R-style
5209/// identifier list.
5210///
5211/// D is the declarator being parsed.  If FirstArgAttrs is non-null, then the
5212/// caller parsed those arguments immediately after the open paren - they should
5213/// be considered to be part of the first parameter.
5214///
5215/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
5216/// be the location of the ellipsis, if any was parsed.
5217///
5218///       parameter-type-list: [C99 6.7.5]
5219///         parameter-list
5220///         parameter-list ',' '...'
5221/// [C++]   parameter-list '...'
5222///
5223///       parameter-list: [C99 6.7.5]
5224///         parameter-declaration
5225///         parameter-list ',' parameter-declaration
5226///
5227///       parameter-declaration: [C99 6.7.5]
5228///         declaration-specifiers declarator
5229/// [C++]   declaration-specifiers declarator '=' assignment-expression
5230/// [C++11]                                       initializer-clause
5231/// [GNU]   declaration-specifiers declarator attributes
5232///         declaration-specifiers abstract-declarator[opt]
5233/// [C++]   declaration-specifiers abstract-declarator[opt]
5234///           '=' assignment-expression
5235/// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
5236/// [C++11] attribute-specifier-seq parameter-declaration
5237///
5238void Parser::ParseParameterDeclarationClause(
5239       Declarator &D,
5240       ParsedAttributes &FirstArgAttrs,
5241       SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
5242       SourceLocation &EllipsisLoc) {
5243
5244  while (1) {
5245    if (Tok.is(tok::ellipsis)) {
5246      // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
5247      // before deciding this was a parameter-declaration-clause.
5248      EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
5249      break;
5250    }
5251
5252    // Parse the declaration-specifiers.
5253    // Just use the ParsingDeclaration "scope" of the declarator.
5254    DeclSpec DS(AttrFactory);
5255
5256    // Parse any C++11 attributes.
5257    MaybeParseCXX11Attributes(DS.getAttributes());
5258
5259    // Skip any Microsoft attributes before a param.
5260    MaybeParseMicrosoftAttributes(DS.getAttributes());
5261
5262    SourceLocation DSStart = Tok.getLocation();
5263
5264    // If the caller parsed attributes for the first argument, add them now.
5265    // Take them so that we only apply the attributes to the first parameter.
5266    // FIXME: If we can leave the attributes in the token stream somehow, we can
5267    // get rid of a parameter (FirstArgAttrs) and this statement. It might be
5268    // too much hassle.
5269    DS.takeAttributesFrom(FirstArgAttrs);
5270
5271    ParseDeclarationSpecifiers(DS);
5272
5273    // Parse the declarator.  This is "PrototypeContext", because we must
5274    // accept either 'declarator' or 'abstract-declarator' here.
5275    Declarator ParmDecl(DS, Declarator::PrototypeContext);
5276    ParseDeclarator(ParmDecl);
5277
5278    // Parse GNU attributes, if present.
5279    MaybeParseGNUAttributes(ParmDecl);
5280
5281    // Remember this parsed parameter in ParamInfo.
5282    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
5283
5284    // DefArgToks is used when the parsing of default arguments needs
5285    // to be delayed.
5286    CachedTokens *DefArgToks = 0;
5287
5288    // If no parameter was specified, verify that *something* was specified,
5289    // otherwise we have a missing type and identifier.
5290    if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
5291        ParmDecl.getNumTypeObjects() == 0) {
5292      // Completely missing, emit error.
5293      Diag(DSStart, diag::err_missing_param);
5294    } else {
5295      // Otherwise, we have something.  Add it and let semantic analysis try
5296      // to grok it and add the result to the ParamInfo we are building.
5297
5298      // Inform the actions module about the parameter declarator, so it gets
5299      // added to the current scope.
5300      Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
5301
5302      // Parse the default argument, if any. We parse the default
5303      // arguments in all dialects; the semantic analysis in
5304      // ActOnParamDefaultArgument will reject the default argument in
5305      // C.
5306      if (Tok.is(tok::equal)) {
5307        SourceLocation EqualLoc = Tok.getLocation();
5308
5309        // Parse the default argument
5310        if (D.getContext() == Declarator::MemberContext) {
5311          // If we're inside a class definition, cache the tokens
5312          // corresponding to the default argument. We'll actually parse
5313          // them when we see the end of the class definition.
5314          // FIXME: Can we use a smart pointer for Toks?
5315          DefArgToks = new CachedTokens;
5316
5317          if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
5318                                    /*StopAtSemi=*/true,
5319                                    /*ConsumeFinalToken=*/false)) {
5320            delete DefArgToks;
5321            DefArgToks = 0;
5322            Actions.ActOnParamDefaultArgumentError(Param);
5323          } else {
5324            // Mark the end of the default argument so that we know when to
5325            // stop when we parse it later on.
5326            Token DefArgEnd;
5327            DefArgEnd.startToken();
5328            DefArgEnd.setKind(tok::cxx_defaultarg_end);
5329            DefArgEnd.setLocation(Tok.getLocation());
5330            DefArgToks->push_back(DefArgEnd);
5331            Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
5332                                                (*DefArgToks)[1].getLocation());
5333          }
5334        } else {
5335          // Consume the '='.
5336          ConsumeToken();
5337
5338          // The argument isn't actually potentially evaluated unless it is
5339          // used.
5340          EnterExpressionEvaluationContext Eval(Actions,
5341                                              Sema::PotentiallyEvaluatedIfUsed,
5342                                                Param);
5343
5344          ExprResult DefArgResult;
5345          if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
5346            Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
5347            DefArgResult = ParseBraceInitializer();
5348          } else
5349            DefArgResult = ParseAssignmentExpression();
5350          if (DefArgResult.isInvalid()) {
5351            Actions.ActOnParamDefaultArgumentError(Param);
5352            SkipUntil(tok::comma, tok::r_paren, true, true);
5353          } else {
5354            // Inform the actions module about the default argument
5355            Actions.ActOnParamDefaultArgument(Param, EqualLoc,
5356                                              DefArgResult.take());
5357          }
5358        }
5359      }
5360
5361      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
5362                                          ParmDecl.getIdentifierLoc(), Param,
5363                                          DefArgToks));
5364    }
5365
5366    // If the next token is a comma, consume it and keep reading arguments.
5367    if (Tok.isNot(tok::comma)) {
5368      if (Tok.is(tok::ellipsis)) {
5369        EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
5370
5371        if (!getLangOpts().CPlusPlus) {
5372          // We have ellipsis without a preceding ',', which is ill-formed
5373          // in C. Complain and provide the fix.
5374          Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
5375            << FixItHint::CreateInsertion(EllipsisLoc, ", ");
5376        }
5377      }
5378
5379      break;
5380    }
5381
5382    // Consume the comma.
5383    ConsumeToken();
5384  }
5385
5386}
5387
5388/// [C90]   direct-declarator '[' constant-expression[opt] ']'
5389/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5390/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5391/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5392/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
5393/// [C++11] direct-declarator '[' constant-expression[opt] ']'
5394///                           attribute-specifier-seq[opt]
5395void Parser::ParseBracketDeclarator(Declarator &D) {
5396  if (CheckProhibitedCXX11Attribute())
5397    return;
5398
5399  BalancedDelimiterTracker T(*this, tok::l_square);
5400  T.consumeOpen();
5401
5402  // C array syntax has many features, but by-far the most common is [] and [4].
5403  // This code does a fast path to handle some of the most obvious cases.
5404  if (Tok.getKind() == tok::r_square) {
5405    T.consumeClose();
5406    ParsedAttributes attrs(AttrFactory);
5407    MaybeParseCXX11Attributes(attrs);
5408
5409    // Remember that we parsed the empty array type.
5410    ExprResult NumElements;
5411    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
5412                                            T.getOpenLocation(),
5413                                            T.getCloseLocation()),
5414                  attrs, T.getCloseLocation());
5415    return;
5416  } else if (Tok.getKind() == tok::numeric_constant &&
5417             GetLookAheadToken(1).is(tok::r_square)) {
5418    // [4] is very common.  Parse the numeric constant expression.
5419    ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
5420    ConsumeToken();
5421
5422    T.consumeClose();
5423    ParsedAttributes attrs(AttrFactory);
5424    MaybeParseCXX11Attributes(attrs);
5425
5426    // Remember that we parsed a array type, and remember its features.
5427    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false,
5428                                            ExprRes.release(),
5429                                            T.getOpenLocation(),
5430                                            T.getCloseLocation()),
5431                  attrs, T.getCloseLocation());
5432    return;
5433  }
5434
5435  // If valid, this location is the position where we read the 'static' keyword.
5436  SourceLocation StaticLoc;
5437  if (Tok.is(tok::kw_static))
5438    StaticLoc = ConsumeToken();
5439
5440  // If there is a type-qualifier-list, read it now.
5441  // Type qualifiers in an array subscript are a C99 feature.
5442  DeclSpec DS(AttrFactory);
5443  ParseTypeQualifierListOpt(DS, false /*no attributes*/);
5444
5445  // If we haven't already read 'static', check to see if there is one after the
5446  // type-qualifier-list.
5447  if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
5448    StaticLoc = ConsumeToken();
5449
5450  // Handle "direct-declarator [ type-qual-list[opt] * ]".
5451  bool isStar = false;
5452  ExprResult NumElements;
5453
5454  // Handle the case where we have '[*]' as the array size.  However, a leading
5455  // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
5456  // the token after the star is a ']'.  Since stars in arrays are
5457  // infrequent, use of lookahead is not costly here.
5458  if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
5459    ConsumeToken();  // Eat the '*'.
5460
5461    if (StaticLoc.isValid()) {
5462      Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
5463      StaticLoc = SourceLocation();  // Drop the static.
5464    }
5465    isStar = true;
5466  } else if (Tok.isNot(tok::r_square)) {
5467    // Note, in C89, this production uses the constant-expr production instead
5468    // of assignment-expr.  The only difference is that assignment-expr allows
5469    // things like '=' and '*='.  Sema rejects these in C89 mode because they
5470    // are not i-c-e's, so we don't need to distinguish between the two here.
5471
5472    // Parse the constant-expression or assignment-expression now (depending
5473    // on dialect).
5474    if (getLangOpts().CPlusPlus) {
5475      NumElements = ParseConstantExpression();
5476    } else {
5477      EnterExpressionEvaluationContext Unevaluated(Actions,
5478                                                   Sema::ConstantEvaluated);
5479      NumElements = ParseAssignmentExpression();
5480    }
5481  }
5482
5483  // If there was an error parsing the assignment-expression, recover.
5484  if (NumElements.isInvalid()) {
5485    D.setInvalidType(true);
5486    // If the expression was invalid, skip it.
5487    SkipUntil(tok::r_square);
5488    return;
5489  }
5490
5491  T.consumeClose();
5492
5493  ParsedAttributes attrs(AttrFactory);
5494  MaybeParseCXX11Attributes(attrs);
5495
5496  // Remember that we parsed a array type, and remember its features.
5497  D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
5498                                          StaticLoc.isValid(), isStar,
5499                                          NumElements.release(),
5500                                          T.getOpenLocation(),
5501                                          T.getCloseLocation()),
5502                attrs, T.getCloseLocation());
5503}
5504
5505/// [GNU]   typeof-specifier:
5506///           typeof ( expressions )
5507///           typeof ( type-name )
5508/// [GNU/C++] typeof unary-expression
5509///
5510void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
5511  assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
5512  Token OpTok = Tok;
5513  SourceLocation StartLoc = ConsumeToken();
5514
5515  const bool hasParens = Tok.is(tok::l_paren);
5516
5517  EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
5518                                               Sema::ReuseLambdaContextDecl);
5519
5520  bool isCastExpr;
5521  ParsedType CastTy;
5522  SourceRange CastRange;
5523  ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
5524                                                          CastTy, CastRange);
5525  if (hasParens)
5526    DS.setTypeofParensRange(CastRange);
5527
5528  if (CastRange.getEnd().isInvalid())
5529    // FIXME: Not accurate, the range gets one token more than it should.
5530    DS.SetRangeEnd(Tok.getLocation());
5531  else
5532    DS.SetRangeEnd(CastRange.getEnd());
5533
5534  if (isCastExpr) {
5535    if (!CastTy) {
5536      DS.SetTypeSpecError();
5537      return;
5538    }
5539
5540    const char *PrevSpec = 0;
5541    unsigned DiagID;
5542    // Check for duplicate type specifiers (e.g. "int typeof(int)").
5543    if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
5544                           DiagID, CastTy))
5545      Diag(StartLoc, DiagID) << PrevSpec;
5546    return;
5547  }
5548
5549  // If we get here, the operand to the typeof was an expresion.
5550  if (Operand.isInvalid()) {
5551    DS.SetTypeSpecError();
5552    return;
5553  }
5554
5555  // We might need to transform the operand if it is potentially evaluated.
5556  Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
5557  if (Operand.isInvalid()) {
5558    DS.SetTypeSpecError();
5559    return;
5560  }
5561
5562  const char *PrevSpec = 0;
5563  unsigned DiagID;
5564  // Check for duplicate type specifiers (e.g. "int typeof(int)").
5565  if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
5566                         DiagID, Operand.get()))
5567    Diag(StartLoc, DiagID) << PrevSpec;
5568}
5569
5570/// [C11]   atomic-specifier:
5571///           _Atomic ( type-name )
5572///
5573void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
5574  assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
5575         "Not an atomic specifier");
5576
5577  SourceLocation StartLoc = ConsumeToken();
5578  BalancedDelimiterTracker T(*this, tok::l_paren);
5579  if (T.consumeOpen())
5580    return;
5581
5582  TypeResult Result = ParseTypeName();
5583  if (Result.isInvalid()) {
5584    SkipUntil(tok::r_paren);
5585    return;
5586  }
5587
5588  // Match the ')'
5589  T.consumeClose();
5590
5591  if (T.getCloseLocation().isInvalid())
5592    return;
5593
5594  DS.setTypeofParensRange(T.getRange());
5595  DS.SetRangeEnd(T.getCloseLocation());
5596
5597  const char *PrevSpec = 0;
5598  unsigned DiagID;
5599  if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
5600                         DiagID, Result.release()))
5601    Diag(StartLoc, DiagID) << PrevSpec;
5602}
5603
5604
5605/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
5606/// from TryAltiVecVectorToken.
5607bool Parser::TryAltiVecVectorTokenOutOfLine() {
5608  Token Next = NextToken();
5609  switch (Next.getKind()) {
5610  default: return false;
5611  case tok::kw_short:
5612  case tok::kw_long:
5613  case tok::kw_signed:
5614  case tok::kw_unsigned:
5615  case tok::kw_void:
5616  case tok::kw_char:
5617  case tok::kw_int:
5618  case tok::kw_float:
5619  case tok::kw_double:
5620  case tok::kw_bool:
5621  case tok::kw___pixel:
5622    Tok.setKind(tok::kw___vector);
5623    return true;
5624  case tok::identifier:
5625    if (Next.getIdentifierInfo() == Ident_pixel) {
5626      Tok.setKind(tok::kw___vector);
5627      return true;
5628    }
5629    if (Next.getIdentifierInfo() == Ident_bool) {
5630      Tok.setKind(tok::kw___vector);
5631      return true;
5632    }
5633    return false;
5634  }
5635}
5636
5637bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
5638                                      const char *&PrevSpec, unsigned &DiagID,
5639                                      bool &isInvalid) {
5640  if (Tok.getIdentifierInfo() == Ident_vector) {
5641    Token Next = NextToken();
5642    switch (Next.getKind()) {
5643    case tok::kw_short:
5644    case tok::kw_long:
5645    case tok::kw_signed:
5646    case tok::kw_unsigned:
5647    case tok::kw_void:
5648    case tok::kw_char:
5649    case tok::kw_int:
5650    case tok::kw_float:
5651    case tok::kw_double:
5652    case tok::kw_bool:
5653    case tok::kw___pixel:
5654      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
5655      return true;
5656    case tok::identifier:
5657      if (Next.getIdentifierInfo() == Ident_pixel) {
5658        isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
5659        return true;
5660      }
5661      if (Next.getIdentifierInfo() == Ident_bool) {
5662        isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
5663        return true;
5664      }
5665      break;
5666    default:
5667      break;
5668    }
5669  } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
5670             DS.isTypeAltiVecVector()) {
5671    isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
5672    return true;
5673  } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
5674             DS.isTypeAltiVecVector()) {
5675    isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID);
5676    return true;
5677  }
5678  return false;
5679}
5680