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