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