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