ParseDecl.cpp revision 4c97d762d8c5a84f6554e5bfb31d28c90df64158
1//===--- ParseDecl.cpp - Declaration Parsing ------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements the Declaration portions of the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
15#include "clang/Parse/ParseDiagnostic.h"
16#include "clang/Parse/Scope.h"
17#include "ExtensionRAIIObject.h"
18#include "AstGuard.h"
19#include "llvm/ADT/SmallSet.h"
20using namespace clang;
21
22//===----------------------------------------------------------------------===//
23// C99 6.7: Declarations.
24//===----------------------------------------------------------------------===//
25
26/// ParseTypeName
27///       type-name: [C99 6.7.6]
28///         specifier-qualifier-list abstract-declarator[opt]
29///
30/// Called type-id in C++.
31Action::TypeResult Parser::ParseTypeName() {
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
40  if (DeclaratorInfo.getInvalidType())
41    return true;
42
43  return Actions.ActOnTypeName(CurScope, DeclaratorInfo);
44}
45
46/// ParseAttributes - Parse a non-empty attributes list.
47///
48/// [GNU] attributes:
49///         attribute
50///         attributes attribute
51///
52/// [GNU]  attribute:
53///          '__attribute__' '(' '(' attribute-list ')' ')'
54///
55/// [GNU]  attribute-list:
56///          attrib
57///          attribute_list ',' attrib
58///
59/// [GNU]  attrib:
60///          empty
61///          attrib-name
62///          attrib-name '(' identifier ')'
63///          attrib-name '(' identifier ',' nonempty-expr-list ')'
64///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
65///
66/// [GNU]  attrib-name:
67///          identifier
68///          typespec
69///          typequal
70///          storageclass
71///
72/// FIXME: The GCC grammar/code for this construct implies we need two
73/// token lookahead. Comment from gcc: "If they start with an identifier
74/// which is followed by a comma or close parenthesis, then the arguments
75/// start with that identifier; otherwise they are an expression list."
76///
77/// At the moment, I am not doing 2 token lookahead. I am also unaware of
78/// any attributes that don't work (based on my limited testing). Most
79/// attributes are very simple in practice. Until we find a bug, I don't see
80/// a pressing need to implement the 2 token lookahead.
81
82AttributeList *Parser::ParseAttributes(SourceLocation *EndLoc) {
83  assert(Tok.is(tok::kw___attribute) && "Not an attribute list!");
84
85  AttributeList *CurrAttr = 0;
86
87  while (Tok.is(tok::kw___attribute)) {
88    ConsumeToken();
89    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
90                         "attribute")) {
91      SkipUntil(tok::r_paren, true); // skip until ) or ;
92      return CurrAttr;
93    }
94    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
95      SkipUntil(tok::r_paren, true); // skip until ) or ;
96      return CurrAttr;
97    }
98    // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
99    while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
100           Tok.is(tok::comma)) {
101
102      if (Tok.is(tok::comma)) {
103        // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
104        ConsumeToken();
105        continue;
106      }
107      // we have an identifier or declaration specifier (const, int, etc.)
108      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
109      SourceLocation AttrNameLoc = ConsumeToken();
110
111      // check if we have a "paramterized" attribute
112      if (Tok.is(tok::l_paren)) {
113        ConsumeParen(); // ignore the left paren loc for now
114
115        if (Tok.is(tok::identifier)) {
116          IdentifierInfo *ParmName = Tok.getIdentifierInfo();
117          SourceLocation ParmLoc = ConsumeToken();
118
119          if (Tok.is(tok::r_paren)) {
120            // __attribute__(( mode(byte) ))
121            ConsumeParen(); // ignore the right paren loc for now
122            CurrAttr = new AttributeList(AttrName, AttrNameLoc,
123                                         ParmName, ParmLoc, 0, 0, CurrAttr);
124          } else if (Tok.is(tok::comma)) {
125            ConsumeToken();
126            // __attribute__(( format(printf, 1, 2) ))
127            ExprVector ArgExprs(Actions);
128            bool ArgExprsOk = true;
129
130            // now parse the non-empty comma separated list of expressions
131            while (1) {
132              OwningExprResult ArgExpr(ParseAssignmentExpression());
133              if (ArgExpr.isInvalid()) {
134                ArgExprsOk = false;
135                SkipUntil(tok::r_paren);
136                break;
137              } else {
138                ArgExprs.push_back(ArgExpr.release());
139              }
140              if (Tok.isNot(tok::comma))
141                break;
142              ConsumeToken(); // Eat the comma, move to the next argument
143            }
144            if (ArgExprsOk && Tok.is(tok::r_paren)) {
145              ConsumeParen(); // ignore the right paren loc for now
146              CurrAttr = new AttributeList(AttrName, AttrNameLoc, ParmName,
147                           ParmLoc, ArgExprs.take(), ArgExprs.size(), CurrAttr);
148            }
149          }
150        } else { // not an identifier
151          // parse a possibly empty comma separated list of expressions
152          if (Tok.is(tok::r_paren)) {
153            // __attribute__(( nonnull() ))
154            ConsumeParen(); // ignore the right paren loc for now
155            CurrAttr = new AttributeList(AttrName, AttrNameLoc,
156                                         0, SourceLocation(), 0, 0, CurrAttr);
157          } else {
158            // __attribute__(( aligned(16) ))
159            ExprVector ArgExprs(Actions);
160            bool ArgExprsOk = true;
161
162            // now parse the list of expressions
163            while (1) {
164              OwningExprResult ArgExpr(ParseAssignmentExpression());
165              if (ArgExpr.isInvalid()) {
166                ArgExprsOk = false;
167                SkipUntil(tok::r_paren);
168                break;
169              } else {
170                ArgExprs.push_back(ArgExpr.release());
171              }
172              if (Tok.isNot(tok::comma))
173                break;
174              ConsumeToken(); // Eat the comma, move to the next argument
175            }
176            // Match the ')'.
177            if (ArgExprsOk && Tok.is(tok::r_paren)) {
178              ConsumeParen(); // ignore the right paren loc for now
179              CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0,
180                           SourceLocation(), ArgExprs.take(), ArgExprs.size(),
181                           CurrAttr);
182            }
183          }
184        }
185      } else {
186        CurrAttr = new AttributeList(AttrName, AttrNameLoc,
187                                     0, SourceLocation(), 0, 0, CurrAttr);
188      }
189    }
190    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
191      SkipUntil(tok::r_paren, false);
192    SourceLocation Loc = Tok.getLocation();;
193    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
194      SkipUntil(tok::r_paren, false);
195    }
196    if (EndLoc)
197      *EndLoc = Loc;
198  }
199  return CurrAttr;
200}
201
202/// FuzzyParseMicrosoftDeclSpec. When -fms-extensions is enabled, this
203/// routine is called to skip/ignore tokens that comprise the MS declspec.
204void Parser::FuzzyParseMicrosoftDeclSpec() {
205  assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
206  ConsumeToken();
207  if (Tok.is(tok::l_paren)) {
208    unsigned short savedParenCount = ParenCount;
209    do {
210      ConsumeAnyToken();
211    } while (ParenCount > savedParenCount && Tok.isNot(tok::eof));
212  }
213  return;
214}
215
216/// ParseDeclaration - Parse a full 'declaration', which consists of
217/// declaration-specifiers, some number of declarators, and a semicolon.
218/// 'Context' should be a Declarator::TheContext value.  This returns the
219/// location of the semicolon in DeclEnd.
220///
221///       declaration: [C99 6.7]
222///         block-declaration ->
223///           simple-declaration
224///           others                   [FIXME]
225/// [C++]   template-declaration
226/// [C++]   namespace-definition
227/// [C++]   using-directive
228/// [C++]   using-declaration [TODO]
229/// [C++0x] static_assert-declaration
230///         others... [FIXME]
231///
232Parser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context,
233                                                SourceLocation &DeclEnd) {
234  DeclPtrTy SingleDecl;
235  switch (Tok.getKind()) {
236  case tok::kw_export:
237  case tok::kw_template:
238    SingleDecl = ParseTemplateDeclarationOrSpecialization(Context, DeclEnd);
239    break;
240  case tok::kw_namespace:
241    SingleDecl = ParseNamespace(Context, DeclEnd);
242    break;
243  case tok::kw_using:
244    SingleDecl = ParseUsingDirectiveOrDeclaration(Context, DeclEnd);
245    break;
246  case tok::kw_static_assert:
247    SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
248    break;
249  default:
250    return ParseSimpleDeclaration(Context, DeclEnd);
251  }
252
253  // This routine returns a DeclGroup, if the thing we parsed only contains a
254  // single decl, convert it now.
255  return Actions.ConvertDeclToDeclGroup(SingleDecl);
256}
257
258///       simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
259///         declaration-specifiers init-declarator-list[opt] ';'
260///[C90/C++]init-declarator-list ';'                             [TODO]
261/// [OMP]   threadprivate-directive                              [TODO]
262///
263/// If RequireSemi is false, this does not check for a ';' at the end of the
264/// declaration.
265Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(unsigned Context,
266                                                      SourceLocation &DeclEnd,
267                                                      bool RequireSemi) {
268  // Parse the common declaration-specifiers piece.
269  DeclSpec DS;
270  ParseDeclarationSpecifiers(DS);
271
272  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
273  // declaration-specifiers init-declarator-list[opt] ';'
274  if (Tok.is(tok::semi)) {
275    ConsumeToken();
276    DeclPtrTy TheDecl = Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
277    return Actions.ConvertDeclToDeclGroup(TheDecl);
278  }
279
280  Declarator DeclaratorInfo(DS, (Declarator::TheContext)Context);
281  ParseDeclarator(DeclaratorInfo);
282
283  DeclGroupPtrTy DG =
284    ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo);
285
286  DeclEnd = Tok.getLocation();
287
288  // If the client wants to check what comes after the declaration, just return
289  // immediately without checking anything!
290  if (!RequireSemi) return DG;
291
292  if (Tok.is(tok::semi)) {
293    ConsumeToken();
294    return DG;
295  }
296
297  Diag(Tok, diag::err_expected_semi_declation);
298  // Skip to end of block or statement
299  SkipUntil(tok::r_brace, true, true);
300  if (Tok.is(tok::semi))
301    ConsumeToken();
302  return DG;
303}
304
305
306/// ParseInitDeclaratorListAfterFirstDeclarator - Parse 'declaration' after
307/// parsing 'declaration-specifiers declarator'.  This method is split out this
308/// way to handle the ambiguity between top-level function-definitions and
309/// declarations.
310///
311///       init-declarator-list: [C99 6.7]
312///         init-declarator
313///         init-declarator-list ',' init-declarator
314///       init-declarator: [C99 6.7]
315///         declarator
316///         declarator '=' initializer
317/// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
318/// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
319/// [C++]   declarator initializer[opt]
320///
321/// [C++] initializer:
322/// [C++]   '=' initializer-clause
323/// [C++]   '(' expression-list ')'
324/// [C++0x] '=' 'default'                                                [TODO]
325/// [C++0x] '=' 'delete'
326///
327/// According to the standard grammar, =default and =delete are function
328/// definitions, but that definitely doesn't fit with the parser here.
329///
330Parser::DeclGroupPtrTy Parser::
331ParseInitDeclaratorListAfterFirstDeclarator(Declarator &D) {
332  // Declarators may be grouped together ("int X, *Y, Z();"). Remember the decls
333  // that we parse together here.
334  llvm::SmallVector<DeclPtrTy, 8> DeclsInGroup;
335
336  // At this point, we know that it is not a function definition.  Parse the
337  // rest of the init-declarator-list.
338  while (1) {
339    // If a simple-asm-expr is present, parse it.
340    if (Tok.is(tok::kw_asm)) {
341      SourceLocation Loc;
342      OwningExprResult AsmLabel(ParseSimpleAsm(&Loc));
343      if (AsmLabel.isInvalid()) {
344        SkipUntil(tok::semi, true, true);
345        return DeclGroupPtrTy();
346      }
347
348      D.setAsmLabel(AsmLabel.release());
349      D.SetRangeEnd(Loc);
350    }
351
352    // If attributes are present, parse them.
353    if (Tok.is(tok::kw___attribute)) {
354      SourceLocation Loc;
355      AttributeList *AttrList = ParseAttributes(&Loc);
356      D.AddAttributes(AttrList, Loc);
357    }
358
359    // Inform the current actions module that we just parsed this declarator.
360    DeclPtrTy ThisDecl = Actions.ActOnDeclarator(CurScope, D);
361    DeclsInGroup.push_back(ThisDecl);
362
363    // Parse declarator '=' initializer.
364    if (Tok.is(tok::equal)) {
365      ConsumeToken();
366      if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) {
367        SourceLocation DelLoc = ConsumeToken();
368        Actions.SetDeclDeleted(ThisDecl, DelLoc);
369      } else {
370        OwningExprResult Init(ParseInitializer());
371        if (Init.isInvalid()) {
372          SkipUntil(tok::semi, true, true);
373          return DeclGroupPtrTy();
374        }
375        Actions.AddInitializerToDecl(ThisDecl, move(Init));
376      }
377    } else if (Tok.is(tok::l_paren)) {
378      // Parse C++ direct initializer: '(' expression-list ')'
379      SourceLocation LParenLoc = ConsumeParen();
380      ExprVector Exprs(Actions);
381      CommaLocsTy CommaLocs;
382
383      bool InvalidExpr = false;
384      if (ParseExpressionList(Exprs, CommaLocs)) {
385        SkipUntil(tok::r_paren);
386        InvalidExpr = true;
387      }
388      // Match the ')'.
389      SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
390
391      if (!InvalidExpr) {
392        assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
393               "Unexpected number of commas!");
394        Actions.AddCXXDirectInitializerToDecl(ThisDecl, LParenLoc,
395                                              move_arg(Exprs),
396                                              &CommaLocs[0], RParenLoc);
397      }
398    } else {
399      Actions.ActOnUninitializedDecl(ThisDecl);
400    }
401
402    // If we don't have a comma, it is either the end of the list (a ';') or an
403    // error, bail out.
404    if (Tok.isNot(tok::comma))
405      break;
406
407    // Consume the comma.
408    ConsumeToken();
409
410    // Parse the next declarator.
411    D.clear();
412
413    // Accept attributes in an init-declarator.  In the first declarator in a
414    // declaration, these would be part of the declspec.  In subsequent
415    // declarators, they become part of the declarator itself, so that they
416    // don't apply to declarators after *this* one.  Examples:
417    //    short __attribute__((common)) var;    -> declspec
418    //    short var __attribute__((common));    -> declarator
419    //    short x, __attribute__((common)) var;    -> declarator
420    if (Tok.is(tok::kw___attribute)) {
421      SourceLocation Loc;
422      AttributeList *AttrList = ParseAttributes(&Loc);
423      D.AddAttributes(AttrList, Loc);
424    }
425
426    ParseDeclarator(D);
427  }
428
429  return Actions.FinalizeDeclaratorGroup(CurScope, &DeclsInGroup[0],
430                                         DeclsInGroup.size());
431}
432
433/// ParseSpecifierQualifierList
434///        specifier-qualifier-list:
435///          type-specifier specifier-qualifier-list[opt]
436///          type-qualifier specifier-qualifier-list[opt]
437/// [GNU]    attributes     specifier-qualifier-list[opt]
438///
439void Parser::ParseSpecifierQualifierList(DeclSpec &DS) {
440  /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
441  /// parse declaration-specifiers and complain about extra stuff.
442  ParseDeclarationSpecifiers(DS);
443
444  // Validate declspec for type-name.
445  unsigned Specs = DS.getParsedSpecifiers();
446  if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers())
447    Diag(Tok, diag::err_typename_requires_specqual);
448
449  // Issue diagnostic and remove storage class if present.
450  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
451    if (DS.getStorageClassSpecLoc().isValid())
452      Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
453    else
454      Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
455    DS.ClearStorageClassSpecs();
456  }
457
458  // Issue diagnostic and remove function specfier if present.
459  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
460    if (DS.isInlineSpecified())
461      Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
462    if (DS.isVirtualSpecified())
463      Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
464    if (DS.isExplicitSpecified())
465      Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
466    DS.ClearFunctionSpecs();
467  }
468}
469
470/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
471/// specified token is valid after the identifier in a declarator which
472/// immediately follows the declspec.  For example, these things are valid:
473///
474///      int x   [             4];         // direct-declarator
475///      int x   (             int y);     // direct-declarator
476///  int(int x   )                         // direct-declarator
477///      int x   ;                         // simple-declaration
478///      int x   =             17;         // init-declarator-list
479///      int x   ,             y;          // init-declarator-list
480///      int x   __asm__       ("foo");    // init-declarator-list
481///
482/// This is not, because 'x' does not immediately follow the declspec (though
483/// ')' happens to be valid anyway).
484///    int (x)
485///
486static bool isValidAfterIdentifierInDeclarator(const Token &T) {
487  return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
488         T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
489         T.is(tok::kw_asm);
490
491}
492
493/// ParseDeclarationSpecifiers
494///       declaration-specifiers: [C99 6.7]
495///         storage-class-specifier declaration-specifiers[opt]
496///         type-specifier declaration-specifiers[opt]
497/// [C99]   function-specifier declaration-specifiers[opt]
498/// [GNU]   attributes declaration-specifiers[opt]
499///
500///       storage-class-specifier: [C99 6.7.1]
501///         'typedef'
502///         'extern'
503///         'static'
504///         'auto'
505///         'register'
506/// [C++]   'mutable'
507/// [GNU]   '__thread'
508///       function-specifier: [C99 6.7.4]
509/// [C99]   'inline'
510/// [C++]   'virtual'
511/// [C++]   'explicit'
512///
513void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
514                                        TemplateParameterLists *TemplateParams,
515                                        AccessSpecifier AS) {
516  DS.SetRangeStart(Tok.getLocation());
517  while (1) {
518    int isInvalid = false;
519    const char *PrevSpec = 0;
520    SourceLocation Loc = Tok.getLocation();
521
522    switch (Tok.getKind()) {
523    default:
524    DoneWithDeclSpec:
525      // If this is not a declaration specifier token, we're done reading decl
526      // specifiers.  First verify that DeclSpec's are consistent.
527      DS.Finish(Diags, PP);
528      return;
529
530    case tok::coloncolon: // ::foo::bar
531      // Annotate C++ scope specifiers.  If we get one, loop.
532      if (TryAnnotateCXXScopeToken())
533        continue;
534      goto DoneWithDeclSpec;
535
536    case tok::annot_cxxscope: {
537      if (DS.hasTypeSpecifier())
538        goto DoneWithDeclSpec;
539
540      // We are looking for a qualified typename.
541      Token Next = NextToken();
542      if (Next.is(tok::annot_template_id) &&
543          static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
544            ->Kind == TNK_Type_template) {
545        // We have a qualified template-id, e.g., N::A<int>
546        CXXScopeSpec SS;
547        ParseOptionalCXXScopeSpecifier(SS);
548        assert(Tok.is(tok::annot_template_id) &&
549               "ParseOptionalCXXScopeSpecifier not working");
550        AnnotateTemplateIdTokenAsType(&SS);
551        continue;
552      }
553
554      if (Next.isNot(tok::identifier))
555        goto DoneWithDeclSpec;
556
557      CXXScopeSpec SS;
558      SS.setScopeRep(Tok.getAnnotationValue());
559      SS.setRange(Tok.getAnnotationRange());
560
561      // If the next token is the name of the class type that the C++ scope
562      // denotes, followed by a '(', then this is a constructor declaration.
563      // We're done with the decl-specifiers.
564      if (Actions.isCurrentClassName(*NextToken().getIdentifierInfo(),
565                                     CurScope, &SS) &&
566          GetLookAheadToken(2).is(tok::l_paren))
567        goto DoneWithDeclSpec;
568
569      TypeTy *TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
570                                            Next.getLocation(), CurScope, &SS);
571
572      if (TypeRep == 0)
573        goto DoneWithDeclSpec;
574
575      ConsumeToken(); // The C++ scope.
576
577      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
578                                     TypeRep);
579      if (isInvalid)
580        break;
581
582      DS.SetRangeEnd(Tok.getLocation());
583      ConsumeToken(); // The typename.
584
585      continue;
586    }
587
588    case tok::annot_typename: {
589      if (Tok.getAnnotationValue())
590        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
591                                       Tok.getAnnotationValue());
592      else
593        DS.SetTypeSpecError();
594      DS.SetRangeEnd(Tok.getAnnotationEndLoc());
595      ConsumeToken(); // The typename
596
597      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
598      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
599      // Objective-C interface.  If we don't have Objective-C or a '<', this is
600      // just a normal reference to a typedef name.
601      if (!Tok.is(tok::less) || !getLang().ObjC1)
602        continue;
603
604      SourceLocation EndProtoLoc;
605      llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
606      ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
607      DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size());
608
609      DS.SetRangeEnd(EndProtoLoc);
610      continue;
611    }
612
613      // typedef-name
614    case tok::identifier: {
615      // In C++, check to see if this is a scope specifier like foo::bar::, if
616      // so handle it as such.  This is important for ctor parsing.
617      if (getLang().CPlusPlus && TryAnnotateCXXScopeToken())
618        continue;
619
620      // This identifier can only be a typedef name if we haven't already seen
621      // a type-specifier.  Without this check we misparse:
622      //  typedef int X; struct Y { short X; };  as 'short int'.
623      if (DS.hasTypeSpecifier())
624        goto DoneWithDeclSpec;
625
626      // It has to be available as a typedef too!
627      TypeTy *TypeRep = Actions.getTypeName(*Tok.getIdentifierInfo(),
628                                            Tok.getLocation(), CurScope);
629
630      // If this is not a typedef name, don't parse it as part of the declspec,
631      // it must be an implicit int or an error.
632      if (TypeRep == 0) {
633        // If we see an identifier that is not a type name, we normally would
634        // parse it as the identifer being declared.  However, when a typename
635        // is typo'd or the definition is not included, this will incorrectly
636        // parse the typename as the identifier name and fall over misparsing
637        // later parts of the diagnostic.
638        //
639        // As such, we try to do some look-ahead in cases where this would
640        // otherwise be an "implicit-int" case to see if this is invalid.  For
641        // example: "static foo_t x = 4;"  In this case, if we parsed foo_t as
642        // an identifier with implicit int, we'd get a parse error because the
643        // next token is obviously invalid for a type.  Parse these as a case
644        // with an invalid type specifier.
645        assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
646
647        // Since we know that this either implicit int (which is rare) or an
648        // error, we'd do lookahead to try to do better recovery.
649        if (isValidAfterIdentifierInDeclarator(NextToken())) {
650          // If this token is valid for implicit int, e.g. "static x = 4", then
651          // we just avoid eating the identifier, so it will be parsed as the
652          // identifier in the declarator.
653          goto DoneWithDeclSpec;
654        }
655
656        // Otherwise, if we don't consume this token, we are going to emit an
657        // error anyway.  Try to recover from various common problems.  Check
658        // to see if this was a reference to a tag name without a tag specified.
659        // This is a common problem in C (saying 'foo' insteat of 'struct foo').
660        const char *TagName = 0;
661        tok::TokenKind TagKind = tok::unknown;
662
663        switch (Actions.isTagName(*Tok.getIdentifierInfo(), CurScope)) {
664        default: break;
665        case DeclSpec::TST_enum:  TagName="enum"  ;TagKind=tok::kw_enum  ;break;
666        case DeclSpec::TST_union: TagName="union" ;TagKind=tok::kw_union ;break;
667        case DeclSpec::TST_struct:TagName="struct";TagKind=tok::kw_struct;break;
668        case DeclSpec::TST_class: TagName="class" ;TagKind=tok::kw_class ;break;
669        }
670        if (TagName) {
671          Diag(Loc, diag::err_use_of_tag_name_without_tag)
672            << Tok.getIdentifierInfo() << TagName
673            << CodeModificationHint::CreateInsertion(Tok.getLocation(),TagName);
674
675          // Parse this as a tag as if the missing tag were present.
676          if (TagKind == tok::kw_enum)
677            ParseEnumSpecifier(Loc, DS, AS);
678          else
679            ParseClassSpecifier(TagKind, Loc, DS, TemplateParams, AS);
680          continue;
681        }
682
683        // Since this is almost certainly an invalid type name, emit a
684        // diagnostic that says it, eat the token, and pretend we saw an 'int'.
685        Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo();
686        DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec);
687        DS.SetRangeEnd(Tok.getLocation());
688        ConsumeToken();
689
690        // TODO: Could inject an invalid typedef decl in an enclosing scope to
691        // avoid rippling error messages on subsequent uses of the same type,
692        // could be useful if #include was forgotten.
693
694        // FIXME: Mark DeclSpec as invalid.
695        goto DoneWithDeclSpec;
696      }
697
698      // C++: If the identifier is actually the name of the class type
699      // being defined and the next token is a '(', then this is a
700      // constructor declaration. We're done with the decl-specifiers
701      // and will treat this token as an identifier.
702      if (getLang().CPlusPlus && CurScope->isClassScope() &&
703          Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) &&
704          NextToken().getKind() == tok::l_paren)
705        goto DoneWithDeclSpec;
706
707      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
708                                     TypeRep);
709      if (isInvalid)
710        break;
711
712      DS.SetRangeEnd(Tok.getLocation());
713      ConsumeToken(); // The identifier
714
715      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
716      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
717      // Objective-C interface.  If we don't have Objective-C or a '<', this is
718      // just a normal reference to a typedef name.
719      if (!Tok.is(tok::less) || !getLang().ObjC1)
720        continue;
721
722      SourceLocation EndProtoLoc;
723      llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
724      ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
725      DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size());
726
727      DS.SetRangeEnd(EndProtoLoc);
728
729      // Need to support trailing type qualifiers (e.g. "id<p> const").
730      // If a type specifier follows, it will be diagnosed elsewhere.
731      continue;
732    }
733
734      // type-name
735    case tok::annot_template_id: {
736      TemplateIdAnnotation *TemplateId
737        = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
738      if (TemplateId->Kind != TNK_Type_template) {
739        // This template-id does not refer to a type name, so we're
740        // done with the type-specifiers.
741        goto DoneWithDeclSpec;
742      }
743
744      // Turn the template-id annotation token into a type annotation
745      // token, then try again to parse it as a type-specifier.
746      AnnotateTemplateIdTokenAsType();
747      continue;
748    }
749
750    // GNU attributes support.
751    case tok::kw___attribute:
752      DS.AddAttributes(ParseAttributes());
753      continue;
754
755    // Microsoft declspec support.
756    case tok::kw___declspec:
757      if (!PP.getLangOptions().Microsoft)
758        goto DoneWithDeclSpec;
759      FuzzyParseMicrosoftDeclSpec();
760      continue;
761
762    // Microsoft single token adornments.
763    case tok::kw___forceinline:
764    case tok::kw___w64:
765    case tok::kw___cdecl:
766    case tok::kw___stdcall:
767    case tok::kw___fastcall:
768      if (!PP.getLangOptions().Microsoft)
769        goto DoneWithDeclSpec;
770      // Just ignore it.
771      break;
772
773    // storage-class-specifier
774    case tok::kw_typedef:
775      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec);
776      break;
777    case tok::kw_extern:
778      if (DS.isThreadSpecified())
779        Diag(Tok, diag::ext_thread_before) << "extern";
780      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec);
781      break;
782    case tok::kw___private_extern__:
783      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
784                                         PrevSpec);
785      break;
786    case tok::kw_static:
787      if (DS.isThreadSpecified())
788        Diag(Tok, diag::ext_thread_before) << "static";
789      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec);
790      break;
791    case tok::kw_auto:
792      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec);
793      break;
794    case tok::kw_register:
795      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec);
796      break;
797    case tok::kw_mutable:
798      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec);
799      break;
800    case tok::kw___thread:
801      isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec)*2;
802      break;
803
804    // function-specifier
805    case tok::kw_inline:
806      isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec);
807      break;
808    case tok::kw_virtual:
809      isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec);
810      break;
811    case tok::kw_explicit:
812      isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec);
813      break;
814
815    // type-specifier
816    case tok::kw_short:
817      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec);
818      break;
819    case tok::kw_long:
820      if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
821        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec);
822      else
823        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec);
824      break;
825    case tok::kw_signed:
826      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec);
827      break;
828    case tok::kw_unsigned:
829      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec);
830      break;
831    case tok::kw__Complex:
832      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec);
833      break;
834    case tok::kw__Imaginary:
835      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec);
836      break;
837    case tok::kw_void:
838      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec);
839      break;
840    case tok::kw_char:
841      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec);
842      break;
843    case tok::kw_int:
844      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec);
845      break;
846    case tok::kw_float:
847      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec);
848      break;
849    case tok::kw_double:
850      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec);
851      break;
852    case tok::kw_wchar_t:
853      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec);
854      break;
855    case tok::kw_bool:
856    case tok::kw__Bool:
857      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec);
858      break;
859    case tok::kw__Decimal32:
860      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec);
861      break;
862    case tok::kw__Decimal64:
863      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec);
864      break;
865    case tok::kw__Decimal128:
866      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec);
867      break;
868
869    // class-specifier:
870    case tok::kw_class:
871    case tok::kw_struct:
872    case tok::kw_union: {
873      tok::TokenKind Kind = Tok.getKind();
874      ConsumeToken();
875      ParseClassSpecifier(Kind, Loc, DS, TemplateParams, AS);
876      continue;
877    }
878
879    // enum-specifier:
880    case tok::kw_enum:
881      ConsumeToken();
882      ParseEnumSpecifier(Loc, DS, AS);
883      continue;
884
885    // cv-qualifier:
886    case tok::kw_const:
887      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec,getLang())*2;
888      break;
889    case tok::kw_volatile:
890      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
891                                 getLang())*2;
892      break;
893    case tok::kw_restrict:
894      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
895                                 getLang())*2;
896      break;
897
898    // C++ typename-specifier:
899    case tok::kw_typename:
900      if (TryAnnotateTypeOrScopeToken())
901        continue;
902      break;
903
904    // GNU typeof support.
905    case tok::kw_typeof:
906      ParseTypeofSpecifier(DS);
907      continue;
908
909    case tok::less:
910      // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
911      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
912      // but we support it.
913      if (DS.hasTypeSpecifier() || !getLang().ObjC1)
914        goto DoneWithDeclSpec;
915
916      {
917        SourceLocation EndProtoLoc;
918        llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
919        ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
920        DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size());
921        DS.SetRangeEnd(EndProtoLoc);
922
923        Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
924          << CodeModificationHint::CreateInsertion(Loc, "id")
925          << SourceRange(Loc, EndProtoLoc);
926        // Need to support trailing type qualifiers (e.g. "id<p> const").
927        // If a type specifier follows, it will be diagnosed elsewhere.
928        continue;
929      }
930    }
931    // If the specifier combination wasn't legal, issue a diagnostic.
932    if (isInvalid) {
933      assert(PrevSpec && "Method did not return previous specifier!");
934      // Pick between error or extwarn.
935      unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination
936                                       : diag::ext_duplicate_declspec;
937      Diag(Tok, DiagID) << PrevSpec;
938    }
939    DS.SetRangeEnd(Tok.getLocation());
940    ConsumeToken();
941  }
942}
943
944/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
945/// primarily follow the C++ grammar with additions for C99 and GNU,
946/// which together subsume the C grammar. Note that the C++
947/// type-specifier also includes the C type-qualifier (for const,
948/// volatile, and C99 restrict). Returns true if a type-specifier was
949/// found (and parsed), false otherwise.
950///
951///       type-specifier: [C++ 7.1.5]
952///         simple-type-specifier
953///         class-specifier
954///         enum-specifier
955///         elaborated-type-specifier  [TODO]
956///         cv-qualifier
957///
958///       cv-qualifier: [C++ 7.1.5.1]
959///         'const'
960///         'volatile'
961/// [C99]   'restrict'
962///
963///       simple-type-specifier: [ C++ 7.1.5.2]
964///         '::'[opt] nested-name-specifier[opt] type-name [TODO]
965///         '::'[opt] nested-name-specifier 'template' template-id [TODO]
966///         'char'
967///         'wchar_t'
968///         'bool'
969///         'short'
970///         'int'
971///         'long'
972///         'signed'
973///         'unsigned'
974///         'float'
975///         'double'
976///         'void'
977/// [C99]   '_Bool'
978/// [C99]   '_Complex'
979/// [C99]   '_Imaginary'  // Removed in TC2?
980/// [GNU]   '_Decimal32'
981/// [GNU]   '_Decimal64'
982/// [GNU]   '_Decimal128'
983/// [GNU]   typeof-specifier
984/// [OBJC]  class-name objc-protocol-refs[opt]    [TODO]
985/// [OBJC]  typedef-name objc-protocol-refs[opt]  [TODO]
986bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, int& isInvalid,
987                                        const char *&PrevSpec,
988                                        TemplateParameterLists *TemplateParams){
989  SourceLocation Loc = Tok.getLocation();
990
991  switch (Tok.getKind()) {
992  case tok::identifier:   // foo::bar
993  case tok::kw_typename:  // typename foo::bar
994    // Annotate typenames and C++ scope specifiers.  If we get one, just
995    // recurse to handle whatever we get.
996    if (TryAnnotateTypeOrScopeToken())
997      return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec,TemplateParams);
998    // Otherwise, not a type specifier.
999    return false;
1000  case tok::coloncolon:   // ::foo::bar
1001    if (NextToken().is(tok::kw_new) ||    // ::new
1002        NextToken().is(tok::kw_delete))   // ::delete
1003      return false;
1004
1005    // Annotate typenames and C++ scope specifiers.  If we get one, just
1006    // recurse to handle whatever we get.
1007    if (TryAnnotateTypeOrScopeToken())
1008      return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec,TemplateParams);
1009    // Otherwise, not a type specifier.
1010    return false;
1011
1012  // simple-type-specifier:
1013  case tok::annot_typename: {
1014    if (Tok.getAnnotationValue())
1015      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1016                                     Tok.getAnnotationValue());
1017    else
1018      DS.SetTypeSpecError();
1019    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1020    ConsumeToken(); // The typename
1021
1022    // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1023    // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1024    // Objective-C interface.  If we don't have Objective-C or a '<', this is
1025    // just a normal reference to a typedef name.
1026    if (!Tok.is(tok::less) || !getLang().ObjC1)
1027      return true;
1028
1029    SourceLocation EndProtoLoc;
1030    llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1031    ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
1032    DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size());
1033
1034    DS.SetRangeEnd(EndProtoLoc);
1035    return true;
1036  }
1037
1038  case tok::kw_short:
1039    isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec);
1040    break;
1041  case tok::kw_long:
1042    if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1043      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec);
1044    else
1045      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec);
1046    break;
1047  case tok::kw_signed:
1048    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec);
1049    break;
1050  case tok::kw_unsigned:
1051    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec);
1052    break;
1053  case tok::kw__Complex:
1054    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec);
1055    break;
1056  case tok::kw__Imaginary:
1057    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec);
1058    break;
1059  case tok::kw_void:
1060    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec);
1061    break;
1062  case tok::kw_char:
1063    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec);
1064    break;
1065  case tok::kw_int:
1066    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec);
1067    break;
1068  case tok::kw_float:
1069    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec);
1070    break;
1071  case tok::kw_double:
1072    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec);
1073    break;
1074  case tok::kw_wchar_t:
1075    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec);
1076    break;
1077  case tok::kw_bool:
1078  case tok::kw__Bool:
1079    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec);
1080    break;
1081  case tok::kw__Decimal32:
1082    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec);
1083    break;
1084  case tok::kw__Decimal64:
1085    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec);
1086    break;
1087  case tok::kw__Decimal128:
1088    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec);
1089    break;
1090
1091  // class-specifier:
1092  case tok::kw_class:
1093  case tok::kw_struct:
1094  case tok::kw_union: {
1095    tok::TokenKind Kind = Tok.getKind();
1096    ConsumeToken();
1097    ParseClassSpecifier(Kind, Loc, DS, TemplateParams);
1098    return true;
1099  }
1100
1101  // enum-specifier:
1102  case tok::kw_enum:
1103    ConsumeToken();
1104    ParseEnumSpecifier(Loc, DS);
1105    return true;
1106
1107  // cv-qualifier:
1108  case tok::kw_const:
1109    isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
1110                               getLang())*2;
1111    break;
1112  case tok::kw_volatile:
1113    isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
1114                               getLang())*2;
1115    break;
1116  case tok::kw_restrict:
1117    isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1118                               getLang())*2;
1119    break;
1120
1121  // GNU typeof support.
1122  case tok::kw_typeof:
1123    ParseTypeofSpecifier(DS);
1124    return true;
1125
1126  case tok::kw___cdecl:
1127  case tok::kw___stdcall:
1128  case tok::kw___fastcall:
1129    if (!PP.getLangOptions().Microsoft) return false;
1130    ConsumeToken();
1131    return true;
1132
1133  default:
1134    // Not a type-specifier; do nothing.
1135    return false;
1136  }
1137
1138  // If the specifier combination wasn't legal, issue a diagnostic.
1139  if (isInvalid) {
1140    assert(PrevSpec && "Method did not return previous specifier!");
1141    // Pick between error or extwarn.
1142    unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination
1143                                     : diag::ext_duplicate_declspec;
1144    Diag(Tok, DiagID) << PrevSpec;
1145  }
1146  DS.SetRangeEnd(Tok.getLocation());
1147  ConsumeToken(); // whatever we parsed above.
1148  return true;
1149}
1150
1151/// ParseStructDeclaration - Parse a struct declaration without the terminating
1152/// semicolon.
1153///
1154///       struct-declaration:
1155///         specifier-qualifier-list struct-declarator-list
1156/// [GNU]   __extension__ struct-declaration
1157/// [GNU]   specifier-qualifier-list
1158///       struct-declarator-list:
1159///         struct-declarator
1160///         struct-declarator-list ',' struct-declarator
1161/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
1162///       struct-declarator:
1163///         declarator
1164/// [GNU]   declarator attributes[opt]
1165///         declarator[opt] ':' constant-expression
1166/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
1167///
1168void Parser::
1169ParseStructDeclaration(DeclSpec &DS,
1170                       llvm::SmallVectorImpl<FieldDeclarator> &Fields) {
1171  if (Tok.is(tok::kw___extension__)) {
1172    // __extension__ silences extension warnings in the subexpression.
1173    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1174    ConsumeToken();
1175    return ParseStructDeclaration(DS, Fields);
1176  }
1177
1178  // Parse the common specifier-qualifiers-list piece.
1179  SourceLocation DSStart = Tok.getLocation();
1180  ParseSpecifierQualifierList(DS);
1181
1182  // If there are no declarators, this is a free-standing declaration
1183  // specifier. Let the actions module cope with it.
1184  if (Tok.is(tok::semi)) {
1185    Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
1186    return;
1187  }
1188
1189  // Read struct-declarators until we find the semicolon.
1190  Fields.push_back(FieldDeclarator(DS));
1191  while (1) {
1192    FieldDeclarator &DeclaratorInfo = Fields.back();
1193
1194    /// struct-declarator: declarator
1195    /// struct-declarator: declarator[opt] ':' constant-expression
1196    if (Tok.isNot(tok::colon))
1197      ParseDeclarator(DeclaratorInfo.D);
1198
1199    if (Tok.is(tok::colon)) {
1200      ConsumeToken();
1201      OwningExprResult Res(ParseConstantExpression());
1202      if (Res.isInvalid())
1203        SkipUntil(tok::semi, true, true);
1204      else
1205        DeclaratorInfo.BitfieldSize = Res.release();
1206    }
1207
1208    // If attributes exist after the declarator, parse them.
1209    if (Tok.is(tok::kw___attribute)) {
1210      SourceLocation Loc;
1211      AttributeList *AttrList = ParseAttributes(&Loc);
1212      DeclaratorInfo.D.AddAttributes(AttrList, Loc);
1213    }
1214
1215    // If we don't have a comma, it is either the end of the list (a ';')
1216    // or an error, bail out.
1217    if (Tok.isNot(tok::comma))
1218      return;
1219
1220    // Consume the comma.
1221    ConsumeToken();
1222
1223    // Parse the next declarator.
1224    Fields.push_back(FieldDeclarator(DS));
1225
1226    // Attributes are only allowed on the second declarator.
1227    if (Tok.is(tok::kw___attribute)) {
1228      SourceLocation Loc;
1229      AttributeList *AttrList = ParseAttributes(&Loc);
1230      Fields.back().D.AddAttributes(AttrList, Loc);
1231    }
1232  }
1233}
1234
1235/// ParseStructUnionBody
1236///       struct-contents:
1237///         struct-declaration-list
1238/// [EXT]   empty
1239/// [GNU]   "struct-declaration-list" without terminatoring ';'
1240///       struct-declaration-list:
1241///         struct-declaration
1242///         struct-declaration-list struct-declaration
1243/// [OBC]   '@' 'defs' '(' class-name ')'
1244///
1245void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
1246                                  unsigned TagType, DeclPtrTy TagDecl) {
1247  PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions,
1248                                        PP.getSourceManager(),
1249                                        "parsing struct/union body");
1250
1251  SourceLocation LBraceLoc = ConsumeBrace();
1252
1253  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
1254  Actions.ActOnTagStartDefinition(CurScope, TagDecl);
1255
1256  // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
1257  // C++.
1258  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1259    Diag(Tok, diag::ext_empty_struct_union_enum)
1260      << DeclSpec::getSpecifierName((DeclSpec::TST)TagType);
1261
1262  llvm::SmallVector<DeclPtrTy, 32> FieldDecls;
1263  llvm::SmallVector<FieldDeclarator, 8> FieldDeclarators;
1264
1265  // While we still have something to read, read the declarations in the struct.
1266  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1267    // Each iteration of this loop reads one struct-declaration.
1268
1269    // Check for extraneous top-level semicolon.
1270    if (Tok.is(tok::semi)) {
1271      Diag(Tok, diag::ext_extra_struct_semi)
1272        << CodeModificationHint::CreateRemoval(SourceRange(Tok.getLocation()));
1273      ConsumeToken();
1274      continue;
1275    }
1276
1277    // Parse all the comma separated declarators.
1278    DeclSpec DS;
1279    FieldDeclarators.clear();
1280    if (!Tok.is(tok::at)) {
1281      ParseStructDeclaration(DS, FieldDeclarators);
1282
1283      // Convert them all to fields.
1284      for (unsigned i = 0, e = FieldDeclarators.size(); i != e; ++i) {
1285        FieldDeclarator &FD = FieldDeclarators[i];
1286        // Install the declarator into the current TagDecl.
1287        DeclPtrTy Field = Actions.ActOnField(CurScope, TagDecl,
1288                                             DS.getSourceRange().getBegin(),
1289                                             FD.D, FD.BitfieldSize);
1290        FieldDecls.push_back(Field);
1291      }
1292    } else { // Handle @defs
1293      ConsumeToken();
1294      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
1295        Diag(Tok, diag::err_unexpected_at);
1296        SkipUntil(tok::semi, true, true);
1297        continue;
1298      }
1299      ConsumeToken();
1300      ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
1301      if (!Tok.is(tok::identifier)) {
1302        Diag(Tok, diag::err_expected_ident);
1303        SkipUntil(tok::semi, true, true);
1304        continue;
1305      }
1306      llvm::SmallVector<DeclPtrTy, 16> Fields;
1307      Actions.ActOnDefs(CurScope, TagDecl, Tok.getLocation(),
1308                        Tok.getIdentifierInfo(), Fields);
1309      FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
1310      ConsumeToken();
1311      ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
1312    }
1313
1314    if (Tok.is(tok::semi)) {
1315      ConsumeToken();
1316    } else if (Tok.is(tok::r_brace)) {
1317      Diag(Tok, diag::ext_expected_semi_decl_list);
1318      break;
1319    } else {
1320      Diag(Tok, diag::err_expected_semi_decl_list);
1321      // Skip to end of block or statement
1322      SkipUntil(tok::r_brace, true, true);
1323    }
1324  }
1325
1326  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1327
1328  AttributeList *AttrList = 0;
1329  // If attributes exist after struct contents, parse them.
1330  if (Tok.is(tok::kw___attribute))
1331    AttrList = ParseAttributes();
1332
1333  Actions.ActOnFields(CurScope,
1334                      RecordLoc,TagDecl,&FieldDecls[0],FieldDecls.size(),
1335                      LBraceLoc, RBraceLoc,
1336                      AttrList);
1337  StructScope.Exit();
1338  Actions.ActOnTagFinishDefinition(CurScope, TagDecl);
1339}
1340
1341
1342/// ParseEnumSpecifier
1343///       enum-specifier: [C99 6.7.2.2]
1344///         'enum' identifier[opt] '{' enumerator-list '}'
1345///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
1346/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
1347///                                                 '}' attributes[opt]
1348///         'enum' identifier
1349/// [GNU]   'enum' attributes[opt] identifier
1350///
1351/// [C++] elaborated-type-specifier:
1352/// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
1353///
1354void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
1355                                AccessSpecifier AS) {
1356  // Parse the tag portion of this.
1357
1358  AttributeList *Attr = 0;
1359  // If attributes exist after tag, parse them.
1360  if (Tok.is(tok::kw___attribute))
1361    Attr = ParseAttributes();
1362
1363  CXXScopeSpec SS;
1364  if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS)) {
1365    if (Tok.isNot(tok::identifier)) {
1366      Diag(Tok, diag::err_expected_ident);
1367      if (Tok.isNot(tok::l_brace)) {
1368        // Has no name and is not a definition.
1369        // Skip the rest of this declarator, up until the comma or semicolon.
1370        SkipUntil(tok::comma, true);
1371        return;
1372      }
1373    }
1374  }
1375
1376  // Must have either 'enum name' or 'enum {...}'.
1377  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) {
1378    Diag(Tok, diag::err_expected_ident_lbrace);
1379
1380    // Skip the rest of this declarator, up until the comma or semicolon.
1381    SkipUntil(tok::comma, true);
1382    return;
1383  }
1384
1385  // If an identifier is present, consume and remember it.
1386  IdentifierInfo *Name = 0;
1387  SourceLocation NameLoc;
1388  if (Tok.is(tok::identifier)) {
1389    Name = Tok.getIdentifierInfo();
1390    NameLoc = ConsumeToken();
1391  }
1392
1393  // There are three options here.  If we have 'enum foo;', then this is a
1394  // forward declaration.  If we have 'enum foo {...' then this is a
1395  // definition. Otherwise we have something like 'enum foo xyz', a reference.
1396  //
1397  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
1398  // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
1399  // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
1400  //
1401  Action::TagKind TK;
1402  if (Tok.is(tok::l_brace))
1403    TK = Action::TK_Definition;
1404  else if (Tok.is(tok::semi))
1405    TK = Action::TK_Declaration;
1406  else
1407    TK = Action::TK_Reference;
1408  DeclPtrTy TagDecl = Actions.ActOnTag(CurScope, DeclSpec::TST_enum, TK,
1409                                       StartLoc, SS, Name, NameLoc, Attr, AS);
1410
1411  if (Tok.is(tok::l_brace))
1412    ParseEnumBody(StartLoc, TagDecl);
1413
1414  // TODO: semantic analysis on the declspec for enums.
1415  const char *PrevSpec = 0;
1416  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, PrevSpec,
1417                         TagDecl.getAs<void>()))
1418    Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
1419}
1420
1421/// ParseEnumBody - Parse a {} enclosed enumerator-list.
1422///       enumerator-list:
1423///         enumerator
1424///         enumerator-list ',' enumerator
1425///       enumerator:
1426///         enumeration-constant
1427///         enumeration-constant '=' constant-expression
1428///       enumeration-constant:
1429///         identifier
1430///
1431void Parser::ParseEnumBody(SourceLocation StartLoc, DeclPtrTy EnumDecl) {
1432  // Enter the scope of the enum body and start the definition.
1433  ParseScope EnumScope(this, Scope::DeclScope);
1434  Actions.ActOnTagStartDefinition(CurScope, EnumDecl);
1435
1436  SourceLocation LBraceLoc = ConsumeBrace();
1437
1438  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
1439  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1440    Diag(Tok, diag::ext_empty_struct_union_enum) << "enum";
1441
1442  llvm::SmallVector<DeclPtrTy, 32> EnumConstantDecls;
1443
1444  DeclPtrTy LastEnumConstDecl;
1445
1446  // Parse the enumerator-list.
1447  while (Tok.is(tok::identifier)) {
1448    IdentifierInfo *Ident = Tok.getIdentifierInfo();
1449    SourceLocation IdentLoc = ConsumeToken();
1450
1451    SourceLocation EqualLoc;
1452    OwningExprResult AssignedVal(Actions);
1453    if (Tok.is(tok::equal)) {
1454      EqualLoc = ConsumeToken();
1455      AssignedVal = ParseConstantExpression();
1456      if (AssignedVal.isInvalid())
1457        SkipUntil(tok::comma, tok::r_brace, true, true);
1458    }
1459
1460    // Install the enumerator constant into EnumDecl.
1461    DeclPtrTy EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl,
1462                                                        LastEnumConstDecl,
1463                                                        IdentLoc, Ident,
1464                                                        EqualLoc,
1465                                                        AssignedVal.release());
1466    EnumConstantDecls.push_back(EnumConstDecl);
1467    LastEnumConstDecl = EnumConstDecl;
1468
1469    if (Tok.isNot(tok::comma))
1470      break;
1471    SourceLocation CommaLoc = ConsumeToken();
1472
1473    if (Tok.isNot(tok::identifier) &&
1474        !(getLang().C99 || getLang().CPlusPlus0x))
1475      Diag(CommaLoc, diag::ext_enumerator_list_comma)
1476        << getLang().CPlusPlus
1477        << CodeModificationHint::CreateRemoval((SourceRange(CommaLoc)));
1478  }
1479
1480  // Eat the }.
1481  MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1482
1483  Actions.ActOnEnumBody(StartLoc, EnumDecl, &EnumConstantDecls[0],
1484                        EnumConstantDecls.size());
1485
1486  Action::AttrTy *AttrList = 0;
1487  // If attributes exist after the identifier list, parse them.
1488  if (Tok.is(tok::kw___attribute))
1489    AttrList = ParseAttributes(); // FIXME: where do they do?
1490
1491  EnumScope.Exit();
1492  Actions.ActOnTagFinishDefinition(CurScope, EnumDecl);
1493}
1494
1495/// isTypeSpecifierQualifier - Return true if the current token could be the
1496/// start of a type-qualifier-list.
1497bool Parser::isTypeQualifier() const {
1498  switch (Tok.getKind()) {
1499  default: return false;
1500    // type-qualifier
1501  case tok::kw_const:
1502  case tok::kw_volatile:
1503  case tok::kw_restrict:
1504    return true;
1505  }
1506}
1507
1508/// isTypeSpecifierQualifier - Return true if the current token could be the
1509/// start of a specifier-qualifier-list.
1510bool Parser::isTypeSpecifierQualifier() {
1511  switch (Tok.getKind()) {
1512  default: return false;
1513
1514  case tok::identifier:   // foo::bar
1515  case tok::kw_typename:  // typename T::type
1516    // Annotate typenames and C++ scope specifiers.  If we get one, just
1517    // recurse to handle whatever we get.
1518    if (TryAnnotateTypeOrScopeToken())
1519      return isTypeSpecifierQualifier();
1520    // Otherwise, not a type specifier.
1521    return false;
1522
1523  case tok::coloncolon:   // ::foo::bar
1524    if (NextToken().is(tok::kw_new) ||    // ::new
1525        NextToken().is(tok::kw_delete))   // ::delete
1526      return false;
1527
1528    // Annotate typenames and C++ scope specifiers.  If we get one, just
1529    // recurse to handle whatever we get.
1530    if (TryAnnotateTypeOrScopeToken())
1531      return isTypeSpecifierQualifier();
1532    // Otherwise, not a type specifier.
1533    return false;
1534
1535    // GNU attributes support.
1536  case tok::kw___attribute:
1537    // GNU typeof support.
1538  case tok::kw_typeof:
1539
1540    // type-specifiers
1541  case tok::kw_short:
1542  case tok::kw_long:
1543  case tok::kw_signed:
1544  case tok::kw_unsigned:
1545  case tok::kw__Complex:
1546  case tok::kw__Imaginary:
1547  case tok::kw_void:
1548  case tok::kw_char:
1549  case tok::kw_wchar_t:
1550  case tok::kw_int:
1551  case tok::kw_float:
1552  case tok::kw_double:
1553  case tok::kw_bool:
1554  case tok::kw__Bool:
1555  case tok::kw__Decimal32:
1556  case tok::kw__Decimal64:
1557  case tok::kw__Decimal128:
1558
1559    // struct-or-union-specifier (C99) or class-specifier (C++)
1560  case tok::kw_class:
1561  case tok::kw_struct:
1562  case tok::kw_union:
1563    // enum-specifier
1564  case tok::kw_enum:
1565
1566    // type-qualifier
1567  case tok::kw_const:
1568  case tok::kw_volatile:
1569  case tok::kw_restrict:
1570
1571    // typedef-name
1572  case tok::annot_typename:
1573    return true;
1574
1575    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
1576  case tok::less:
1577    return getLang().ObjC1;
1578
1579  case tok::kw___cdecl:
1580  case tok::kw___stdcall:
1581  case tok::kw___fastcall:
1582    return PP.getLangOptions().Microsoft;
1583  }
1584}
1585
1586/// isDeclarationSpecifier() - Return true if the current token is part of a
1587/// declaration specifier.
1588bool Parser::isDeclarationSpecifier() {
1589  switch (Tok.getKind()) {
1590  default: return false;
1591
1592  case tok::identifier:   // foo::bar
1593    // Unfortunate hack to support "Class.factoryMethod" notation.
1594    if (getLang().ObjC1 && NextToken().is(tok::period))
1595      return false;
1596    // Fall through
1597
1598  case tok::kw_typename: // typename T::type
1599    // Annotate typenames and C++ scope specifiers.  If we get one, just
1600    // recurse to handle whatever we get.
1601    if (TryAnnotateTypeOrScopeToken())
1602      return isDeclarationSpecifier();
1603    // Otherwise, not a declaration specifier.
1604    return false;
1605  case tok::coloncolon:   // ::foo::bar
1606    if (NextToken().is(tok::kw_new) ||    // ::new
1607        NextToken().is(tok::kw_delete))   // ::delete
1608      return false;
1609
1610    // Annotate typenames and C++ scope specifiers.  If we get one, just
1611    // recurse to handle whatever we get.
1612    if (TryAnnotateTypeOrScopeToken())
1613      return isDeclarationSpecifier();
1614    // Otherwise, not a declaration specifier.
1615    return false;
1616
1617    // storage-class-specifier
1618  case tok::kw_typedef:
1619  case tok::kw_extern:
1620  case tok::kw___private_extern__:
1621  case tok::kw_static:
1622  case tok::kw_auto:
1623  case tok::kw_register:
1624  case tok::kw___thread:
1625
1626    // type-specifiers
1627  case tok::kw_short:
1628  case tok::kw_long:
1629  case tok::kw_signed:
1630  case tok::kw_unsigned:
1631  case tok::kw__Complex:
1632  case tok::kw__Imaginary:
1633  case tok::kw_void:
1634  case tok::kw_char:
1635  case tok::kw_wchar_t:
1636  case tok::kw_int:
1637  case tok::kw_float:
1638  case tok::kw_double:
1639  case tok::kw_bool:
1640  case tok::kw__Bool:
1641  case tok::kw__Decimal32:
1642  case tok::kw__Decimal64:
1643  case tok::kw__Decimal128:
1644
1645    // struct-or-union-specifier (C99) or class-specifier (C++)
1646  case tok::kw_class:
1647  case tok::kw_struct:
1648  case tok::kw_union:
1649    // enum-specifier
1650  case tok::kw_enum:
1651
1652    // type-qualifier
1653  case tok::kw_const:
1654  case tok::kw_volatile:
1655  case tok::kw_restrict:
1656
1657    // function-specifier
1658  case tok::kw_inline:
1659  case tok::kw_virtual:
1660  case tok::kw_explicit:
1661
1662    // typedef-name
1663  case tok::annot_typename:
1664
1665    // GNU typeof support.
1666  case tok::kw_typeof:
1667
1668    // GNU attributes.
1669  case tok::kw___attribute:
1670    return true;
1671
1672    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
1673  case tok::less:
1674    return getLang().ObjC1;
1675
1676  case tok::kw___declspec:
1677  case tok::kw___cdecl:
1678  case tok::kw___stdcall:
1679  case tok::kw___fastcall:
1680    return PP.getLangOptions().Microsoft;
1681  }
1682}
1683
1684
1685/// ParseTypeQualifierListOpt
1686///       type-qualifier-list: [C99 6.7.5]
1687///         type-qualifier
1688/// [GNU]   attributes                        [ only if AttributesAllowed=true ]
1689///         type-qualifier-list type-qualifier
1690/// [GNU]   type-qualifier-list attributes    [ only if AttributesAllowed=true ]
1691///
1692void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, bool AttributesAllowed) {
1693  while (1) {
1694    int isInvalid = false;
1695    const char *PrevSpec = 0;
1696    SourceLocation Loc = Tok.getLocation();
1697
1698    switch (Tok.getKind()) {
1699    case tok::kw_const:
1700      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
1701                                 getLang())*2;
1702      break;
1703    case tok::kw_volatile:
1704      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
1705                                 getLang())*2;
1706      break;
1707    case tok::kw_restrict:
1708      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1709                                 getLang())*2;
1710      break;
1711    case tok::kw___ptr64:
1712    case tok::kw___cdecl:
1713    case tok::kw___stdcall:
1714    case tok::kw___fastcall:
1715      if (!PP.getLangOptions().Microsoft)
1716        goto DoneWithTypeQuals;
1717      // Just ignore it.
1718      break;
1719    case tok::kw___attribute:
1720      if (AttributesAllowed) {
1721        DS.AddAttributes(ParseAttributes());
1722        continue; // do *not* consume the next token!
1723      }
1724      // otherwise, FALL THROUGH!
1725    default:
1726      DoneWithTypeQuals:
1727      // If this is not a type-qualifier token, we're done reading type
1728      // qualifiers.  First verify that DeclSpec's are consistent.
1729      DS.Finish(Diags, PP);
1730      return;
1731    }
1732
1733    // If the specifier combination wasn't legal, issue a diagnostic.
1734    if (isInvalid) {
1735      assert(PrevSpec && "Method did not return previous specifier!");
1736      // Pick between error or extwarn.
1737      unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination
1738                                      : diag::ext_duplicate_declspec;
1739      Diag(Tok, DiagID) << PrevSpec;
1740    }
1741    ConsumeToken();
1742  }
1743}
1744
1745
1746/// ParseDeclarator - Parse and verify a newly-initialized declarator.
1747///
1748void Parser::ParseDeclarator(Declarator &D) {
1749  /// This implements the 'declarator' production in the C grammar, then checks
1750  /// for well-formedness and issues diagnostics.
1751  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
1752}
1753
1754/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
1755/// is parsed by the function passed to it. Pass null, and the direct-declarator
1756/// isn't parsed at all, making this function effectively parse the C++
1757/// ptr-operator production.
1758///
1759///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
1760/// [C]     pointer[opt] direct-declarator
1761/// [C++]   direct-declarator
1762/// [C++]   ptr-operator declarator
1763///
1764///       pointer: [C99 6.7.5]
1765///         '*' type-qualifier-list[opt]
1766///         '*' type-qualifier-list[opt] pointer
1767///
1768///       ptr-operator:
1769///         '*' cv-qualifier-seq[opt]
1770///         '&'
1771/// [C++0x] '&&'
1772/// [GNU]   '&' restrict[opt] attributes[opt]
1773/// [GNU?]  '&&' restrict[opt] attributes[opt]
1774///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
1775void Parser::ParseDeclaratorInternal(Declarator &D,
1776                                     DirectDeclParseFunction DirectDeclParser) {
1777
1778  // C++ member pointers start with a '::' or a nested-name.
1779  // Member pointers get special handling, since there's no place for the
1780  // scope spec in the generic path below.
1781  if (getLang().CPlusPlus &&
1782      (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
1783       Tok.is(tok::annot_cxxscope))) {
1784    CXXScopeSpec SS;
1785    if (ParseOptionalCXXScopeSpecifier(SS)) {
1786      if(Tok.isNot(tok::star)) {
1787        // The scope spec really belongs to the direct-declarator.
1788        D.getCXXScopeSpec() = SS;
1789        if (DirectDeclParser)
1790          (this->*DirectDeclParser)(D);
1791        return;
1792      }
1793
1794      SourceLocation Loc = ConsumeToken();
1795      D.SetRangeEnd(Loc);
1796      DeclSpec DS;
1797      ParseTypeQualifierListOpt(DS);
1798      D.ExtendWithDeclSpec(DS);
1799
1800      // Recurse to parse whatever is left.
1801      ParseDeclaratorInternal(D, DirectDeclParser);
1802
1803      // Sema will have to catch (syntactically invalid) pointers into global
1804      // scope. It has to catch pointers into namespace scope anyway.
1805      D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
1806                                                      Loc, DS.TakeAttributes()),
1807                    /* Don't replace range end. */SourceLocation());
1808      return;
1809    }
1810  }
1811
1812  tok::TokenKind Kind = Tok.getKind();
1813  // Not a pointer, C++ reference, or block.
1814  if (Kind != tok::star && Kind != tok::caret &&
1815      (Kind != tok::amp || !getLang().CPlusPlus) &&
1816      // We parse rvalue refs in C++03, because otherwise the errors are scary.
1817      (Kind != tok::ampamp || !getLang().CPlusPlus)) {
1818    if (DirectDeclParser)
1819      (this->*DirectDeclParser)(D);
1820    return;
1821  }
1822
1823  // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
1824  // '&&' -> rvalue reference
1825  SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
1826  D.SetRangeEnd(Loc);
1827
1828  if (Kind == tok::star || Kind == tok::caret) {
1829    // Is a pointer.
1830    DeclSpec DS;
1831
1832    ParseTypeQualifierListOpt(DS);
1833    D.ExtendWithDeclSpec(DS);
1834
1835    // Recursively parse the declarator.
1836    ParseDeclaratorInternal(D, DirectDeclParser);
1837    if (Kind == tok::star)
1838      // Remember that we parsed a pointer type, and remember the type-quals.
1839      D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
1840                                                DS.TakeAttributes()),
1841                    SourceLocation());
1842    else
1843      // Remember that we parsed a Block type, and remember the type-quals.
1844      D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
1845                                                     Loc),
1846                    SourceLocation());
1847  } else {
1848    // Is a reference
1849    DeclSpec DS;
1850
1851    // Complain about rvalue references in C++03, but then go on and build
1852    // the declarator.
1853    if (Kind == tok::ampamp && !getLang().CPlusPlus0x)
1854      Diag(Loc, diag::err_rvalue_reference);
1855
1856    // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
1857    // cv-qualifiers are introduced through the use of a typedef or of a
1858    // template type argument, in which case the cv-qualifiers are ignored.
1859    //
1860    // [GNU] Retricted references are allowed.
1861    // [GNU] Attributes on references are allowed.
1862    ParseTypeQualifierListOpt(DS);
1863    D.ExtendWithDeclSpec(DS);
1864
1865    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
1866      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1867        Diag(DS.getConstSpecLoc(),
1868             diag::err_invalid_reference_qualifier_application) << "const";
1869      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
1870        Diag(DS.getVolatileSpecLoc(),
1871             diag::err_invalid_reference_qualifier_application) << "volatile";
1872    }
1873
1874    // Recursively parse the declarator.
1875    ParseDeclaratorInternal(D, DirectDeclParser);
1876
1877    if (D.getNumTypeObjects() > 0) {
1878      // C++ [dcl.ref]p4: There shall be no references to references.
1879      DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
1880      if (InnerChunk.Kind == DeclaratorChunk::Reference) {
1881        if (const IdentifierInfo *II = D.getIdentifier())
1882          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
1883           << II;
1884        else
1885          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
1886            << "type name";
1887
1888        // Once we've complained about the reference-to-reference, we
1889        // can go ahead and build the (technically ill-formed)
1890        // declarator: reference collapsing will take care of it.
1891      }
1892    }
1893
1894    // Remember that we parsed a reference type. It doesn't have type-quals.
1895    D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
1896                                                DS.TakeAttributes(),
1897                                                Kind == tok::amp),
1898                  SourceLocation());
1899  }
1900}
1901
1902/// ParseDirectDeclarator
1903///       direct-declarator: [C99 6.7.5]
1904/// [C99]   identifier
1905///         '(' declarator ')'
1906/// [GNU]   '(' attributes declarator ')'
1907/// [C90]   direct-declarator '[' constant-expression[opt] ']'
1908/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1909/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1910/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1911/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
1912///         direct-declarator '(' parameter-type-list ')'
1913///         direct-declarator '(' identifier-list[opt] ')'
1914/// [GNU]   direct-declarator '(' parameter-forward-declarations
1915///                    parameter-type-list[opt] ')'
1916/// [C++]   direct-declarator '(' parameter-declaration-clause ')'
1917///                    cv-qualifier-seq[opt] exception-specification[opt]
1918/// [C++]   declarator-id
1919///
1920///       declarator-id: [C++ 8]
1921///         id-expression
1922///         '::'[opt] nested-name-specifier[opt] type-name
1923///
1924///       id-expression: [C++ 5.1]
1925///         unqualified-id
1926///         qualified-id            [TODO]
1927///
1928///       unqualified-id: [C++ 5.1]
1929///         identifier
1930///         operator-function-id
1931///         conversion-function-id  [TODO]
1932///          '~' class-name
1933///         template-id
1934///
1935void Parser::ParseDirectDeclarator(Declarator &D) {
1936  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
1937
1938  if (getLang().CPlusPlus) {
1939    if (D.mayHaveIdentifier()) {
1940      // ParseDeclaratorInternal might already have parsed the scope.
1941      bool afterCXXScope = D.getCXXScopeSpec().isSet() ||
1942        ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec());
1943      if (afterCXXScope) {
1944        // Change the declaration context for name lookup, until this function
1945        // is exited (and the declarator has been parsed).
1946        DeclScopeObj.EnterDeclaratorScope();
1947      }
1948
1949      if (Tok.is(tok::identifier)) {
1950        assert(Tok.getIdentifierInfo() && "Not an identifier?");
1951
1952        // If this identifier is the name of the current class, it's a
1953        // constructor name.
1954        if (Actions.isCurrentClassName(*Tok.getIdentifierInfo(),CurScope)){
1955          D.setConstructor(Actions.getTypeName(*Tok.getIdentifierInfo(),
1956                                               Tok.getLocation(), CurScope),
1957                           Tok.getLocation());
1958        // This is a normal identifier.
1959        } else
1960          D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1961        ConsumeToken();
1962        goto PastIdentifier;
1963      } else if (Tok.is(tok::annot_template_id)) {
1964        TemplateIdAnnotation *TemplateId
1965          = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1966
1967        // FIXME: Could this template-id name a constructor?
1968
1969        // FIXME: This is an egregious hack, where we silently ignore
1970        // the specialization (which should be a function template
1971        // specialization name) and use the name instead. This hack
1972        // will go away when we have support for function
1973        // specializations.
1974        D.SetIdentifier(TemplateId->Name, Tok.getLocation());
1975        TemplateId->Destroy();
1976        ConsumeToken();
1977        goto PastIdentifier;
1978      } else if (Tok.is(tok::kw_operator)) {
1979        SourceLocation OperatorLoc = Tok.getLocation();
1980        SourceLocation EndLoc;
1981
1982        // First try the name of an overloaded operator
1983        if (OverloadedOperatorKind Op = TryParseOperatorFunctionId(&EndLoc)) {
1984          D.setOverloadedOperator(Op, OperatorLoc, EndLoc);
1985        } else {
1986          // This must be a conversion function (C++ [class.conv.fct]).
1987          if (TypeTy *ConvType = ParseConversionFunctionId(&EndLoc))
1988            D.setConversionFunction(ConvType, OperatorLoc, EndLoc);
1989          else {
1990            D.SetIdentifier(0, Tok.getLocation());
1991          }
1992        }
1993        goto PastIdentifier;
1994      } else if (Tok.is(tok::tilde)) {
1995        // This should be a C++ destructor.
1996        SourceLocation TildeLoc = ConsumeToken();
1997        if (Tok.is(tok::identifier)) {
1998          // FIXME: Inaccurate.
1999          SourceLocation NameLoc = Tok.getLocation();
2000          SourceLocation EndLoc;
2001          TypeResult Type = ParseClassName(EndLoc);
2002          if (Type.isInvalid())
2003            D.SetIdentifier(0, TildeLoc);
2004          else
2005            D.setDestructor(Type.get(), TildeLoc, NameLoc);
2006        } else {
2007          Diag(Tok, diag::err_expected_class_name);
2008          D.SetIdentifier(0, TildeLoc);
2009        }
2010        goto PastIdentifier;
2011      }
2012
2013      // If we reached this point, token is not identifier and not '~'.
2014
2015      if (afterCXXScope) {
2016        Diag(Tok, diag::err_expected_unqualified_id);
2017        D.SetIdentifier(0, Tok.getLocation());
2018        D.setInvalidType(true);
2019        goto PastIdentifier;
2020      }
2021    }
2022  }
2023
2024  // If we reached this point, we are either in C/ObjC or the token didn't
2025  // satisfy any of the C++-specific checks.
2026  if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
2027    assert(!getLang().CPlusPlus &&
2028           "There's a C++-specific check for tok::identifier above");
2029    assert(Tok.getIdentifierInfo() && "Not an identifier?");
2030    D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2031    ConsumeToken();
2032  } else if (Tok.is(tok::l_paren)) {
2033    // direct-declarator: '(' declarator ')'
2034    // direct-declarator: '(' attributes declarator ')'
2035    // Example: 'char (*X)'   or 'int (*XX)(void)'
2036    ParseParenDeclarator(D);
2037  } else if (D.mayOmitIdentifier()) {
2038    // This could be something simple like "int" (in which case the declarator
2039    // portion is empty), if an abstract-declarator is allowed.
2040    D.SetIdentifier(0, Tok.getLocation());
2041  } else {
2042    if (D.getContext() == Declarator::MemberContext)
2043      Diag(Tok, diag::err_expected_member_name_or_semi)
2044        << D.getDeclSpec().getSourceRange();
2045    else if (getLang().CPlusPlus)
2046      Diag(Tok, diag::err_expected_unqualified_id);
2047    else
2048      Diag(Tok, diag::err_expected_ident_lparen);
2049    D.SetIdentifier(0, Tok.getLocation());
2050    D.setInvalidType(true);
2051  }
2052
2053 PastIdentifier:
2054  assert(D.isPastIdentifier() &&
2055         "Haven't past the location of the identifier yet?");
2056
2057  while (1) {
2058    if (Tok.is(tok::l_paren)) {
2059      // The paren may be part of a C++ direct initializer, eg. "int x(1);".
2060      // In such a case, check if we actually have a function declarator; if it
2061      // is not, the declarator has been fully parsed.
2062      if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
2063        // When not in file scope, warn for ambiguous function declarators, just
2064        // in case the author intended it as a variable definition.
2065        bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
2066        if (!isCXXFunctionDeclarator(warnIfAmbiguous))
2067          break;
2068      }
2069      ParseFunctionDeclarator(ConsumeParen(), D);
2070    } else if (Tok.is(tok::l_square)) {
2071      ParseBracketDeclarator(D);
2072    } else {
2073      break;
2074    }
2075  }
2076}
2077
2078/// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
2079/// only called before the identifier, so these are most likely just grouping
2080/// parens for precedence.  If we find that these are actually function
2081/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
2082///
2083///       direct-declarator:
2084///         '(' declarator ')'
2085/// [GNU]   '(' attributes declarator ')'
2086///         direct-declarator '(' parameter-type-list ')'
2087///         direct-declarator '(' identifier-list[opt] ')'
2088/// [GNU]   direct-declarator '(' parameter-forward-declarations
2089///                    parameter-type-list[opt] ')'
2090///
2091void Parser::ParseParenDeclarator(Declarator &D) {
2092  SourceLocation StartLoc = ConsumeParen();
2093  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
2094
2095  // Eat any attributes before we look at whether this is a grouping or function
2096  // declarator paren.  If this is a grouping paren, the attribute applies to
2097  // the type being built up, for example:
2098  //     int (__attribute__(()) *x)(long y)
2099  // If this ends up not being a grouping paren, the attribute applies to the
2100  // first argument, for example:
2101  //     int (__attribute__(()) int x)
2102  // In either case, we need to eat any attributes to be able to determine what
2103  // sort of paren this is.
2104  //
2105  AttributeList *AttrList = 0;
2106  bool RequiresArg = false;
2107  if (Tok.is(tok::kw___attribute)) {
2108    AttrList = ParseAttributes();
2109
2110    // We require that the argument list (if this is a non-grouping paren) be
2111    // present even if the attribute list was empty.
2112    RequiresArg = true;
2113  }
2114  // Eat any Microsoft extensions.
2115  while ((Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
2116          (Tok.is(tok::kw___fastcall))) && PP.getLangOptions().Microsoft)
2117    ConsumeToken();
2118
2119  // If we haven't past the identifier yet (or where the identifier would be
2120  // stored, if this is an abstract declarator), then this is probably just
2121  // grouping parens. However, if this could be an abstract-declarator, then
2122  // this could also be the start of function arguments (consider 'void()').
2123  bool isGrouping;
2124
2125  if (!D.mayOmitIdentifier()) {
2126    // If this can't be an abstract-declarator, this *must* be a grouping
2127    // paren, because we haven't seen the identifier yet.
2128    isGrouping = true;
2129  } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
2130             (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
2131             isDeclarationSpecifier()) {       // 'int(int)' is a function.
2132    // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
2133    // considered to be a type, not a K&R identifier-list.
2134    isGrouping = false;
2135  } else {
2136    // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
2137    isGrouping = true;
2138  }
2139
2140  // If this is a grouping paren, handle:
2141  // direct-declarator: '(' declarator ')'
2142  // direct-declarator: '(' attributes declarator ')'
2143  if (isGrouping) {
2144    bool hadGroupingParens = D.hasGroupingParens();
2145    D.setGroupingParens(true);
2146    if (AttrList)
2147      D.AddAttributes(AttrList, SourceLocation());
2148
2149    ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
2150    // Match the ')'.
2151    SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, StartLoc);
2152
2153    D.setGroupingParens(hadGroupingParens);
2154    D.SetRangeEnd(Loc);
2155    return;
2156  }
2157
2158  // Okay, if this wasn't a grouping paren, it must be the start of a function
2159  // argument list.  Recognize that this declarator will never have an
2160  // identifier (and remember where it would have been), then call into
2161  // ParseFunctionDeclarator to handle of argument list.
2162  D.SetIdentifier(0, Tok.getLocation());
2163
2164  ParseFunctionDeclarator(StartLoc, D, AttrList, RequiresArg);
2165}
2166
2167/// ParseFunctionDeclarator - We are after the identifier and have parsed the
2168/// declarator D up to a paren, which indicates that we are parsing function
2169/// arguments.
2170///
2171/// If AttrList is non-null, then the caller parsed those arguments immediately
2172/// after the open paren - they should be considered to be the first argument of
2173/// a parameter.  If RequiresArg is true, then the first argument of the
2174/// function is required to be present and required to not be an identifier
2175/// list.
2176///
2177/// This method also handles this portion of the grammar:
2178///       parameter-type-list: [C99 6.7.5]
2179///         parameter-list
2180///         parameter-list ',' '...'
2181///
2182///       parameter-list: [C99 6.7.5]
2183///         parameter-declaration
2184///         parameter-list ',' parameter-declaration
2185///
2186///       parameter-declaration: [C99 6.7.5]
2187///         declaration-specifiers declarator
2188/// [C++]   declaration-specifiers declarator '=' assignment-expression
2189/// [GNU]   declaration-specifiers declarator attributes
2190///         declaration-specifiers abstract-declarator[opt]
2191/// [C++]   declaration-specifiers abstract-declarator[opt]
2192///           '=' assignment-expression
2193/// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
2194///
2195/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]"
2196/// and "exception-specification[opt]".
2197///
2198void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
2199                                     AttributeList *AttrList,
2200                                     bool RequiresArg) {
2201  // lparen is already consumed!
2202  assert(D.isPastIdentifier() && "Should not call before identifier!");
2203
2204  // This parameter list may be empty.
2205  if (Tok.is(tok::r_paren)) {
2206    if (RequiresArg) {
2207      Diag(Tok, diag::err_argument_required_after_attribute);
2208      delete AttrList;
2209    }
2210
2211    SourceLocation Loc = ConsumeParen();  // Eat the closing ')'.
2212
2213    // cv-qualifier-seq[opt].
2214    DeclSpec DS;
2215    if (getLang().CPlusPlus) {
2216      ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2217      if (!DS.getSourceRange().getEnd().isInvalid())
2218        Loc = DS.getSourceRange().getEnd();
2219
2220      // Parse exception-specification[opt].
2221      if (Tok.is(tok::kw_throw))
2222        ParseExceptionSpecification(Loc);
2223    }
2224
2225    // Remember that we parsed a function type, and remember the attributes.
2226    // int() -> no prototype, no '...'.
2227    D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus,
2228                                               /*variadic*/ false,
2229                                               SourceLocation(),
2230                                               /*arglist*/ 0, 0,
2231                                               DS.getTypeQualifiers(),
2232                                               LParenLoc, D),
2233                  Loc);
2234    return;
2235  }
2236
2237  // Alternatively, this parameter list may be an identifier list form for a
2238  // K&R-style function:  void foo(a,b,c)
2239  if (!getLang().CPlusPlus && Tok.is(tok::identifier)) {
2240    if (!TryAnnotateTypeOrScopeToken()) {
2241      // K&R identifier lists can't have typedefs as identifiers, per
2242      // C99 6.7.5.3p11.
2243      if (RequiresArg) {
2244        Diag(Tok, diag::err_argument_required_after_attribute);
2245        delete AttrList;
2246      }
2247      // Identifier list.  Note that '(' identifier-list ')' is only allowed for
2248      // normal declarators, not for abstract-declarators.
2249      return ParseFunctionDeclaratorIdentifierList(LParenLoc, D);
2250    }
2251  }
2252
2253  // Finally, a normal, non-empty parameter type list.
2254
2255  // Build up an array of information about the parsed arguments.
2256  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
2257
2258  // Enter function-declaration scope, limiting any declarators to the
2259  // function prototype scope, including parameter declarators.
2260  ParseScope PrototypeScope(this,
2261                            Scope::FunctionPrototypeScope|Scope::DeclScope);
2262
2263  bool IsVariadic = false;
2264  SourceLocation EllipsisLoc;
2265  while (1) {
2266    if (Tok.is(tok::ellipsis)) {
2267      IsVariadic = true;
2268      EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
2269      break;
2270    }
2271
2272    SourceLocation DSStart = Tok.getLocation();
2273
2274    // Parse the declaration-specifiers.
2275    DeclSpec DS;
2276
2277    // If the caller parsed attributes for the first argument, add them now.
2278    if (AttrList) {
2279      DS.AddAttributes(AttrList);
2280      AttrList = 0;  // Only apply the attributes to the first parameter.
2281    }
2282    ParseDeclarationSpecifiers(DS);
2283
2284    // Parse the declarator.  This is "PrototypeContext", because we must
2285    // accept either 'declarator' or 'abstract-declarator' here.
2286    Declarator ParmDecl(DS, Declarator::PrototypeContext);
2287    ParseDeclarator(ParmDecl);
2288
2289    // Parse GNU attributes, if present.
2290    if (Tok.is(tok::kw___attribute)) {
2291      SourceLocation Loc;
2292      AttributeList *AttrList = ParseAttributes(&Loc);
2293      ParmDecl.AddAttributes(AttrList, Loc);
2294    }
2295
2296    // Remember this parsed parameter in ParamInfo.
2297    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
2298
2299    // DefArgToks is used when the parsing of default arguments needs
2300    // to be delayed.
2301    CachedTokens *DefArgToks = 0;
2302
2303    // If no parameter was specified, verify that *something* was specified,
2304    // otherwise we have a missing type and identifier.
2305    if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
2306        ParmDecl.getNumTypeObjects() == 0) {
2307      // Completely missing, emit error.
2308      Diag(DSStart, diag::err_missing_param);
2309    } else {
2310      // Otherwise, we have something.  Add it and let semantic analysis try
2311      // to grok it and add the result to the ParamInfo we are building.
2312
2313      // Inform the actions module about the parameter declarator, so it gets
2314      // added to the current scope.
2315      DeclPtrTy Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl);
2316
2317      // Parse the default argument, if any. We parse the default
2318      // arguments in all dialects; the semantic analysis in
2319      // ActOnParamDefaultArgument will reject the default argument in
2320      // C.
2321      if (Tok.is(tok::equal)) {
2322        SourceLocation EqualLoc = Tok.getLocation();
2323
2324        // Parse the default argument
2325        if (D.getContext() == Declarator::MemberContext) {
2326          // If we're inside a class definition, cache the tokens
2327          // corresponding to the default argument. We'll actually parse
2328          // them when we see the end of the class definition.
2329          // FIXME: Templates will require something similar.
2330          // FIXME: Can we use a smart pointer for Toks?
2331          DefArgToks = new CachedTokens;
2332
2333          if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
2334                                    tok::semi, false)) {
2335            delete DefArgToks;
2336            DefArgToks = 0;
2337            Actions.ActOnParamDefaultArgumentError(Param);
2338          } else
2339            Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc);
2340        } else {
2341          // Consume the '='.
2342          ConsumeToken();
2343
2344          OwningExprResult DefArgResult(ParseAssignmentExpression());
2345          if (DefArgResult.isInvalid()) {
2346            Actions.ActOnParamDefaultArgumentError(Param);
2347            SkipUntil(tok::comma, tok::r_paren, true, true);
2348          } else {
2349            // Inform the actions module about the default argument
2350            Actions.ActOnParamDefaultArgument(Param, EqualLoc,
2351                                              move(DefArgResult));
2352          }
2353        }
2354      }
2355
2356      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
2357                                          ParmDecl.getIdentifierLoc(), Param,
2358                                          DefArgToks));
2359    }
2360
2361    // If the next token is a comma, consume it and keep reading arguments.
2362    if (Tok.isNot(tok::comma)) break;
2363
2364    // Consume the comma.
2365    ConsumeToken();
2366  }
2367
2368  // Leave prototype scope.
2369  PrototypeScope.Exit();
2370
2371  // If we have the closing ')', eat it.
2372  SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2373
2374  DeclSpec DS;
2375  if (getLang().CPlusPlus) {
2376    // Parse cv-qualifier-seq[opt].
2377    ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2378      if (!DS.getSourceRange().getEnd().isInvalid())
2379        Loc = DS.getSourceRange().getEnd();
2380
2381    // Parse exception-specification[opt].
2382    if (Tok.is(tok::kw_throw))
2383      ParseExceptionSpecification(Loc);
2384  }
2385
2386  // Remember that we parsed a function type, and remember the attributes.
2387  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
2388                                             EllipsisLoc,
2389                                             &ParamInfo[0], ParamInfo.size(),
2390                                             DS.getTypeQualifiers(),
2391                                             LParenLoc, D),
2392                Loc);
2393}
2394
2395/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
2396/// we found a K&R-style identifier list instead of a type argument list.  The
2397/// current token is known to be the first identifier in the list.
2398///
2399///       identifier-list: [C99 6.7.5]
2400///         identifier
2401///         identifier-list ',' identifier
2402///
2403void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
2404                                                   Declarator &D) {
2405  // Build up an array of information about the parsed arguments.
2406  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
2407  llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
2408
2409  // If there was no identifier specified for the declarator, either we are in
2410  // an abstract-declarator, or we are in a parameter declarator which was found
2411  // to be abstract.  In abstract-declarators, identifier lists are not valid:
2412  // diagnose this.
2413  if (!D.getIdentifier())
2414    Diag(Tok, diag::ext_ident_list_in_param);
2415
2416  // Tok is known to be the first identifier in the list.  Remember this
2417  // identifier in ParamInfo.
2418  ParamsSoFar.insert(Tok.getIdentifierInfo());
2419  ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
2420                                                 Tok.getLocation(),
2421                                                 DeclPtrTy()));
2422
2423  ConsumeToken();  // eat the first identifier.
2424
2425  while (Tok.is(tok::comma)) {
2426    // Eat the comma.
2427    ConsumeToken();
2428
2429    // If this isn't an identifier, report the error and skip until ')'.
2430    if (Tok.isNot(tok::identifier)) {
2431      Diag(Tok, diag::err_expected_ident);
2432      SkipUntil(tok::r_paren);
2433      return;
2434    }
2435
2436    IdentifierInfo *ParmII = Tok.getIdentifierInfo();
2437
2438    // Reject 'typedef int y; int test(x, y)', but continue parsing.
2439    if (Actions.getTypeName(*ParmII, Tok.getLocation(), CurScope))
2440      Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
2441
2442    // Verify that the argument identifier has not already been mentioned.
2443    if (!ParamsSoFar.insert(ParmII)) {
2444      Diag(Tok, diag::err_param_redefinition) << ParmII;
2445    } else {
2446      // Remember this identifier in ParamInfo.
2447      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
2448                                                     Tok.getLocation(),
2449                                                     DeclPtrTy()));
2450    }
2451
2452    // Eat the identifier.
2453    ConsumeToken();
2454  }
2455
2456  // If we have the closing ')', eat it and we're done.
2457  SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2458
2459  // Remember that we parsed a function type, and remember the attributes.  This
2460  // function type is always a K&R style function type, which is not varargs and
2461  // has no prototype.
2462  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
2463                                             SourceLocation(),
2464                                             &ParamInfo[0], ParamInfo.size(),
2465                                             /*TypeQuals*/0, LParenLoc, D),
2466                RLoc);
2467}
2468
2469/// [C90]   direct-declarator '[' constant-expression[opt] ']'
2470/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2471/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2472/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2473/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
2474void Parser::ParseBracketDeclarator(Declarator &D) {
2475  SourceLocation StartLoc = ConsumeBracket();
2476
2477  // C array syntax has many features, but by-far the most common is [] and [4].
2478  // This code does a fast path to handle some of the most obvious cases.
2479  if (Tok.getKind() == tok::r_square) {
2480    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
2481    // Remember that we parsed the empty array type.
2482    OwningExprResult NumElements(Actions);
2483    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0, StartLoc),
2484                  EndLoc);
2485    return;
2486  } else if (Tok.getKind() == tok::numeric_constant &&
2487             GetLookAheadToken(1).is(tok::r_square)) {
2488    // [4] is very common.  Parse the numeric constant expression.
2489    OwningExprResult ExprRes(Actions.ActOnNumericConstant(Tok));
2490    ConsumeToken();
2491
2492    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
2493
2494    // If there was an error parsing the assignment-expression, recover.
2495    if (ExprRes.isInvalid())
2496      ExprRes.release();  // Deallocate expr, just use [].
2497
2498    // Remember that we parsed a array type, and remember its features.
2499    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0,
2500                                            ExprRes.release(), StartLoc),
2501                  EndLoc);
2502    return;
2503  }
2504
2505  // If valid, this location is the position where we read the 'static' keyword.
2506  SourceLocation StaticLoc;
2507  if (Tok.is(tok::kw_static))
2508    StaticLoc = ConsumeToken();
2509
2510  // If there is a type-qualifier-list, read it now.
2511  // Type qualifiers in an array subscript are a C99 feature.
2512  DeclSpec DS;
2513  ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2514
2515  // If we haven't already read 'static', check to see if there is one after the
2516  // type-qualifier-list.
2517  if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
2518    StaticLoc = ConsumeToken();
2519
2520  // Handle "direct-declarator [ type-qual-list[opt] * ]".
2521  bool isStar = false;
2522  OwningExprResult NumElements(Actions);
2523
2524  // Handle the case where we have '[*]' as the array size.  However, a leading
2525  // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
2526  // the the token after the star is a ']'.  Since stars in arrays are
2527  // infrequent, use of lookahead is not costly here.
2528  if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
2529    ConsumeToken();  // Eat the '*'.
2530
2531    if (StaticLoc.isValid()) {
2532      Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
2533      StaticLoc = SourceLocation();  // Drop the static.
2534    }
2535    isStar = true;
2536  } else if (Tok.isNot(tok::r_square)) {
2537    // Note, in C89, this production uses the constant-expr production instead
2538    // of assignment-expr.  The only difference is that assignment-expr allows
2539    // things like '=' and '*='.  Sema rejects these in C89 mode because they
2540    // are not i-c-e's, so we don't need to distinguish between the two here.
2541
2542    // Parse the assignment-expression now.
2543    NumElements = ParseAssignmentExpression();
2544  }
2545
2546  // If there was an error parsing the assignment-expression, recover.
2547  if (NumElements.isInvalid()) {
2548    // If the expression was invalid, skip it.
2549    SkipUntil(tok::r_square);
2550    return;
2551  }
2552
2553  SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
2554
2555  // Remember that we parsed a array type, and remember its features.
2556  D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
2557                                          StaticLoc.isValid(), isStar,
2558                                          NumElements.release(), StartLoc),
2559                EndLoc);
2560}
2561
2562/// [GNU]   typeof-specifier:
2563///           typeof ( expressions )
2564///           typeof ( type-name )
2565/// [GNU/C++] typeof unary-expression
2566///
2567void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
2568  assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
2569  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
2570  SourceLocation StartLoc = ConsumeToken();
2571
2572  if (Tok.isNot(tok::l_paren)) {
2573    if (!getLang().CPlusPlus) {
2574      Diag(Tok, diag::err_expected_lparen_after_id) << BuiltinII;
2575      return;
2576    }
2577
2578    OwningExprResult Result(ParseCastExpression(true/*isUnaryExpression*/));
2579    if (Result.isInvalid()) {
2580      DS.SetTypeSpecError();
2581      return;
2582    }
2583
2584    const char *PrevSpec = 0;
2585    // Check for duplicate type specifiers.
2586    if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
2587                           Result.release()))
2588      Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
2589
2590    // FIXME: Not accurate, the range gets one token more than it should.
2591    DS.SetRangeEnd(Tok.getLocation());
2592    return;
2593  }
2594
2595  SourceLocation LParenLoc = ConsumeParen(), RParenLoc;
2596
2597  if (isTypeIdInParens()) {
2598    Action::TypeResult Ty = ParseTypeName();
2599
2600    assert((Ty.isInvalid() || Ty.get()) &&
2601           "Parser::ParseTypeofSpecifier(): missing type");
2602
2603    if (Tok.isNot(tok::r_paren)) {
2604      MatchRHSPunctuation(tok::r_paren, LParenLoc);
2605      return;
2606    }
2607    RParenLoc = ConsumeParen();
2608
2609    if (Ty.isInvalid())
2610      DS.SetTypeSpecError();
2611    else {
2612      const char *PrevSpec = 0;
2613      // Check for duplicate type specifiers (e.g. "int typeof(int)").
2614      if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
2615                             Ty.get()))
2616        Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
2617    }
2618  } else { // we have an expression.
2619    OwningExprResult Result(ParseExpression());
2620
2621    if (Result.isInvalid() || Tok.isNot(tok::r_paren)) {
2622      MatchRHSPunctuation(tok::r_paren, LParenLoc);
2623      DS.SetTypeSpecError();
2624      return;
2625    }
2626    RParenLoc = ConsumeParen();
2627    const char *PrevSpec = 0;
2628    // Check for duplicate type specifiers (e.g. "int typeof(int)").
2629    if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
2630                           Result.release()))
2631      Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
2632  }
2633  DS.SetRangeEnd(RParenLoc);
2634}
2635
2636
2637