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