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