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