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