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