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