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