ParseDecl.cpp revision 3e156ad9adc7332e626eedbc86aa4e3b03f17ca5
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
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      // Annotate C++ scope specifiers.  If we get one, loop.
863      if (TryAnnotateCXXScopeToken(true))
864        continue;
865      goto DoneWithDeclSpec;
866
867    case tok::annot_cxxscope: {
868      if (DS.hasTypeSpecifier())
869        goto DoneWithDeclSpec;
870
871      CXXScopeSpec SS;
872      SS.setScopeRep(Tok.getAnnotationValue());
873      SS.setRange(Tok.getAnnotationRange());
874
875      // We are looking for a qualified typename.
876      Token Next = NextToken();
877      if (Next.is(tok::annot_template_id) &&
878          static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
879            ->Kind == TNK_Type_template) {
880        // We have a qualified template-id, e.g., N::A<int>
881
882        // C++ [class.qual]p2:
883        //   In a lookup in which the constructor is an acceptable lookup
884        //   result and the nested-name-specifier nominates a class C:
885        //
886        //     - if the name specified after the
887        //       nested-name-specifier, when looked up in C, is the
888        //       injected-class-name of C (Clause 9), or
889        //
890        //     - if the name specified after the nested-name-specifier
891        //       is the same as the identifier or the
892        //       simple-template-id's template-name in the last
893        //       component of the nested-name-specifier,
894        //
895        //   the name is instead considered to name the constructor of
896        //   class C.
897        //
898        // Thus, if the template-name is actually the constructor
899        // name, then the code is ill-formed; this interpretation is
900        // reinforced by the NAD status of core issue 635.
901        TemplateIdAnnotation *TemplateId
902          = static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue());
903        if (DSContext == DSC_top_level && TemplateId->Name &&
904            Actions.isCurrentClassName(*TemplateId->Name, CurScope, &SS)) {
905          if (isConstructorDeclarator()) {
906            // The user meant this to be an out-of-line constructor
907            // definition, but template arguments are not allowed
908            // there.  Just allow this as a constructor; we'll
909            // complain about it later.
910            goto DoneWithDeclSpec;
911          }
912
913          // The user meant this to name a type, but it actually names
914          // a constructor with some extraneous template
915          // arguments. Complain, then parse it as a type as the user
916          // intended.
917          Diag(TemplateId->TemplateNameLoc,
918               diag::err_out_of_line_template_id_names_constructor)
919            << TemplateId->Name;
920        }
921
922        DS.getTypeSpecScope() = SS;
923        ConsumeToken(); // The C++ scope.
924        assert(Tok.is(tok::annot_template_id) &&
925               "ParseOptionalCXXScopeSpecifier not working");
926        AnnotateTemplateIdTokenAsType(&SS);
927        continue;
928      }
929
930      if (Next.is(tok::annot_typename)) {
931        DS.getTypeSpecScope() = SS;
932        ConsumeToken(); // The C++ scope.
933        if (Tok.getAnnotationValue())
934          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc,
935                                         PrevSpec, DiagID,
936                                         Tok.getAnnotationValue());
937        else
938          DS.SetTypeSpecError();
939        DS.SetRangeEnd(Tok.getAnnotationEndLoc());
940        ConsumeToken(); // The typename
941      }
942
943      if (Next.isNot(tok::identifier))
944        goto DoneWithDeclSpec;
945
946      // If we're in a context where the identifier could be a class name,
947      // check whether this is a constructor declaration.
948      if (DSContext == DSC_top_level &&
949          Actions.isCurrentClassName(*Next.getIdentifierInfo(), CurScope,
950                                     &SS)) {
951        if (isConstructorDeclarator())
952          goto DoneWithDeclSpec;
953
954        // As noted in C++ [class.qual]p2 (cited above), when the name
955        // of the class is qualified in a context where it could name
956        // a constructor, its a constructor name. However, we've
957        // looked at the declarator, and the user probably meant this
958        // to be a type. Complain that it isn't supposed to be treated
959        // as a type, then proceed to parse it as a type.
960        Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
961          << Next.getIdentifierInfo();
962      }
963
964      TypeTy *TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
965                                            Next.getLocation(), CurScope, &SS);
966
967      // If the referenced identifier is not a type, then this declspec is
968      // erroneous: We already checked about that it has no type specifier, and
969      // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
970      // typename.
971      if (TypeRep == 0) {
972        ConsumeToken();   // Eat the scope spec so the identifier is current.
973        if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue;
974        goto DoneWithDeclSpec;
975      }
976
977      DS.getTypeSpecScope() = SS;
978      ConsumeToken(); // The C++ scope.
979
980      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
981                                     DiagID, TypeRep);
982      if (isInvalid)
983        break;
984
985      DS.SetRangeEnd(Tok.getLocation());
986      ConsumeToken(); // The typename.
987
988      continue;
989    }
990
991    case tok::annot_typename: {
992      if (Tok.getAnnotationValue())
993        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
994                                       DiagID, Tok.getAnnotationValue());
995      else
996        DS.SetTypeSpecError();
997      DS.SetRangeEnd(Tok.getAnnotationEndLoc());
998      ConsumeToken(); // The typename
999
1000      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1001      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1002      // Objective-C interface.  If we don't have Objective-C or a '<', this is
1003      // just a normal reference to a typedef name.
1004      if (!Tok.is(tok::less) || !getLang().ObjC1)
1005        continue;
1006
1007      SourceLocation LAngleLoc, EndProtoLoc;
1008      llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1009      llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1010      ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1011                                  LAngleLoc, EndProtoLoc);
1012      DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1013                               ProtocolLocs.data(), LAngleLoc);
1014
1015      DS.SetRangeEnd(EndProtoLoc);
1016      continue;
1017    }
1018
1019      // typedef-name
1020    case tok::identifier: {
1021      // In C++, check to see if this is a scope specifier like foo::bar::, if
1022      // so handle it as such.  This is important for ctor parsing.
1023      if (getLang().CPlusPlus && TryAnnotateCXXScopeToken(true))
1024        continue;
1025
1026      // This identifier can only be a typedef name if we haven't already seen
1027      // a type-specifier.  Without this check we misparse:
1028      //  typedef int X; struct Y { short X; };  as 'short int'.
1029      if (DS.hasTypeSpecifier())
1030        goto DoneWithDeclSpec;
1031
1032      // It has to be available as a typedef too!
1033      TypeTy *TypeRep = Actions.getTypeName(*Tok.getIdentifierInfo(),
1034                                            Tok.getLocation(), CurScope);
1035
1036      // If this is not a typedef name, don't parse it as part of the declspec,
1037      // it must be an implicit int or an error.
1038      if (TypeRep == 0) {
1039        if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue;
1040        goto DoneWithDeclSpec;
1041      }
1042
1043      // If we're in a context where the identifier could be a class name,
1044      // check whether this is a constructor declaration.
1045      if (getLang().CPlusPlus && DSContext == DSC_class &&
1046          Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) &&
1047          isConstructorDeclarator())
1048        goto DoneWithDeclSpec;
1049
1050      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1051                                     DiagID, TypeRep);
1052      if (isInvalid)
1053        break;
1054
1055      DS.SetRangeEnd(Tok.getLocation());
1056      ConsumeToken(); // The identifier
1057
1058      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1059      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1060      // Objective-C interface.  If we don't have Objective-C or a '<', this is
1061      // just a normal reference to a typedef name.
1062      if (!Tok.is(tok::less) || !getLang().ObjC1)
1063        continue;
1064
1065      SourceLocation LAngleLoc, EndProtoLoc;
1066      llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1067      llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1068      ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1069                                  LAngleLoc, EndProtoLoc);
1070      DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1071                               ProtocolLocs.data(), LAngleLoc);
1072
1073      DS.SetRangeEnd(EndProtoLoc);
1074
1075      // Need to support trailing type qualifiers (e.g. "id<p> const").
1076      // If a type specifier follows, it will be diagnosed elsewhere.
1077      continue;
1078    }
1079
1080      // type-name
1081    case tok::annot_template_id: {
1082      TemplateIdAnnotation *TemplateId
1083        = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1084      if (TemplateId->Kind != TNK_Type_template) {
1085        // This template-id does not refer to a type name, so we're
1086        // done with the type-specifiers.
1087        goto DoneWithDeclSpec;
1088      }
1089
1090      // If we're in a context where the template-id could be a
1091      // constructor name or specialization, check whether this is a
1092      // constructor declaration.
1093      if (getLang().CPlusPlus && DSContext == DSC_class &&
1094          Actions.isCurrentClassName(*TemplateId->Name, CurScope) &&
1095          isConstructorDeclarator())
1096        goto DoneWithDeclSpec;
1097
1098      // Turn the template-id annotation token into a type annotation
1099      // token, then try again to parse it as a type-specifier.
1100      AnnotateTemplateIdTokenAsType();
1101      continue;
1102    }
1103
1104    // GNU attributes support.
1105    case tok::kw___attribute:
1106      DS.AddAttributes(ParseGNUAttributes());
1107      continue;
1108
1109    // Microsoft declspec support.
1110    case tok::kw___declspec:
1111      DS.AddAttributes(ParseMicrosoftDeclSpec());
1112      continue;
1113
1114    // Microsoft single token adornments.
1115    case tok::kw___forceinline:
1116      // FIXME: Add handling here!
1117      break;
1118
1119    case tok::kw___ptr64:
1120    case tok::kw___w64:
1121    case tok::kw___cdecl:
1122    case tok::kw___stdcall:
1123    case tok::kw___fastcall:
1124      DS.AddAttributes(ParseMicrosoftTypeAttributes());
1125      continue;
1126
1127    // storage-class-specifier
1128    case tok::kw_typedef:
1129      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec,
1130                                         DiagID);
1131      break;
1132    case tok::kw_extern:
1133      if (DS.isThreadSpecified())
1134        Diag(Tok, diag::ext_thread_before) << "extern";
1135      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec,
1136                                         DiagID);
1137      break;
1138    case tok::kw___private_extern__:
1139      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
1140                                         PrevSpec, DiagID);
1141      break;
1142    case tok::kw_static:
1143      if (DS.isThreadSpecified())
1144        Diag(Tok, diag::ext_thread_before) << "static";
1145      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec,
1146                                         DiagID);
1147      break;
1148    case tok::kw_auto:
1149      if (getLang().CPlusPlus0x)
1150        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
1151                                       DiagID);
1152      else
1153        isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec,
1154                                           DiagID);
1155      break;
1156    case tok::kw_register:
1157      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec,
1158                                         DiagID);
1159      break;
1160    case tok::kw_mutable:
1161      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec,
1162                                         DiagID);
1163      break;
1164    case tok::kw___thread:
1165      isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
1166      break;
1167
1168    // function-specifier
1169    case tok::kw_inline:
1170      isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
1171      break;
1172    case tok::kw_virtual:
1173      isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
1174      break;
1175    case tok::kw_explicit:
1176      isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
1177      break;
1178
1179    // friend
1180    case tok::kw_friend:
1181      if (DSContext == DSC_class)
1182        isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
1183      else {
1184        PrevSpec = ""; // not actually used by the diagnostic
1185        DiagID = diag::err_friend_invalid_in_context;
1186        isInvalid = true;
1187      }
1188      break;
1189
1190    // constexpr
1191    case tok::kw_constexpr:
1192      isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
1193      break;
1194
1195    // type-specifier
1196    case tok::kw_short:
1197      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
1198                                      DiagID);
1199      break;
1200    case tok::kw_long:
1201      if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1202        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1203                                        DiagID);
1204      else
1205        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1206                                        DiagID);
1207      break;
1208    case tok::kw_signed:
1209      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
1210                                     DiagID);
1211      break;
1212    case tok::kw_unsigned:
1213      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1214                                     DiagID);
1215      break;
1216    case tok::kw__Complex:
1217      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1218                                        DiagID);
1219      break;
1220    case tok::kw__Imaginary:
1221      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1222                                        DiagID);
1223      break;
1224    case tok::kw_void:
1225      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
1226                                     DiagID);
1227      break;
1228    case tok::kw_char:
1229      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
1230                                     DiagID);
1231      break;
1232    case tok::kw_int:
1233      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
1234                                     DiagID);
1235      break;
1236    case tok::kw_float:
1237      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
1238                                     DiagID);
1239      break;
1240    case tok::kw_double:
1241      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
1242                                     DiagID);
1243      break;
1244    case tok::kw_wchar_t:
1245      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
1246                                     DiagID);
1247      break;
1248    case tok::kw_char16_t:
1249      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
1250                                     DiagID);
1251      break;
1252    case tok::kw_char32_t:
1253      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
1254                                     DiagID);
1255      break;
1256    case tok::kw_bool:
1257    case tok::kw__Bool:
1258      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
1259                                     DiagID);
1260      break;
1261    case tok::kw__Decimal32:
1262      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1263                                     DiagID);
1264      break;
1265    case tok::kw__Decimal64:
1266      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1267                                     DiagID);
1268      break;
1269    case tok::kw__Decimal128:
1270      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1271                                     DiagID);
1272      break;
1273
1274    // class-specifier:
1275    case tok::kw_class:
1276    case tok::kw_struct:
1277    case tok::kw_union: {
1278      tok::TokenKind Kind = Tok.getKind();
1279      ConsumeToken();
1280      ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS);
1281      continue;
1282    }
1283
1284    // enum-specifier:
1285    case tok::kw_enum:
1286      ConsumeToken();
1287      ParseEnumSpecifier(Loc, DS, AS);
1288      continue;
1289
1290    // cv-qualifier:
1291    case tok::kw_const:
1292      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
1293                                 getLang());
1294      break;
1295    case tok::kw_volatile:
1296      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
1297                                 getLang());
1298      break;
1299    case tok::kw_restrict:
1300      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
1301                                 getLang());
1302      break;
1303
1304    // C++ typename-specifier:
1305    case tok::kw_typename:
1306      if (TryAnnotateTypeOrScopeToken())
1307        continue;
1308      break;
1309
1310    // GNU typeof support.
1311    case tok::kw_typeof:
1312      ParseTypeofSpecifier(DS);
1313      continue;
1314
1315    case tok::kw_decltype:
1316      ParseDecltypeSpecifier(DS);
1317      continue;
1318
1319    case tok::less:
1320      // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
1321      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
1322      // but we support it.
1323      if (DS.hasTypeSpecifier() || !getLang().ObjC1)
1324        goto DoneWithDeclSpec;
1325
1326      {
1327        SourceLocation LAngleLoc, EndProtoLoc;
1328        llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1329        llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1330        ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1331                                    LAngleLoc, EndProtoLoc);
1332        DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1333                                 ProtocolLocs.data(), LAngleLoc);
1334        DS.SetRangeEnd(EndProtoLoc);
1335
1336        Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
1337          << CodeModificationHint::CreateInsertion(Loc, "id")
1338          << SourceRange(Loc, EndProtoLoc);
1339        // Need to support trailing type qualifiers (e.g. "id<p> const").
1340        // If a type specifier follows, it will be diagnosed elsewhere.
1341        continue;
1342      }
1343    }
1344    // If the specifier wasn't legal, issue a diagnostic.
1345    if (isInvalid) {
1346      assert(PrevSpec && "Method did not return previous specifier!");
1347      assert(DiagID);
1348      Diag(Tok, DiagID) << PrevSpec;
1349    }
1350    DS.SetRangeEnd(Tok.getLocation());
1351    ConsumeToken();
1352  }
1353}
1354
1355/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
1356/// primarily follow the C++ grammar with additions for C99 and GNU,
1357/// which together subsume the C grammar. Note that the C++
1358/// type-specifier also includes the C type-qualifier (for const,
1359/// volatile, and C99 restrict). Returns true if a type-specifier was
1360/// found (and parsed), false otherwise.
1361///
1362///       type-specifier: [C++ 7.1.5]
1363///         simple-type-specifier
1364///         class-specifier
1365///         enum-specifier
1366///         elaborated-type-specifier  [TODO]
1367///         cv-qualifier
1368///
1369///       cv-qualifier: [C++ 7.1.5.1]
1370///         'const'
1371///         'volatile'
1372/// [C99]   'restrict'
1373///
1374///       simple-type-specifier: [ C++ 7.1.5.2]
1375///         '::'[opt] nested-name-specifier[opt] type-name [TODO]
1376///         '::'[opt] nested-name-specifier 'template' template-id [TODO]
1377///         'char'
1378///         'wchar_t'
1379///         'bool'
1380///         'short'
1381///         'int'
1382///         'long'
1383///         'signed'
1384///         'unsigned'
1385///         'float'
1386///         'double'
1387///         'void'
1388/// [C99]   '_Bool'
1389/// [C99]   '_Complex'
1390/// [C99]   '_Imaginary'  // Removed in TC2?
1391/// [GNU]   '_Decimal32'
1392/// [GNU]   '_Decimal64'
1393/// [GNU]   '_Decimal128'
1394/// [GNU]   typeof-specifier
1395/// [OBJC]  class-name objc-protocol-refs[opt]    [TODO]
1396/// [OBJC]  typedef-name objc-protocol-refs[opt]  [TODO]
1397/// [C++0x] 'decltype' ( expression )
1398bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid,
1399                                        const char *&PrevSpec,
1400                                        unsigned &DiagID,
1401                                      const ParsedTemplateInfo &TemplateInfo) {
1402  SourceLocation Loc = Tok.getLocation();
1403
1404  switch (Tok.getKind()) {
1405  case tok::identifier:   // foo::bar
1406  case tok::kw_typename:  // typename foo::bar
1407    // Annotate typenames and C++ scope specifiers.  If we get one, just
1408    // recurse to handle whatever we get.
1409    if (TryAnnotateTypeOrScopeToken())
1410      return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1411                                        TemplateInfo);
1412    // Otherwise, not a type specifier.
1413    return false;
1414  case tok::coloncolon:   // ::foo::bar
1415    if (NextToken().is(tok::kw_new) ||    // ::new
1416        NextToken().is(tok::kw_delete))   // ::delete
1417      return false;
1418
1419    // Annotate typenames and C++ scope specifiers.  If we get one, just
1420    // recurse to handle whatever we get.
1421    if (TryAnnotateTypeOrScopeToken())
1422      return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1423                                        TemplateInfo);
1424    // Otherwise, not a type specifier.
1425    return false;
1426
1427  // simple-type-specifier:
1428  case tok::annot_typename: {
1429    if (Tok.getAnnotationValue())
1430      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1431                                     DiagID, Tok.getAnnotationValue());
1432    else
1433      DS.SetTypeSpecError();
1434    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1435    ConsumeToken(); // The typename
1436
1437    // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1438    // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1439    // Objective-C interface.  If we don't have Objective-C or a '<', this is
1440    // just a normal reference to a typedef name.
1441    if (!Tok.is(tok::less) || !getLang().ObjC1)
1442      return true;
1443
1444    SourceLocation LAngleLoc, EndProtoLoc;
1445    llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1446    llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1447    ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1448                                LAngleLoc, EndProtoLoc);
1449    DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1450                             ProtocolLocs.data(), LAngleLoc);
1451
1452    DS.SetRangeEnd(EndProtoLoc);
1453    return true;
1454  }
1455
1456  case tok::kw_short:
1457    isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
1458    break;
1459  case tok::kw_long:
1460    if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1461      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1462                                      DiagID);
1463    else
1464      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1465                                      DiagID);
1466    break;
1467  case tok::kw_signed:
1468    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1469    break;
1470  case tok::kw_unsigned:
1471    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1472                                   DiagID);
1473    break;
1474  case tok::kw__Complex:
1475    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1476                                      DiagID);
1477    break;
1478  case tok::kw__Imaginary:
1479    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1480                                      DiagID);
1481    break;
1482  case tok::kw_void:
1483    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
1484    break;
1485  case tok::kw_char:
1486    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
1487    break;
1488  case tok::kw_int:
1489    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
1490    break;
1491  case tok::kw_float:
1492    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
1493    break;
1494  case tok::kw_double:
1495    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
1496    break;
1497  case tok::kw_wchar_t:
1498    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
1499    break;
1500  case tok::kw_char16_t:
1501    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
1502    break;
1503  case tok::kw_char32_t:
1504    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
1505    break;
1506  case tok::kw_bool:
1507  case tok::kw__Bool:
1508    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
1509    break;
1510  case tok::kw__Decimal32:
1511    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1512                                   DiagID);
1513    break;
1514  case tok::kw__Decimal64:
1515    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1516                                   DiagID);
1517    break;
1518  case tok::kw__Decimal128:
1519    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1520                                   DiagID);
1521    break;
1522
1523  // class-specifier:
1524  case tok::kw_class:
1525  case tok::kw_struct:
1526  case tok::kw_union: {
1527    tok::TokenKind Kind = Tok.getKind();
1528    ConsumeToken();
1529    ParseClassSpecifier(Kind, Loc, DS, TemplateInfo);
1530    return true;
1531  }
1532
1533  // enum-specifier:
1534  case tok::kw_enum:
1535    ConsumeToken();
1536    ParseEnumSpecifier(Loc, DS);
1537    return true;
1538
1539  // cv-qualifier:
1540  case tok::kw_const:
1541    isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
1542                               DiagID, getLang());
1543    break;
1544  case tok::kw_volatile:
1545    isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
1546                               DiagID, getLang());
1547    break;
1548  case tok::kw_restrict:
1549    isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1550                               DiagID, getLang());
1551    break;
1552
1553  // GNU typeof support.
1554  case tok::kw_typeof:
1555    ParseTypeofSpecifier(DS);
1556    return true;
1557
1558  // C++0x decltype support.
1559  case tok::kw_decltype:
1560    ParseDecltypeSpecifier(DS);
1561    return true;
1562
1563  // C++0x auto support.
1564  case tok::kw_auto:
1565    if (!getLang().CPlusPlus0x)
1566      return false;
1567
1568    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID);
1569    break;
1570  case tok::kw___ptr64:
1571  case tok::kw___w64:
1572  case tok::kw___cdecl:
1573  case tok::kw___stdcall:
1574  case tok::kw___fastcall:
1575    DS.AddAttributes(ParseMicrosoftTypeAttributes());
1576    return true;
1577
1578  default:
1579    // Not a type-specifier; do nothing.
1580    return false;
1581  }
1582
1583  // If the specifier combination wasn't legal, issue a diagnostic.
1584  if (isInvalid) {
1585    assert(PrevSpec && "Method did not return previous specifier!");
1586    // Pick between error or extwarn.
1587    Diag(Tok, DiagID) << PrevSpec;
1588  }
1589  DS.SetRangeEnd(Tok.getLocation());
1590  ConsumeToken(); // whatever we parsed above.
1591  return true;
1592}
1593
1594/// ParseStructDeclaration - Parse a struct declaration without the terminating
1595/// semicolon.
1596///
1597///       struct-declaration:
1598///         specifier-qualifier-list struct-declarator-list
1599/// [GNU]   __extension__ struct-declaration
1600/// [GNU]   specifier-qualifier-list
1601///       struct-declarator-list:
1602///         struct-declarator
1603///         struct-declarator-list ',' struct-declarator
1604/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
1605///       struct-declarator:
1606///         declarator
1607/// [GNU]   declarator attributes[opt]
1608///         declarator[opt] ':' constant-expression
1609/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
1610///
1611void Parser::
1612ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) {
1613  if (Tok.is(tok::kw___extension__)) {
1614    // __extension__ silences extension warnings in the subexpression.
1615    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1616    ConsumeToken();
1617    return ParseStructDeclaration(DS, Fields);
1618  }
1619
1620  // Parse the common specifier-qualifiers-list piece.
1621  SourceLocation DSStart = Tok.getLocation();
1622  ParseSpecifierQualifierList(DS);
1623
1624  // If there are no declarators, this is a free-standing declaration
1625  // specifier. Let the actions module cope with it.
1626  if (Tok.is(tok::semi)) {
1627    Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
1628    return;
1629  }
1630
1631  // Read struct-declarators until we find the semicolon.
1632  bool FirstDeclarator = true;
1633  while (1) {
1634    ParsingDeclRAIIObject PD(*this);
1635    FieldDeclarator DeclaratorInfo(DS);
1636
1637    // Attributes are only allowed here on successive declarators.
1638    if (!FirstDeclarator && Tok.is(tok::kw___attribute)) {
1639      SourceLocation Loc;
1640      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1641      DeclaratorInfo.D.AddAttributes(AttrList, Loc);
1642    }
1643
1644    /// struct-declarator: declarator
1645    /// struct-declarator: declarator[opt] ':' constant-expression
1646    if (Tok.isNot(tok::colon)) {
1647      // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
1648      ColonProtectionRAIIObject X(*this);
1649      ParseDeclarator(DeclaratorInfo.D);
1650    }
1651
1652    if (Tok.is(tok::colon)) {
1653      ConsumeToken();
1654      OwningExprResult Res(ParseConstantExpression());
1655      if (Res.isInvalid())
1656        SkipUntil(tok::semi, true, true);
1657      else
1658        DeclaratorInfo.BitfieldSize = Res.release();
1659    }
1660
1661    // If attributes exist after the declarator, parse them.
1662    if (Tok.is(tok::kw___attribute)) {
1663      SourceLocation Loc;
1664      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1665      DeclaratorInfo.D.AddAttributes(AttrList, Loc);
1666    }
1667
1668    // We're done with this declarator;  invoke the callback.
1669    DeclPtrTy D = Fields.invoke(DeclaratorInfo);
1670    PD.complete(D);
1671
1672    // If we don't have a comma, it is either the end of the list (a ';')
1673    // or an error, bail out.
1674    if (Tok.isNot(tok::comma))
1675      return;
1676
1677    // Consume the comma.
1678    ConsumeToken();
1679
1680    FirstDeclarator = false;
1681  }
1682}
1683
1684/// ParseStructUnionBody
1685///       struct-contents:
1686///         struct-declaration-list
1687/// [EXT]   empty
1688/// [GNU]   "struct-declaration-list" without terminatoring ';'
1689///       struct-declaration-list:
1690///         struct-declaration
1691///         struct-declaration-list struct-declaration
1692/// [OBC]   '@' 'defs' '(' class-name ')'
1693///
1694void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
1695                                  unsigned TagType, DeclPtrTy TagDecl) {
1696  PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions,
1697                                        PP.getSourceManager(),
1698                                        "parsing struct/union body");
1699
1700  SourceLocation LBraceLoc = ConsumeBrace();
1701
1702  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
1703  Actions.ActOnTagStartDefinition(CurScope, TagDecl);
1704
1705  // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
1706  // C++.
1707  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1708    Diag(Tok, diag::ext_empty_struct_union_enum)
1709      << DeclSpec::getSpecifierName((DeclSpec::TST)TagType);
1710
1711  llvm::SmallVector<DeclPtrTy, 32> FieldDecls;
1712
1713  // While we still have something to read, read the declarations in the struct.
1714  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1715    // Each iteration of this loop reads one struct-declaration.
1716
1717    // Check for extraneous top-level semicolon.
1718    if (Tok.is(tok::semi)) {
1719      Diag(Tok, diag::ext_extra_struct_semi)
1720        << CodeModificationHint::CreateRemoval(Tok.getLocation());
1721      ConsumeToken();
1722      continue;
1723    }
1724
1725    // Parse all the comma separated declarators.
1726    DeclSpec DS;
1727
1728    if (!Tok.is(tok::at)) {
1729      struct CFieldCallback : FieldCallback {
1730        Parser &P;
1731        DeclPtrTy TagDecl;
1732        llvm::SmallVectorImpl<DeclPtrTy> &FieldDecls;
1733
1734        CFieldCallback(Parser &P, DeclPtrTy TagDecl,
1735                       llvm::SmallVectorImpl<DeclPtrTy> &FieldDecls) :
1736          P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
1737
1738        virtual DeclPtrTy invoke(FieldDeclarator &FD) {
1739          // Install the declarator into the current TagDecl.
1740          DeclPtrTy Field = P.Actions.ActOnField(P.CurScope, TagDecl,
1741                              FD.D.getDeclSpec().getSourceRange().getBegin(),
1742                                                 FD.D, FD.BitfieldSize);
1743          FieldDecls.push_back(Field);
1744          return Field;
1745        }
1746      } Callback(*this, TagDecl, FieldDecls);
1747
1748      ParseStructDeclaration(DS, Callback);
1749    } else { // Handle @defs
1750      ConsumeToken();
1751      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
1752        Diag(Tok, diag::err_unexpected_at);
1753        SkipUntil(tok::semi, true);
1754        continue;
1755      }
1756      ConsumeToken();
1757      ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
1758      if (!Tok.is(tok::identifier)) {
1759        Diag(Tok, diag::err_expected_ident);
1760        SkipUntil(tok::semi, true);
1761        continue;
1762      }
1763      llvm::SmallVector<DeclPtrTy, 16> Fields;
1764      Actions.ActOnDefs(CurScope, TagDecl, Tok.getLocation(),
1765                        Tok.getIdentifierInfo(), Fields);
1766      FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
1767      ConsumeToken();
1768      ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
1769    }
1770
1771    if (Tok.is(tok::semi)) {
1772      ConsumeToken();
1773    } else if (Tok.is(tok::r_brace)) {
1774      ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
1775      break;
1776    } else {
1777      ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
1778      // Skip to end of block or statement to avoid ext-warning on extra ';'.
1779      SkipUntil(tok::r_brace, true, true);
1780      // If we stopped at a ';', eat it.
1781      if (Tok.is(tok::semi)) ConsumeToken();
1782    }
1783  }
1784
1785  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1786
1787  AttributeList *AttrList = 0;
1788  // If attributes exist after struct contents, parse them.
1789  if (Tok.is(tok::kw___attribute))
1790    AttrList = ParseGNUAttributes();
1791
1792  Actions.ActOnFields(CurScope,
1793                      RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(),
1794                      LBraceLoc, RBraceLoc,
1795                      AttrList);
1796  StructScope.Exit();
1797  Actions.ActOnTagFinishDefinition(CurScope, TagDecl, RBraceLoc);
1798}
1799
1800
1801/// ParseEnumSpecifier
1802///       enum-specifier: [C99 6.7.2.2]
1803///         'enum' identifier[opt] '{' enumerator-list '}'
1804///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
1805/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
1806///                                                 '}' attributes[opt]
1807///         'enum' identifier
1808/// [GNU]   'enum' attributes[opt] identifier
1809///
1810/// [C++] elaborated-type-specifier:
1811/// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
1812///
1813void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
1814                                AccessSpecifier AS) {
1815  // Parse the tag portion of this.
1816  if (Tok.is(tok::code_completion)) {
1817    // Code completion for an enum name.
1818    Actions.CodeCompleteTag(CurScope, DeclSpec::TST_enum);
1819    ConsumeToken();
1820  }
1821
1822  AttributeList *Attr = 0;
1823  // If attributes exist after tag, parse them.
1824  if (Tok.is(tok::kw___attribute))
1825    Attr = ParseGNUAttributes();
1826
1827  CXXScopeSpec SS;
1828  if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS, 0, false)) {
1829    if (Tok.isNot(tok::identifier)) {
1830      Diag(Tok, diag::err_expected_ident);
1831      if (Tok.isNot(tok::l_brace)) {
1832        // Has no name and is not a definition.
1833        // Skip the rest of this declarator, up until the comma or semicolon.
1834        SkipUntil(tok::comma, true);
1835        return;
1836      }
1837    }
1838  }
1839
1840  // Must have either 'enum name' or 'enum {...}'.
1841  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) {
1842    Diag(Tok, diag::err_expected_ident_lbrace);
1843
1844    // Skip the rest of this declarator, up until the comma or semicolon.
1845    SkipUntil(tok::comma, true);
1846    return;
1847  }
1848
1849  // If an identifier is present, consume and remember it.
1850  IdentifierInfo *Name = 0;
1851  SourceLocation NameLoc;
1852  if (Tok.is(tok::identifier)) {
1853    Name = Tok.getIdentifierInfo();
1854    NameLoc = ConsumeToken();
1855  }
1856
1857  // There are three options here.  If we have 'enum foo;', then this is a
1858  // forward declaration.  If we have 'enum foo {...' then this is a
1859  // definition. Otherwise we have something like 'enum foo xyz', a reference.
1860  //
1861  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
1862  // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
1863  // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
1864  //
1865  Action::TagUseKind TUK;
1866  if (Tok.is(tok::l_brace))
1867    TUK = Action::TUK_Definition;
1868  else if (Tok.is(tok::semi))
1869    TUK = Action::TUK_Declaration;
1870  else
1871    TUK = Action::TUK_Reference;
1872  bool Owned = false;
1873  bool IsDependent = false;
1874  DeclPtrTy TagDecl = Actions.ActOnTag(CurScope, DeclSpec::TST_enum, TUK,
1875                                       StartLoc, SS, Name, NameLoc, Attr, AS,
1876                                       Action::MultiTemplateParamsArg(Actions),
1877                                       Owned, IsDependent);
1878  assert(!IsDependent && "didn't expect dependent enum");
1879
1880  if (Tok.is(tok::l_brace))
1881    ParseEnumBody(StartLoc, TagDecl);
1882
1883  // FIXME: The DeclSpec should keep the locations of both the keyword and the
1884  // name (if there is one).
1885  SourceLocation TSTLoc = NameLoc.isValid()? NameLoc : StartLoc;
1886  const char *PrevSpec = 0;
1887  unsigned DiagID;
1888  if (DS.SetTypeSpecType(DeclSpec::TST_enum, TSTLoc, PrevSpec, DiagID,
1889                         TagDecl.getAs<void>(), Owned))
1890    Diag(StartLoc, DiagID) << PrevSpec;
1891}
1892
1893/// ParseEnumBody - Parse a {} enclosed enumerator-list.
1894///       enumerator-list:
1895///         enumerator
1896///         enumerator-list ',' enumerator
1897///       enumerator:
1898///         enumeration-constant
1899///         enumeration-constant '=' constant-expression
1900///       enumeration-constant:
1901///         identifier
1902///
1903void Parser::ParseEnumBody(SourceLocation StartLoc, DeclPtrTy EnumDecl) {
1904  // Enter the scope of the enum body and start the definition.
1905  ParseScope EnumScope(this, Scope::DeclScope);
1906  Actions.ActOnTagStartDefinition(CurScope, EnumDecl);
1907
1908  SourceLocation LBraceLoc = ConsumeBrace();
1909
1910  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
1911  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1912    Diag(Tok, diag::ext_empty_struct_union_enum) << "enum";
1913
1914  llvm::SmallVector<DeclPtrTy, 32> EnumConstantDecls;
1915
1916  DeclPtrTy LastEnumConstDecl;
1917
1918  // Parse the enumerator-list.
1919  while (Tok.is(tok::identifier)) {
1920    IdentifierInfo *Ident = Tok.getIdentifierInfo();
1921    SourceLocation IdentLoc = ConsumeToken();
1922
1923    SourceLocation EqualLoc;
1924    OwningExprResult AssignedVal(Actions);
1925    if (Tok.is(tok::equal)) {
1926      EqualLoc = ConsumeToken();
1927      AssignedVal = ParseConstantExpression();
1928      if (AssignedVal.isInvalid())
1929        SkipUntil(tok::comma, tok::r_brace, true, true);
1930    }
1931
1932    // Install the enumerator constant into EnumDecl.
1933    DeclPtrTy EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl,
1934                                                        LastEnumConstDecl,
1935                                                        IdentLoc, Ident,
1936                                                        EqualLoc,
1937                                                        AssignedVal.release());
1938    EnumConstantDecls.push_back(EnumConstDecl);
1939    LastEnumConstDecl = EnumConstDecl;
1940
1941    if (Tok.isNot(tok::comma))
1942      break;
1943    SourceLocation CommaLoc = ConsumeToken();
1944
1945    if (Tok.isNot(tok::identifier) &&
1946        !(getLang().C99 || getLang().CPlusPlus0x))
1947      Diag(CommaLoc, diag::ext_enumerator_list_comma)
1948        << getLang().CPlusPlus
1949        << CodeModificationHint::CreateRemoval(CommaLoc);
1950  }
1951
1952  // Eat the }.
1953  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1954
1955  AttributeList *Attr = 0;
1956  // If attributes exist after the identifier list, parse them.
1957  if (Tok.is(tok::kw___attribute))
1958    Attr = ParseGNUAttributes(); // FIXME: where do they do?
1959
1960  Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl,
1961                        EnumConstantDecls.data(), EnumConstantDecls.size(),
1962                        CurScope, Attr);
1963
1964  EnumScope.Exit();
1965  Actions.ActOnTagFinishDefinition(CurScope, EnumDecl, RBraceLoc);
1966}
1967
1968/// isTypeSpecifierQualifier - Return true if the current token could be the
1969/// start of a type-qualifier-list.
1970bool Parser::isTypeQualifier() const {
1971  switch (Tok.getKind()) {
1972  default: return false;
1973    // type-qualifier
1974  case tok::kw_const:
1975  case tok::kw_volatile:
1976  case tok::kw_restrict:
1977    return true;
1978  }
1979}
1980
1981/// isTypeSpecifierQualifier - Return true if the current token could be the
1982/// start of a specifier-qualifier-list.
1983bool Parser::isTypeSpecifierQualifier() {
1984  switch (Tok.getKind()) {
1985  default: return false;
1986
1987  case tok::identifier:   // foo::bar
1988  case tok::kw_typename:  // typename T::type
1989    // Annotate typenames and C++ scope specifiers.  If we get one, just
1990    // recurse to handle whatever we get.
1991    if (TryAnnotateTypeOrScopeToken())
1992      return isTypeSpecifierQualifier();
1993    // Otherwise, not a type specifier.
1994    return false;
1995
1996  case tok::coloncolon:   // ::foo::bar
1997    if (NextToken().is(tok::kw_new) ||    // ::new
1998        NextToken().is(tok::kw_delete))   // ::delete
1999      return false;
2000
2001    // Annotate typenames and C++ scope specifiers.  If we get one, just
2002    // recurse to handle whatever we get.
2003    if (TryAnnotateTypeOrScopeToken())
2004      return isTypeSpecifierQualifier();
2005    // Otherwise, not a type specifier.
2006    return false;
2007
2008    // GNU attributes support.
2009  case tok::kw___attribute:
2010    // GNU typeof support.
2011  case tok::kw_typeof:
2012
2013    // type-specifiers
2014  case tok::kw_short:
2015  case tok::kw_long:
2016  case tok::kw_signed:
2017  case tok::kw_unsigned:
2018  case tok::kw__Complex:
2019  case tok::kw__Imaginary:
2020  case tok::kw_void:
2021  case tok::kw_char:
2022  case tok::kw_wchar_t:
2023  case tok::kw_char16_t:
2024  case tok::kw_char32_t:
2025  case tok::kw_int:
2026  case tok::kw_float:
2027  case tok::kw_double:
2028  case tok::kw_bool:
2029  case tok::kw__Bool:
2030  case tok::kw__Decimal32:
2031  case tok::kw__Decimal64:
2032  case tok::kw__Decimal128:
2033
2034    // struct-or-union-specifier (C99) or class-specifier (C++)
2035  case tok::kw_class:
2036  case tok::kw_struct:
2037  case tok::kw_union:
2038    // enum-specifier
2039  case tok::kw_enum:
2040
2041    // type-qualifier
2042  case tok::kw_const:
2043  case tok::kw_volatile:
2044  case tok::kw_restrict:
2045
2046    // typedef-name
2047  case tok::annot_typename:
2048    return true;
2049
2050    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2051  case tok::less:
2052    return getLang().ObjC1;
2053
2054  case tok::kw___cdecl:
2055  case tok::kw___stdcall:
2056  case tok::kw___fastcall:
2057  case tok::kw___w64:
2058  case tok::kw___ptr64:
2059    return true;
2060  }
2061}
2062
2063/// isDeclarationSpecifier() - Return true if the current token is part of a
2064/// declaration specifier.
2065bool Parser::isDeclarationSpecifier() {
2066  switch (Tok.getKind()) {
2067  default: return false;
2068
2069  case tok::identifier:   // foo::bar
2070    // Unfortunate hack to support "Class.factoryMethod" notation.
2071    if (getLang().ObjC1 && NextToken().is(tok::period))
2072      return false;
2073    // Fall through
2074
2075  case tok::kw_typename: // typename T::type
2076    // Annotate typenames and C++ scope specifiers.  If we get one, just
2077    // recurse to handle whatever we get.
2078    if (TryAnnotateTypeOrScopeToken())
2079      return isDeclarationSpecifier();
2080    // Otherwise, not a declaration specifier.
2081    return false;
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    // Annotate typenames and C++ scope specifiers.  If we get one, just
2088    // recurse to handle whatever we get.
2089    if (TryAnnotateTypeOrScopeToken())
2090      return isDeclarationSpecifier();
2091    // Otherwise, not a declaration specifier.
2092    return false;
2093
2094    // storage-class-specifier
2095  case tok::kw_typedef:
2096  case tok::kw_extern:
2097  case tok::kw___private_extern__:
2098  case tok::kw_static:
2099  case tok::kw_auto:
2100  case tok::kw_register:
2101  case tok::kw___thread:
2102
2103    // type-specifiers
2104  case tok::kw_short:
2105  case tok::kw_long:
2106  case tok::kw_signed:
2107  case tok::kw_unsigned:
2108  case tok::kw__Complex:
2109  case tok::kw__Imaginary:
2110  case tok::kw_void:
2111  case tok::kw_char:
2112  case tok::kw_wchar_t:
2113  case tok::kw_char16_t:
2114  case tok::kw_char32_t:
2115
2116  case tok::kw_int:
2117  case tok::kw_float:
2118  case tok::kw_double:
2119  case tok::kw_bool:
2120  case tok::kw__Bool:
2121  case tok::kw__Decimal32:
2122  case tok::kw__Decimal64:
2123  case tok::kw__Decimal128:
2124
2125    // struct-or-union-specifier (C99) or class-specifier (C++)
2126  case tok::kw_class:
2127  case tok::kw_struct:
2128  case tok::kw_union:
2129    // enum-specifier
2130  case tok::kw_enum:
2131
2132    // type-qualifier
2133  case tok::kw_const:
2134  case tok::kw_volatile:
2135  case tok::kw_restrict:
2136
2137    // function-specifier
2138  case tok::kw_inline:
2139  case tok::kw_virtual:
2140  case tok::kw_explicit:
2141
2142    // typedef-name
2143  case tok::annot_typename:
2144
2145    // GNU typeof support.
2146  case tok::kw_typeof:
2147
2148    // GNU attributes.
2149  case tok::kw___attribute:
2150    return true;
2151
2152    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2153  case tok::less:
2154    return getLang().ObjC1;
2155
2156  case tok::kw___declspec:
2157  case tok::kw___cdecl:
2158  case tok::kw___stdcall:
2159  case tok::kw___fastcall:
2160  case tok::kw___w64:
2161  case tok::kw___ptr64:
2162  case tok::kw___forceinline:
2163    return true;
2164  }
2165}
2166
2167bool Parser::isConstructorDeclarator() {
2168  TentativeParsingAction TPA(*this);
2169
2170  // Parse the C++ scope specifier.
2171  CXXScopeSpec SS;
2172  ParseOptionalCXXScopeSpecifier(SS, 0, true);
2173
2174  // Parse the constructor name.
2175  if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
2176    // We already know that we have a constructor name; just consume
2177    // the token.
2178    ConsumeToken();
2179  } else {
2180    TPA.Revert();
2181    return false;
2182  }
2183
2184  // Current class name must be followed by a left parentheses.
2185  if (Tok.isNot(tok::l_paren)) {
2186    TPA.Revert();
2187    return false;
2188  }
2189  ConsumeParen();
2190
2191  // A right parentheses or ellipsis signals that we have a constructor.
2192  if (Tok.is(tok::r_paren) || Tok.is(tok::ellipsis)) {
2193    TPA.Revert();
2194    return true;
2195  }
2196
2197  // If we need to, enter the specified scope.
2198  DeclaratorScopeObj DeclScopeObj(*this, SS);
2199  if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(CurScope, SS))
2200    DeclScopeObj.EnterDeclaratorScope();
2201
2202  // Check whether the next token(s) are part of a declaration
2203  // specifier, in which case we have the start of a parameter and,
2204  // therefore, we know that this is a constructor.
2205  bool IsConstructor = isDeclarationSpecifier();
2206  TPA.Revert();
2207  return IsConstructor;
2208}
2209
2210/// ParseTypeQualifierListOpt
2211///       type-qualifier-list: [C99 6.7.5]
2212///         type-qualifier
2213/// [GNU]   attributes                        [ only if AttributesAllowed=true ]
2214///         type-qualifier-list type-qualifier
2215/// [GNU]   type-qualifier-list attributes    [ only if AttributesAllowed=true ]
2216/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
2217///           if CXX0XAttributesAllowed = true
2218///
2219void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, bool GNUAttributesAllowed,
2220                                       bool CXX0XAttributesAllowed) {
2221  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
2222    SourceLocation Loc = Tok.getLocation();
2223    CXX0XAttributeList Attr = ParseCXX0XAttributes();
2224    if (CXX0XAttributesAllowed)
2225      DS.AddAttributes(Attr.AttrList);
2226    else
2227      Diag(Loc, diag::err_attributes_not_allowed);
2228  }
2229
2230  while (1) {
2231    bool isInvalid = false;
2232    const char *PrevSpec = 0;
2233    unsigned DiagID = 0;
2234    SourceLocation Loc = Tok.getLocation();
2235
2236    switch (Tok.getKind()) {
2237    case tok::kw_const:
2238      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec, DiagID,
2239                                 getLang());
2240      break;
2241    case tok::kw_volatile:
2242      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
2243                                 getLang());
2244      break;
2245    case tok::kw_restrict:
2246      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
2247                                 getLang());
2248      break;
2249    case tok::kw___w64:
2250    case tok::kw___ptr64:
2251    case tok::kw___cdecl:
2252    case tok::kw___stdcall:
2253    case tok::kw___fastcall:
2254      if (GNUAttributesAllowed) {
2255        DS.AddAttributes(ParseMicrosoftTypeAttributes());
2256        continue;
2257      }
2258      goto DoneWithTypeQuals;
2259    case tok::kw___attribute:
2260      if (GNUAttributesAllowed) {
2261        DS.AddAttributes(ParseGNUAttributes());
2262        continue; // do *not* consume the next token!
2263      }
2264      // otherwise, FALL THROUGH!
2265    default:
2266      DoneWithTypeQuals:
2267      // If this is not a type-qualifier token, we're done reading type
2268      // qualifiers.  First verify that DeclSpec's are consistent.
2269      DS.Finish(Diags, PP);
2270      return;
2271    }
2272
2273    // If the specifier combination wasn't legal, issue a diagnostic.
2274    if (isInvalid) {
2275      assert(PrevSpec && "Method did not return previous specifier!");
2276      Diag(Tok, DiagID) << PrevSpec;
2277    }
2278    ConsumeToken();
2279  }
2280}
2281
2282
2283/// ParseDeclarator - Parse and verify a newly-initialized declarator.
2284///
2285void Parser::ParseDeclarator(Declarator &D) {
2286  /// This implements the 'declarator' production in the C grammar, then checks
2287  /// for well-formedness and issues diagnostics.
2288  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
2289}
2290
2291/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
2292/// is parsed by the function passed to it. Pass null, and the direct-declarator
2293/// isn't parsed at all, making this function effectively parse the C++
2294/// ptr-operator production.
2295///
2296///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
2297/// [C]     pointer[opt] direct-declarator
2298/// [C++]   direct-declarator
2299/// [C++]   ptr-operator declarator
2300///
2301///       pointer: [C99 6.7.5]
2302///         '*' type-qualifier-list[opt]
2303///         '*' type-qualifier-list[opt] pointer
2304///
2305///       ptr-operator:
2306///         '*' cv-qualifier-seq[opt]
2307///         '&'
2308/// [C++0x] '&&'
2309/// [GNU]   '&' restrict[opt] attributes[opt]
2310/// [GNU?]  '&&' restrict[opt] attributes[opt]
2311///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
2312void Parser::ParseDeclaratorInternal(Declarator &D,
2313                                     DirectDeclParseFunction DirectDeclParser) {
2314  if (Diags.hasAllExtensionsSilenced())
2315    D.setExtension();
2316  // C++ member pointers start with a '::' or a nested-name.
2317  // Member pointers get special handling, since there's no place for the
2318  // scope spec in the generic path below.
2319  if (getLang().CPlusPlus &&
2320      (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
2321       Tok.is(tok::annot_cxxscope))) {
2322    CXXScopeSpec SS;
2323    if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true)) {
2324      if (Tok.isNot(tok::star)) {
2325        // The scope spec really belongs to the direct-declarator.
2326        D.getCXXScopeSpec() = SS;
2327        if (DirectDeclParser)
2328          (this->*DirectDeclParser)(D);
2329        return;
2330      }
2331
2332      SourceLocation Loc = ConsumeToken();
2333      D.SetRangeEnd(Loc);
2334      DeclSpec DS;
2335      ParseTypeQualifierListOpt(DS);
2336      D.ExtendWithDeclSpec(DS);
2337
2338      // Recurse to parse whatever is left.
2339      ParseDeclaratorInternal(D, DirectDeclParser);
2340
2341      // Sema will have to catch (syntactically invalid) pointers into global
2342      // scope. It has to catch pointers into namespace scope anyway.
2343      D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
2344                                                      Loc, DS.TakeAttributes()),
2345                    /* Don't replace range end. */SourceLocation());
2346      return;
2347    }
2348  }
2349
2350  tok::TokenKind Kind = Tok.getKind();
2351  // Not a pointer, C++ reference, or block.
2352  if (Kind != tok::star && Kind != tok::caret &&
2353      (Kind != tok::amp || !getLang().CPlusPlus) &&
2354      // We parse rvalue refs in C++03, because otherwise the errors are scary.
2355      (Kind != tok::ampamp || !getLang().CPlusPlus)) {
2356    if (DirectDeclParser)
2357      (this->*DirectDeclParser)(D);
2358    return;
2359  }
2360
2361  // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
2362  // '&&' -> rvalue reference
2363  SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
2364  D.SetRangeEnd(Loc);
2365
2366  if (Kind == tok::star || Kind == tok::caret) {
2367    // Is a pointer.
2368    DeclSpec DS;
2369
2370    ParseTypeQualifierListOpt(DS);
2371    D.ExtendWithDeclSpec(DS);
2372
2373    // Recursively parse the declarator.
2374    ParseDeclaratorInternal(D, DirectDeclParser);
2375    if (Kind == tok::star)
2376      // Remember that we parsed a pointer type, and remember the type-quals.
2377      D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
2378                                                DS.TakeAttributes()),
2379                    SourceLocation());
2380    else
2381      // Remember that we parsed a Block type, and remember the type-quals.
2382      D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
2383                                                     Loc, DS.TakeAttributes()),
2384                    SourceLocation());
2385  } else {
2386    // Is a reference
2387    DeclSpec DS;
2388
2389    // Complain about rvalue references in C++03, but then go on and build
2390    // the declarator.
2391    if (Kind == tok::ampamp && !getLang().CPlusPlus0x)
2392      Diag(Loc, diag::err_rvalue_reference);
2393
2394    // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
2395    // cv-qualifiers are introduced through the use of a typedef or of a
2396    // template type argument, in which case the cv-qualifiers are ignored.
2397    //
2398    // [GNU] Retricted references are allowed.
2399    // [GNU] Attributes on references are allowed.
2400    // [C++0x] Attributes on references are not allowed.
2401    ParseTypeQualifierListOpt(DS, true, false);
2402    D.ExtendWithDeclSpec(DS);
2403
2404    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2405      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2406        Diag(DS.getConstSpecLoc(),
2407             diag::err_invalid_reference_qualifier_application) << "const";
2408      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2409        Diag(DS.getVolatileSpecLoc(),
2410             diag::err_invalid_reference_qualifier_application) << "volatile";
2411    }
2412
2413    // Recursively parse the declarator.
2414    ParseDeclaratorInternal(D, DirectDeclParser);
2415
2416    if (D.getNumTypeObjects() > 0) {
2417      // C++ [dcl.ref]p4: There shall be no references to references.
2418      DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
2419      if (InnerChunk.Kind == DeclaratorChunk::Reference) {
2420        if (const IdentifierInfo *II = D.getIdentifier())
2421          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
2422           << II;
2423        else
2424          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
2425            << "type name";
2426
2427        // Once we've complained about the reference-to-reference, we
2428        // can go ahead and build the (technically ill-formed)
2429        // declarator: reference collapsing will take care of it.
2430      }
2431    }
2432
2433    // Remember that we parsed a reference type. It doesn't have type-quals.
2434    D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
2435                                                DS.TakeAttributes(),
2436                                                Kind == tok::amp),
2437                  SourceLocation());
2438  }
2439}
2440
2441/// ParseDirectDeclarator
2442///       direct-declarator: [C99 6.7.5]
2443/// [C99]   identifier
2444///         '(' declarator ')'
2445/// [GNU]   '(' attributes declarator ')'
2446/// [C90]   direct-declarator '[' constant-expression[opt] ']'
2447/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2448/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2449/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2450/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
2451///         direct-declarator '(' parameter-type-list ')'
2452///         direct-declarator '(' identifier-list[opt] ')'
2453/// [GNU]   direct-declarator '(' parameter-forward-declarations
2454///                    parameter-type-list[opt] ')'
2455/// [C++]   direct-declarator '(' parameter-declaration-clause ')'
2456///                    cv-qualifier-seq[opt] exception-specification[opt]
2457/// [C++]   declarator-id
2458///
2459///       declarator-id: [C++ 8]
2460///         id-expression
2461///         '::'[opt] nested-name-specifier[opt] type-name
2462///
2463///       id-expression: [C++ 5.1]
2464///         unqualified-id
2465///         qualified-id
2466///
2467///       unqualified-id: [C++ 5.1]
2468///         identifier
2469///         operator-function-id
2470///         conversion-function-id
2471///          '~' class-name
2472///         template-id
2473///
2474void Parser::ParseDirectDeclarator(Declarator &D) {
2475  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
2476
2477  if (getLang().CPlusPlus && D.mayHaveIdentifier()) {
2478    // ParseDeclaratorInternal might already have parsed the scope.
2479    bool afterCXXScope = D.getCXXScopeSpec().isSet() ||
2480      ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), /*ObjectType=*/0,
2481                                     true);
2482    if (afterCXXScope) {
2483      if (Actions.ShouldEnterDeclaratorScope(CurScope, D.getCXXScopeSpec()))
2484        // Change the declaration context for name lookup, until this function
2485        // is exited (and the declarator has been parsed).
2486        DeclScopeObj.EnterDeclaratorScope();
2487    }
2488
2489    if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
2490        Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
2491      // We found something that indicates the start of an unqualified-id.
2492      // Parse that unqualified-id.
2493      bool AllowConstructorName
2494        = ((D.getCXXScopeSpec().isSet() &&
2495            D.getContext() == Declarator::FileContext) ||
2496           (!D.getCXXScopeSpec().isSet() &&
2497            D.getContext() == Declarator::MemberContext)) &&
2498        !D.getDeclSpec().hasTypeSpecifier();
2499      if (ParseUnqualifiedId(D.getCXXScopeSpec(),
2500                             /*EnteringContext=*/true,
2501                             /*AllowDestructorName=*/true,
2502                             AllowConstructorName,
2503                             /*ObjectType=*/0,
2504                             D.getName())) {
2505        D.SetIdentifier(0, Tok.getLocation());
2506        D.setInvalidType(true);
2507      } else {
2508        // Parsed the unqualified-id; update range information and move along.
2509        if (D.getSourceRange().getBegin().isInvalid())
2510          D.SetRangeBegin(D.getName().getSourceRange().getBegin());
2511        D.SetRangeEnd(D.getName().getSourceRange().getEnd());
2512      }
2513      goto PastIdentifier;
2514    }
2515  } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
2516    assert(!getLang().CPlusPlus &&
2517           "There's a C++-specific check for tok::identifier above");
2518    assert(Tok.getIdentifierInfo() && "Not an identifier?");
2519    D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2520    ConsumeToken();
2521    goto PastIdentifier;
2522  }
2523
2524  if (Tok.is(tok::l_paren)) {
2525    // direct-declarator: '(' declarator ')'
2526    // direct-declarator: '(' attributes declarator ')'
2527    // Example: 'char (*X)'   or 'int (*XX)(void)'
2528    ParseParenDeclarator(D);
2529
2530    // If the declarator was parenthesized, we entered the declarator
2531    // scope when parsing the parenthesized declarator, then exited
2532    // the scope already. Re-enter the scope, if we need to.
2533    if (D.getCXXScopeSpec().isSet()) {
2534      if (Actions.ShouldEnterDeclaratorScope(CurScope, D.getCXXScopeSpec()))
2535        // Change the declaration context for name lookup, until this function
2536        // is exited (and the declarator has been parsed).
2537        DeclScopeObj.EnterDeclaratorScope();
2538    }
2539  } else if (D.mayOmitIdentifier()) {
2540    // This could be something simple like "int" (in which case the declarator
2541    // portion is empty), if an abstract-declarator is allowed.
2542    D.SetIdentifier(0, Tok.getLocation());
2543  } else {
2544    if (D.getContext() == Declarator::MemberContext)
2545      Diag(Tok, diag::err_expected_member_name_or_semi)
2546        << D.getDeclSpec().getSourceRange();
2547    else if (getLang().CPlusPlus)
2548      Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus;
2549    else
2550      Diag(Tok, diag::err_expected_ident_lparen);
2551    D.SetIdentifier(0, Tok.getLocation());
2552    D.setInvalidType(true);
2553  }
2554
2555 PastIdentifier:
2556  assert(D.isPastIdentifier() &&
2557         "Haven't past the location of the identifier yet?");
2558
2559  // Don't parse attributes unless we have an identifier.
2560  if (D.getIdentifier() && getLang().CPlusPlus
2561   && isCXX0XAttributeSpecifier(true)) {
2562    SourceLocation AttrEndLoc;
2563    CXX0XAttributeList Attr = ParseCXX0XAttributes();
2564    D.AddAttributes(Attr.AttrList, AttrEndLoc);
2565  }
2566
2567  while (1) {
2568    if (Tok.is(tok::l_paren)) {
2569      // The paren may be part of a C++ direct initializer, eg. "int x(1);".
2570      // In such a case, check if we actually have a function declarator; if it
2571      // is not, the declarator has been fully parsed.
2572      if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
2573        // When not in file scope, warn for ambiguous function declarators, just
2574        // in case the author intended it as a variable definition.
2575        bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
2576        if (!isCXXFunctionDeclarator(warnIfAmbiguous))
2577          break;
2578      }
2579      ParseFunctionDeclarator(ConsumeParen(), D);
2580    } else if (Tok.is(tok::l_square)) {
2581      ParseBracketDeclarator(D);
2582    } else {
2583      break;
2584    }
2585  }
2586}
2587
2588/// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
2589/// only called before the identifier, so these are most likely just grouping
2590/// parens for precedence.  If we find that these are actually function
2591/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
2592///
2593///       direct-declarator:
2594///         '(' declarator ')'
2595/// [GNU]   '(' attributes declarator ')'
2596///         direct-declarator '(' parameter-type-list ')'
2597///         direct-declarator '(' identifier-list[opt] ')'
2598/// [GNU]   direct-declarator '(' parameter-forward-declarations
2599///                    parameter-type-list[opt] ')'
2600///
2601void Parser::ParseParenDeclarator(Declarator &D) {
2602  SourceLocation StartLoc = ConsumeParen();
2603  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
2604
2605  // Eat any attributes before we look at whether this is a grouping or function
2606  // declarator paren.  If this is a grouping paren, the attribute applies to
2607  // the type being built up, for example:
2608  //     int (__attribute__(()) *x)(long y)
2609  // If this ends up not being a grouping paren, the attribute applies to the
2610  // first argument, for example:
2611  //     int (__attribute__(()) int x)
2612  // In either case, we need to eat any attributes to be able to determine what
2613  // sort of paren this is.
2614  //
2615  AttributeList *AttrList = 0;
2616  bool RequiresArg = false;
2617  if (Tok.is(tok::kw___attribute)) {
2618    AttrList = ParseGNUAttributes();
2619
2620    // We require that the argument list (if this is a non-grouping paren) be
2621    // present even if the attribute list was empty.
2622    RequiresArg = true;
2623  }
2624  // Eat any Microsoft extensions.
2625  if  (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
2626       Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___w64) ||
2627       Tok.is(tok::kw___ptr64)) {
2628    AttrList = ParseMicrosoftTypeAttributes(AttrList);
2629  }
2630
2631  // If we haven't past the identifier yet (or where the identifier would be
2632  // stored, if this is an abstract declarator), then this is probably just
2633  // grouping parens. However, if this could be an abstract-declarator, then
2634  // this could also be the start of function arguments (consider 'void()').
2635  bool isGrouping;
2636
2637  if (!D.mayOmitIdentifier()) {
2638    // If this can't be an abstract-declarator, this *must* be a grouping
2639    // paren, because we haven't seen the identifier yet.
2640    isGrouping = true;
2641  } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
2642             (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
2643             isDeclarationSpecifier()) {       // 'int(int)' is a function.
2644    // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
2645    // considered to be a type, not a K&R identifier-list.
2646    isGrouping = false;
2647  } else {
2648    // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
2649    isGrouping = true;
2650  }
2651
2652  // If this is a grouping paren, handle:
2653  // direct-declarator: '(' declarator ')'
2654  // direct-declarator: '(' attributes declarator ')'
2655  if (isGrouping) {
2656    bool hadGroupingParens = D.hasGroupingParens();
2657    D.setGroupingParens(true);
2658    if (AttrList)
2659      D.AddAttributes(AttrList, SourceLocation());
2660
2661    ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
2662    // Match the ')'.
2663    SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, StartLoc);
2664
2665    D.setGroupingParens(hadGroupingParens);
2666    D.SetRangeEnd(Loc);
2667    return;
2668  }
2669
2670  // Okay, if this wasn't a grouping paren, it must be the start of a function
2671  // argument list.  Recognize that this declarator will never have an
2672  // identifier (and remember where it would have been), then call into
2673  // ParseFunctionDeclarator to handle of argument list.
2674  D.SetIdentifier(0, Tok.getLocation());
2675
2676  ParseFunctionDeclarator(StartLoc, D, AttrList, RequiresArg);
2677}
2678
2679/// ParseFunctionDeclarator - We are after the identifier and have parsed the
2680/// declarator D up to a paren, which indicates that we are parsing function
2681/// arguments.
2682///
2683/// If AttrList is non-null, then the caller parsed those arguments immediately
2684/// after the open paren - they should be considered to be the first argument of
2685/// a parameter.  If RequiresArg is true, then the first argument of the
2686/// function is required to be present and required to not be an identifier
2687/// list.
2688///
2689/// This method also handles this portion of the grammar:
2690///       parameter-type-list: [C99 6.7.5]
2691///         parameter-list
2692///         parameter-list ',' '...'
2693/// [C++]   parameter-list '...'
2694///
2695///       parameter-list: [C99 6.7.5]
2696///         parameter-declaration
2697///         parameter-list ',' parameter-declaration
2698///
2699///       parameter-declaration: [C99 6.7.5]
2700///         declaration-specifiers declarator
2701/// [C++]   declaration-specifiers declarator '=' assignment-expression
2702/// [GNU]   declaration-specifiers declarator attributes
2703///         declaration-specifiers abstract-declarator[opt]
2704/// [C++]   declaration-specifiers abstract-declarator[opt]
2705///           '=' assignment-expression
2706/// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
2707///
2708/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]"
2709/// and "exception-specification[opt]".
2710///
2711void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
2712                                     AttributeList *AttrList,
2713                                     bool RequiresArg) {
2714  // lparen is already consumed!
2715  assert(D.isPastIdentifier() && "Should not call before identifier!");
2716
2717  // This parameter list may be empty.
2718  if (Tok.is(tok::r_paren)) {
2719    if (RequiresArg) {
2720      Diag(Tok, diag::err_argument_required_after_attribute);
2721      delete AttrList;
2722    }
2723
2724    SourceLocation RParenLoc = ConsumeParen();  // Eat the closing ')'.
2725    SourceLocation EndLoc = RParenLoc;
2726
2727    // cv-qualifier-seq[opt].
2728    DeclSpec DS;
2729    bool hasExceptionSpec = false;
2730    SourceLocation ThrowLoc;
2731    bool hasAnyExceptionSpec = false;
2732    llvm::SmallVector<TypeTy*, 2> Exceptions;
2733    llvm::SmallVector<SourceRange, 2> ExceptionRanges;
2734    if (getLang().CPlusPlus) {
2735      ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2736      if (!DS.getSourceRange().getEnd().isInvalid())
2737        EndLoc = DS.getSourceRange().getEnd();
2738
2739      // Parse exception-specification[opt].
2740      if (Tok.is(tok::kw_throw)) {
2741        hasExceptionSpec = true;
2742        ThrowLoc = Tok.getLocation();
2743        ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges,
2744                                    hasAnyExceptionSpec);
2745        assert(Exceptions.size() == ExceptionRanges.size() &&
2746               "Produced different number of exception types and ranges.");
2747      }
2748    }
2749
2750    // Remember that we parsed a function type, and remember the attributes.
2751    // int() -> no prototype, no '...'.
2752    D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus,
2753                                               /*variadic*/ false,
2754                                               SourceLocation(),
2755                                               /*arglist*/ 0, 0,
2756                                               DS.getTypeQualifiers(),
2757                                               hasExceptionSpec, ThrowLoc,
2758                                               hasAnyExceptionSpec,
2759                                               Exceptions.data(),
2760                                               ExceptionRanges.data(),
2761                                               Exceptions.size(),
2762                                               LParenLoc, RParenLoc, D),
2763                  EndLoc);
2764    return;
2765  }
2766
2767  // Alternatively, this parameter list may be an identifier list form for a
2768  // K&R-style function:  void foo(a,b,c)
2769  if (!getLang().CPlusPlus && Tok.is(tok::identifier)) {
2770    if (!TryAnnotateTypeOrScopeToken()) {
2771      // K&R identifier lists can't have typedefs as identifiers, per
2772      // C99 6.7.5.3p11.
2773      if (RequiresArg) {
2774        Diag(Tok, diag::err_argument_required_after_attribute);
2775        delete AttrList;
2776      }
2777      // Identifier list.  Note that '(' identifier-list ')' is only allowed for
2778      // normal declarators, not for abstract-declarators.
2779      return ParseFunctionDeclaratorIdentifierList(LParenLoc, D);
2780    }
2781  }
2782
2783  // Finally, a normal, non-empty parameter type list.
2784
2785  // Build up an array of information about the parsed arguments.
2786  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
2787
2788  // Enter function-declaration scope, limiting any declarators to the
2789  // function prototype scope, including parameter declarators.
2790  ParseScope PrototypeScope(this,
2791                            Scope::FunctionPrototypeScope|Scope::DeclScope);
2792
2793  bool IsVariadic = false;
2794  SourceLocation EllipsisLoc;
2795  while (1) {
2796    if (Tok.is(tok::ellipsis)) {
2797      IsVariadic = true;
2798      EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
2799      break;
2800    }
2801
2802    SourceLocation DSStart = Tok.getLocation();
2803
2804    // Parse the declaration-specifiers.
2805    // Just use the ParsingDeclaration "scope" of the declarator.
2806    DeclSpec DS;
2807
2808    // If the caller parsed attributes for the first argument, add them now.
2809    if (AttrList) {
2810      DS.AddAttributes(AttrList);
2811      AttrList = 0;  // Only apply the attributes to the first parameter.
2812    }
2813    ParseDeclarationSpecifiers(DS);
2814
2815    // Parse the declarator.  This is "PrototypeContext", because we must
2816    // accept either 'declarator' or 'abstract-declarator' here.
2817    Declarator ParmDecl(DS, Declarator::PrototypeContext);
2818    ParseDeclarator(ParmDecl);
2819
2820    // Parse GNU attributes, if present.
2821    if (Tok.is(tok::kw___attribute)) {
2822      SourceLocation Loc;
2823      AttributeList *AttrList = ParseGNUAttributes(&Loc);
2824      ParmDecl.AddAttributes(AttrList, Loc);
2825    }
2826
2827    // Remember this parsed parameter in ParamInfo.
2828    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
2829
2830    // DefArgToks is used when the parsing of default arguments needs
2831    // to be delayed.
2832    CachedTokens *DefArgToks = 0;
2833
2834    // If no parameter was specified, verify that *something* was specified,
2835    // otherwise we have a missing type and identifier.
2836    if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
2837        ParmDecl.getNumTypeObjects() == 0) {
2838      // Completely missing, emit error.
2839      Diag(DSStart, diag::err_missing_param);
2840    } else {
2841      // Otherwise, we have something.  Add it and let semantic analysis try
2842      // to grok it and add the result to the ParamInfo we are building.
2843
2844      // Inform the actions module about the parameter declarator, so it gets
2845      // added to the current scope.
2846      DeclPtrTy Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl);
2847
2848      // Parse the default argument, if any. We parse the default
2849      // arguments in all dialects; the semantic analysis in
2850      // ActOnParamDefaultArgument will reject the default argument in
2851      // C.
2852      if (Tok.is(tok::equal)) {
2853        SourceLocation EqualLoc = Tok.getLocation();
2854
2855        // Parse the default argument
2856        if (D.getContext() == Declarator::MemberContext) {
2857          // If we're inside a class definition, cache the tokens
2858          // corresponding to the default argument. We'll actually parse
2859          // them when we see the end of the class definition.
2860          // FIXME: Templates will require something similar.
2861          // FIXME: Can we use a smart pointer for Toks?
2862          DefArgToks = new CachedTokens;
2863
2864          if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
2865                                    tok::semi, false)) {
2866            delete DefArgToks;
2867            DefArgToks = 0;
2868            Actions.ActOnParamDefaultArgumentError(Param);
2869          } else
2870            Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
2871                                                (*DefArgToks)[1].getLocation());
2872        } else {
2873          // Consume the '='.
2874          ConsumeToken();
2875
2876          OwningExprResult DefArgResult(ParseAssignmentExpression());
2877          if (DefArgResult.isInvalid()) {
2878            Actions.ActOnParamDefaultArgumentError(Param);
2879            SkipUntil(tok::comma, tok::r_paren, true, true);
2880          } else {
2881            // Inform the actions module about the default argument
2882            Actions.ActOnParamDefaultArgument(Param, EqualLoc,
2883                                              move(DefArgResult));
2884          }
2885        }
2886      }
2887
2888      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
2889                                          ParmDecl.getIdentifierLoc(), Param,
2890                                          DefArgToks));
2891    }
2892
2893    // If the next token is a comma, consume it and keep reading arguments.
2894    if (Tok.isNot(tok::comma)) {
2895      if (Tok.is(tok::ellipsis)) {
2896        IsVariadic = true;
2897        EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
2898
2899        if (!getLang().CPlusPlus) {
2900          // We have ellipsis without a preceding ',', which is ill-formed
2901          // in C. Complain and provide the fix.
2902          Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
2903            << CodeModificationHint::CreateInsertion(EllipsisLoc, ", ");
2904        }
2905      }
2906
2907      break;
2908    }
2909
2910    // Consume the comma.
2911    ConsumeToken();
2912  }
2913
2914  // Leave prototype scope.
2915  PrototypeScope.Exit();
2916
2917  // If we have the closing ')', eat it.
2918  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2919  SourceLocation EndLoc = RParenLoc;
2920
2921  DeclSpec DS;
2922  bool hasExceptionSpec = false;
2923  SourceLocation ThrowLoc;
2924  bool hasAnyExceptionSpec = false;
2925  llvm::SmallVector<TypeTy*, 2> Exceptions;
2926  llvm::SmallVector<SourceRange, 2> ExceptionRanges;
2927
2928  if (getLang().CPlusPlus) {
2929    // Parse cv-qualifier-seq[opt].
2930    ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2931      if (!DS.getSourceRange().getEnd().isInvalid())
2932        EndLoc = DS.getSourceRange().getEnd();
2933
2934    // Parse exception-specification[opt].
2935    if (Tok.is(tok::kw_throw)) {
2936      hasExceptionSpec = true;
2937      ThrowLoc = Tok.getLocation();
2938      ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges,
2939                                  hasAnyExceptionSpec);
2940      assert(Exceptions.size() == ExceptionRanges.size() &&
2941             "Produced different number of exception types and ranges.");
2942    }
2943  }
2944
2945  // Remember that we parsed a function type, and remember the attributes.
2946  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
2947                                             EllipsisLoc,
2948                                             ParamInfo.data(), ParamInfo.size(),
2949                                             DS.getTypeQualifiers(),
2950                                             hasExceptionSpec, ThrowLoc,
2951                                             hasAnyExceptionSpec,
2952                                             Exceptions.data(),
2953                                             ExceptionRanges.data(),
2954                                             Exceptions.size(),
2955                                             LParenLoc, RParenLoc, D),
2956                EndLoc);
2957}
2958
2959/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
2960/// we found a K&R-style identifier list instead of a type argument list.  The
2961/// current token is known to be the first identifier in the list.
2962///
2963///       identifier-list: [C99 6.7.5]
2964///         identifier
2965///         identifier-list ',' identifier
2966///
2967void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
2968                                                   Declarator &D) {
2969  // Build up an array of information about the parsed arguments.
2970  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
2971  llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
2972
2973  // If there was no identifier specified for the declarator, either we are in
2974  // an abstract-declarator, or we are in a parameter declarator which was found
2975  // to be abstract.  In abstract-declarators, identifier lists are not valid:
2976  // diagnose this.
2977  if (!D.getIdentifier())
2978    Diag(Tok, diag::ext_ident_list_in_param);
2979
2980  // Tok is known to be the first identifier in the list.  Remember this
2981  // identifier in ParamInfo.
2982  ParamsSoFar.insert(Tok.getIdentifierInfo());
2983  ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
2984                                                 Tok.getLocation(),
2985                                                 DeclPtrTy()));
2986
2987  ConsumeToken();  // eat the first identifier.
2988
2989  while (Tok.is(tok::comma)) {
2990    // Eat the comma.
2991    ConsumeToken();
2992
2993    // If this isn't an identifier, report the error and skip until ')'.
2994    if (Tok.isNot(tok::identifier)) {
2995      Diag(Tok, diag::err_expected_ident);
2996      SkipUntil(tok::r_paren);
2997      return;
2998    }
2999
3000    IdentifierInfo *ParmII = Tok.getIdentifierInfo();
3001
3002    // Reject 'typedef int y; int test(x, y)', but continue parsing.
3003    if (Actions.getTypeName(*ParmII, Tok.getLocation(), CurScope))
3004      Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
3005
3006    // Verify that the argument identifier has not already been mentioned.
3007    if (!ParamsSoFar.insert(ParmII)) {
3008      Diag(Tok, diag::err_param_redefinition) << ParmII;
3009    } else {
3010      // Remember this identifier in ParamInfo.
3011      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
3012                                                     Tok.getLocation(),
3013                                                     DeclPtrTy()));
3014    }
3015
3016    // Eat the identifier.
3017    ConsumeToken();
3018  }
3019
3020  // If we have the closing ')', eat it and we're done.
3021  SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
3022
3023  // Remember that we parsed a function type, and remember the attributes.  This
3024  // function type is always a K&R style function type, which is not varargs and
3025  // has no prototype.
3026  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
3027                                             SourceLocation(),
3028                                             &ParamInfo[0], ParamInfo.size(),
3029                                             /*TypeQuals*/0,
3030                                             /*exception*/false,
3031                                             SourceLocation(), false, 0, 0, 0,
3032                                             LParenLoc, RLoc, D),
3033                RLoc);
3034}
3035
3036/// [C90]   direct-declarator '[' constant-expression[opt] ']'
3037/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
3038/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
3039/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
3040/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
3041void Parser::ParseBracketDeclarator(Declarator &D) {
3042  SourceLocation StartLoc = ConsumeBracket();
3043
3044  // C array syntax has many features, but by-far the most common is [] and [4].
3045  // This code does a fast path to handle some of the most obvious cases.
3046  if (Tok.getKind() == tok::r_square) {
3047    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
3048    //FIXME: Use these
3049    CXX0XAttributeList Attr;
3050    if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier(true)) {
3051      Attr = ParseCXX0XAttributes();
3052    }
3053
3054    // Remember that we parsed the empty array type.
3055    OwningExprResult NumElements(Actions);
3056    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
3057                                            StartLoc, EndLoc),
3058                  EndLoc);
3059    return;
3060  } else if (Tok.getKind() == tok::numeric_constant &&
3061             GetLookAheadToken(1).is(tok::r_square)) {
3062    // [4] is very common.  Parse the numeric constant expression.
3063    OwningExprResult ExprRes(Actions.ActOnNumericConstant(Tok));
3064    ConsumeToken();
3065
3066    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
3067    //FIXME: Use these
3068    CXX0XAttributeList Attr;
3069    if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
3070      Attr = ParseCXX0XAttributes();
3071    }
3072
3073    // If there was an error parsing the assignment-expression, recover.
3074    if (ExprRes.isInvalid())
3075      ExprRes.release();  // Deallocate expr, just use [].
3076
3077    // Remember that we parsed a array type, and remember its features.
3078    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, ExprRes.release(),
3079                                            StartLoc, EndLoc),
3080                  EndLoc);
3081    return;
3082  }
3083
3084  // If valid, this location is the position where we read the 'static' keyword.
3085  SourceLocation StaticLoc;
3086  if (Tok.is(tok::kw_static))
3087    StaticLoc = ConsumeToken();
3088
3089  // If there is a type-qualifier-list, read it now.
3090  // Type qualifiers in an array subscript are a C99 feature.
3091  DeclSpec DS;
3092  ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3093
3094  // If we haven't already read 'static', check to see if there is one after the
3095  // type-qualifier-list.
3096  if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
3097    StaticLoc = ConsumeToken();
3098
3099  // Handle "direct-declarator [ type-qual-list[opt] * ]".
3100  bool isStar = false;
3101  OwningExprResult NumElements(Actions);
3102
3103  // Handle the case where we have '[*]' as the array size.  However, a leading
3104  // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
3105  // the the token after the star is a ']'.  Since stars in arrays are
3106  // infrequent, use of lookahead is not costly here.
3107  if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
3108    ConsumeToken();  // Eat the '*'.
3109
3110    if (StaticLoc.isValid()) {
3111      Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
3112      StaticLoc = SourceLocation();  // Drop the static.
3113    }
3114    isStar = true;
3115  } else if (Tok.isNot(tok::r_square)) {
3116    // Note, in C89, this production uses the constant-expr production instead
3117    // of assignment-expr.  The only difference is that assignment-expr allows
3118    // things like '=' and '*='.  Sema rejects these in C89 mode because they
3119    // are not i-c-e's, so we don't need to distinguish between the two here.
3120
3121    // Parse the constant-expression or assignment-expression now (depending
3122    // on dialect).
3123    if (getLang().CPlusPlus)
3124      NumElements = ParseConstantExpression();
3125    else
3126      NumElements = ParseAssignmentExpression();
3127  }
3128
3129  // If there was an error parsing the assignment-expression, recover.
3130  if (NumElements.isInvalid()) {
3131    D.setInvalidType(true);
3132    // If the expression was invalid, skip it.
3133    SkipUntil(tok::r_square);
3134    return;
3135  }
3136
3137  SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
3138
3139  //FIXME: Use these
3140  CXX0XAttributeList Attr;
3141  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
3142    Attr = ParseCXX0XAttributes();
3143  }
3144
3145  // Remember that we parsed a array type, and remember its features.
3146  D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
3147                                          StaticLoc.isValid(), isStar,
3148                                          NumElements.release(),
3149                                          StartLoc, EndLoc),
3150                EndLoc);
3151}
3152
3153/// [GNU]   typeof-specifier:
3154///           typeof ( expressions )
3155///           typeof ( type-name )
3156/// [GNU/C++] typeof unary-expression
3157///
3158void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
3159  assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
3160  Token OpTok = Tok;
3161  SourceLocation StartLoc = ConsumeToken();
3162
3163  const bool hasParens = Tok.is(tok::l_paren);
3164
3165  bool isCastExpr;
3166  TypeTy *CastTy;
3167  SourceRange CastRange;
3168  OwningExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok,
3169                                                               isCastExpr,
3170                                                               CastTy,
3171                                                               CastRange);
3172  if (hasParens)
3173    DS.setTypeofParensRange(CastRange);
3174
3175  if (CastRange.getEnd().isInvalid())
3176    // FIXME: Not accurate, the range gets one token more than it should.
3177    DS.SetRangeEnd(Tok.getLocation());
3178  else
3179    DS.SetRangeEnd(CastRange.getEnd());
3180
3181  if (isCastExpr) {
3182    if (!CastTy) {
3183      DS.SetTypeSpecError();
3184      return;
3185    }
3186
3187    const char *PrevSpec = 0;
3188    unsigned DiagID;
3189    // Check for duplicate type specifiers (e.g. "int typeof(int)").
3190    if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
3191                           DiagID, CastTy))
3192      Diag(StartLoc, DiagID) << PrevSpec;
3193    return;
3194  }
3195
3196  // If we get here, the operand to the typeof was an expresion.
3197  if (Operand.isInvalid()) {
3198    DS.SetTypeSpecError();
3199    return;
3200  }
3201
3202  const char *PrevSpec = 0;
3203  unsigned DiagID;
3204  // Check for duplicate type specifiers (e.g. "int typeof(int)").
3205  if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
3206                         DiagID, Operand.release()))
3207    Diag(StartLoc, DiagID) << PrevSpec;
3208}
3209