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