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