ParseDecl.cpp revision cee63fbf0e64ac526582312bf8cf33263fc5c16e
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              ExprResult ArgExpr = ParseAssignmentExpression();
130              if (ArgExpr.isInvalid) {
131                ArgExprsOk = false;
132                SkipUntil(tok::r_paren);
133                break;
134              } else {
135                ArgExprs.push_back(ArgExpr.Val);
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              ExprResult ArgExpr = ParseAssignmentExpression();
162              if (ArgExpr.isInvalid) {
163                ArgExprsOk = false;
164                SkipUntil(tok::r_paren);
165                break;
166              } else {
167                ArgExprs.push_back(ArgExpr.Val);
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      ExprResult AsmLabel = ParseSimpleAsm();
274      if (AsmLabel.isInvalid) {
275        SkipUntil(tok::semi);
276        return 0;
277      }
278
279      D.setAsmLabel(AsmLabel.Val);
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      ExprResult Init = ParseInitializer();
293      if (Init.isInvalid) {
294        SkipUntil(tok::semi);
295        return 0;
296      }
297      Actions.AddInitializerToDecl(LastDeclInGroup, Init.Val);
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      ExprResult Res = ParseConstantExpression();
846      if (Res.isInvalid)
847        SkipUntil(tok::semi, true, true);
848      else
849        DeclaratorInfo.BitfieldSize = Res.Val;
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,
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, Tok.getLocation(), Tok.getIdentifierInfo(),
938          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    ExprTy *AssignedVal = 0;
1078    if (Tok.is(tok::equal)) {
1079      EqualLoc = ConsumeToken();
1080      ExprResult Res = ParseConstantExpression();
1081      if (Res.isInvalid)
1082        SkipUntil(tok::comma, tok::r_brace, true, true);
1083      else
1084        AssignedVal = Res.Val;
1085    }
1086
1087    // Install the enumerator constant into EnumDecl.
1088    DeclTy *EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl,
1089                                                      LastEnumConstDecl,
1090                                                      IdentLoc, Ident,
1091                                                      EqualLoc, AssignedVal);
1092    EnumConstantDecls.push_back(EnumConstDecl);
1093    LastEnumConstDecl = EnumConstDecl;
1094
1095    if (Tok.isNot(tok::comma))
1096      break;
1097    SourceLocation CommaLoc = ConsumeToken();
1098
1099    if (Tok.isNot(tok::identifier) && !getLang().C99)
1100      Diag(CommaLoc, diag::ext_c99_enumerator_list_comma);
1101  }
1102
1103  // Eat the }.
1104  MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1105
1106  Actions.ActOnEnumBody(StartLoc, EnumDecl, &EnumConstantDecls[0],
1107                        EnumConstantDecls.size());
1108
1109  DeclTy *AttrList = 0;
1110  // If attributes exist after the identifier list, parse them.
1111  if (Tok.is(tok::kw___attribute))
1112    AttrList = ParseAttributes(); // FIXME: where do they do?
1113}
1114
1115/// isTypeSpecifierQualifier - Return true if the current token could be the
1116/// start of a type-qualifier-list.
1117bool Parser::isTypeQualifier() const {
1118  switch (Tok.getKind()) {
1119  default: return false;
1120    // type-qualifier
1121  case tok::kw_const:
1122  case tok::kw_volatile:
1123  case tok::kw_restrict:
1124    return true;
1125  }
1126}
1127
1128/// isTypeSpecifierQualifier - Return true if the current token could be the
1129/// start of a specifier-qualifier-list.
1130bool Parser::isTypeSpecifierQualifier() {
1131  // Annotate typenames and C++ scope specifiers.
1132  TryAnnotateTypeOrScopeToken();
1133
1134  switch (Tok.getKind()) {
1135  default: return false;
1136    // GNU attributes support.
1137  case tok::kw___attribute:
1138    // GNU typeof support.
1139  case tok::kw_typeof:
1140
1141    // type-specifiers
1142  case tok::kw_short:
1143  case tok::kw_long:
1144  case tok::kw_signed:
1145  case tok::kw_unsigned:
1146  case tok::kw__Complex:
1147  case tok::kw__Imaginary:
1148  case tok::kw_void:
1149  case tok::kw_char:
1150  case tok::kw_wchar_t:
1151  case tok::kw_int:
1152  case tok::kw_float:
1153  case tok::kw_double:
1154  case tok::kw_bool:
1155  case tok::kw__Bool:
1156  case tok::kw__Decimal32:
1157  case tok::kw__Decimal64:
1158  case tok::kw__Decimal128:
1159
1160    // struct-or-union-specifier (C99) or class-specifier (C++)
1161  case tok::kw_class:
1162  case tok::kw_struct:
1163  case tok::kw_union:
1164    // enum-specifier
1165  case tok::kw_enum:
1166
1167    // type-qualifier
1168  case tok::kw_const:
1169  case tok::kw_volatile:
1170  case tok::kw_restrict:
1171
1172    // typedef-name
1173  case tok::annot_qualtypename:
1174    return true;
1175
1176    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
1177  case tok::less:
1178    return getLang().ObjC1;
1179  }
1180}
1181
1182/// isDeclarationSpecifier() - Return true if the current token is part of a
1183/// declaration specifier.
1184bool Parser::isDeclarationSpecifier() {
1185  // Annotate typenames and C++ scope specifiers.
1186  TryAnnotateTypeOrScopeToken();
1187
1188  switch (Tok.getKind()) {
1189  default: return false;
1190    // storage-class-specifier
1191  case tok::kw_typedef:
1192  case tok::kw_extern:
1193  case tok::kw___private_extern__:
1194  case tok::kw_static:
1195  case tok::kw_auto:
1196  case tok::kw_register:
1197  case tok::kw___thread:
1198
1199    // type-specifiers
1200  case tok::kw_short:
1201  case tok::kw_long:
1202  case tok::kw_signed:
1203  case tok::kw_unsigned:
1204  case tok::kw__Complex:
1205  case tok::kw__Imaginary:
1206  case tok::kw_void:
1207  case tok::kw_char:
1208  case tok::kw_wchar_t:
1209  case tok::kw_int:
1210  case tok::kw_float:
1211  case tok::kw_double:
1212  case tok::kw_bool:
1213  case tok::kw__Bool:
1214  case tok::kw__Decimal32:
1215  case tok::kw__Decimal64:
1216  case tok::kw__Decimal128:
1217
1218    // struct-or-union-specifier (C99) or class-specifier (C++)
1219  case tok::kw_class:
1220  case tok::kw_struct:
1221  case tok::kw_union:
1222    // enum-specifier
1223  case tok::kw_enum:
1224
1225    // type-qualifier
1226  case tok::kw_const:
1227  case tok::kw_volatile:
1228  case tok::kw_restrict:
1229
1230    // function-specifier
1231  case tok::kw_inline:
1232  case tok::kw_virtual:
1233  case tok::kw_explicit:
1234
1235    // typedef-name
1236  case tok::annot_qualtypename:
1237
1238    // GNU typeof support.
1239  case tok::kw_typeof:
1240
1241    // GNU attributes.
1242  case tok::kw___attribute:
1243    return true;
1244
1245    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
1246  case tok::less:
1247    return getLang().ObjC1;
1248  }
1249}
1250
1251
1252/// ParseTypeQualifierListOpt
1253///       type-qualifier-list: [C99 6.7.5]
1254///         type-qualifier
1255/// [GNU]   attributes
1256///         type-qualifier-list type-qualifier
1257/// [GNU]   type-qualifier-list attributes
1258///
1259void Parser::ParseTypeQualifierListOpt(DeclSpec &DS) {
1260  while (1) {
1261    int isInvalid = false;
1262    const char *PrevSpec = 0;
1263    SourceLocation Loc = Tok.getLocation();
1264
1265    switch (Tok.getKind()) {
1266    default:
1267      // If this is not a type-qualifier token, we're done reading type
1268      // qualifiers.  First verify that DeclSpec's are consistent.
1269      DS.Finish(Diags, PP.getSourceManager(), getLang());
1270      return;
1271    case tok::kw_const:
1272      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
1273                                 getLang())*2;
1274      break;
1275    case tok::kw_volatile:
1276      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
1277                                 getLang())*2;
1278      break;
1279    case tok::kw_restrict:
1280      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1281                                 getLang())*2;
1282      break;
1283    case tok::kw___attribute:
1284      DS.AddAttributes(ParseAttributes());
1285      continue; // do *not* consume the next token!
1286    }
1287
1288    // If the specifier combination wasn't legal, issue a diagnostic.
1289    if (isInvalid) {
1290      assert(PrevSpec && "Method did not return previous specifier!");
1291      // Pick between error or extwarn.
1292      unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination
1293                                      : diag::ext_duplicate_declspec;
1294      Diag(Tok, DiagID) << PrevSpec;
1295    }
1296    ConsumeToken();
1297  }
1298}
1299
1300
1301/// ParseDeclarator - Parse and verify a newly-initialized declarator.
1302///
1303void Parser::ParseDeclarator(Declarator &D) {
1304  /// This implements the 'declarator' production in the C grammar, then checks
1305  /// for well-formedness and issues diagnostics.
1306  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
1307}
1308
1309/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
1310/// is parsed by the function passed to it. Pass null, and the direct-declarator
1311/// isn't parsed at all, making this function effectively parse the C++
1312/// ptr-operator production.
1313///
1314///       declarator: [C99 6.7.5]
1315///         pointer[opt] direct-declarator
1316/// [C++]   '&' declarator [C++ 8p4, dcl.decl]
1317/// [GNU]   '&' restrict[opt] attributes[opt] declarator
1318///
1319///       pointer: [C99 6.7.5]
1320///         '*' type-qualifier-list[opt]
1321///         '*' type-qualifier-list[opt] pointer
1322///
1323///       ptr-operator:
1324///         '*' cv-qualifier-seq[opt]
1325///         '&'
1326/// [GNU]   '&' restrict[opt] attributes[opt]
1327///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] [TODO]
1328void Parser::ParseDeclaratorInternal(Declarator &D,
1329                                     DirectDeclParseFunction DirectDeclParser) {
1330  tok::TokenKind Kind = Tok.getKind();
1331
1332  // Not a pointer, C++ reference, or block.
1333  if (Kind != tok::star && (Kind != tok::amp || !getLang().CPlusPlus) &&
1334      (Kind != tok::caret || !getLang().Blocks)) {
1335    if (DirectDeclParser)
1336      (this->*DirectDeclParser)(D);
1337    return;
1338  }
1339
1340  // Otherwise, '*' -> pointer, '^' -> block, '&' -> reference.
1341  SourceLocation Loc = ConsumeToken();  // Eat the * or &.
1342
1343  if (Kind == tok::star || (Kind == tok::caret && getLang().Blocks)) {
1344    // Is a pointer.
1345    DeclSpec DS;
1346
1347    ParseTypeQualifierListOpt(DS);
1348
1349    // Recursively parse the declarator.
1350    ParseDeclaratorInternal(D, DirectDeclParser);
1351    if (Kind == tok::star)
1352      // Remember that we parsed a pointer type, and remember the type-quals.
1353      D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
1354                                                DS.TakeAttributes()));
1355    else
1356      // Remember that we parsed a Block type, and remember the type-quals.
1357      D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
1358                                                     Loc));
1359  } else {
1360    // Is a reference
1361    DeclSpec DS;
1362
1363    // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
1364    // cv-qualifiers are introduced through the use of a typedef or of a
1365    // template type argument, in which case the cv-qualifiers are ignored.
1366    //
1367    // [GNU] Retricted references are allowed.
1368    // [GNU] Attributes on references are allowed.
1369    ParseTypeQualifierListOpt(DS);
1370
1371    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
1372      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1373        Diag(DS.getConstSpecLoc(),
1374             diag::err_invalid_reference_qualifier_application) << "const";
1375      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
1376        Diag(DS.getVolatileSpecLoc(),
1377             diag::err_invalid_reference_qualifier_application) << "volatile";
1378    }
1379
1380    // Recursively parse the declarator.
1381    ParseDeclaratorInternal(D, DirectDeclParser);
1382
1383    if (D.getNumTypeObjects() > 0) {
1384      // C++ [dcl.ref]p4: There shall be no references to references.
1385      DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
1386      if (InnerChunk.Kind == DeclaratorChunk::Reference) {
1387        if (const IdentifierInfo *II = D.getIdentifier())
1388          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
1389           << II;
1390        else
1391          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
1392            << "type name";
1393
1394        // Once we've complained about the reference-to-reference, we
1395        // can go ahead and build the (technically ill-formed)
1396        // declarator: reference collapsing will take care of it.
1397      }
1398    }
1399
1400    // Remember that we parsed a reference type. It doesn't have type-quals.
1401    D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
1402                                                DS.TakeAttributes()));
1403  }
1404}
1405
1406/// ParseDirectDeclarator
1407///       direct-declarator: [C99 6.7.5]
1408/// [C99]   identifier
1409///         '(' declarator ')'
1410/// [GNU]   '(' attributes declarator ')'
1411/// [C90]   direct-declarator '[' constant-expression[opt] ']'
1412/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1413/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1414/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1415/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
1416///         direct-declarator '(' parameter-type-list ')'
1417///         direct-declarator '(' identifier-list[opt] ')'
1418/// [GNU]   direct-declarator '(' parameter-forward-declarations
1419///                    parameter-type-list[opt] ')'
1420/// [C++]   direct-declarator '(' parameter-declaration-clause ')'
1421///                    cv-qualifier-seq[opt] exception-specification[opt]
1422/// [C++]   declarator-id
1423///
1424///       declarator-id: [C++ 8]
1425///         id-expression
1426///         '::'[opt] nested-name-specifier[opt] type-name
1427///
1428///       id-expression: [C++ 5.1]
1429///         unqualified-id
1430///         qualified-id            [TODO]
1431///
1432///       unqualified-id: [C++ 5.1]
1433///         identifier
1434///         operator-function-id
1435///         conversion-function-id  [TODO]
1436///          '~' class-name
1437///         template-id             [TODO]
1438///
1439void Parser::ParseDirectDeclarator(Declarator &D) {
1440  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
1441
1442  if (getLang().CPlusPlus) {
1443    if (D.mayHaveIdentifier()) {
1444      bool afterCXXScope = MaybeParseCXXScopeSpecifier(D.getCXXScopeSpec());
1445      if (afterCXXScope) {
1446        // Change the declaration context for name lookup, until this function
1447        // is exited (and the declarator has been parsed).
1448        DeclScopeObj.EnterDeclaratorScope();
1449      }
1450
1451      if (Tok.is(tok::identifier)) {
1452        assert(Tok.getIdentifierInfo() && "Not an identifier?");
1453        // Determine whether this identifier is a C++ constructor name or
1454        // a normal identifier.
1455        if (Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope)) {
1456          D.setConstructor(Actions.isTypeName(*Tok.getIdentifierInfo(),
1457                                              CurScope),
1458                           Tok.getLocation());
1459        } else
1460          D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1461        ConsumeToken();
1462        goto PastIdentifier;
1463      }
1464
1465      if (Tok.is(tok::tilde)) {
1466        // This should be a C++ destructor.
1467        SourceLocation TildeLoc = ConsumeToken();
1468        if (Tok.is(tok::identifier)) {
1469          if (TypeTy *Type = ParseClassName())
1470            D.setDestructor(Type, TildeLoc);
1471          else
1472            D.SetIdentifier(0, TildeLoc);
1473        } else {
1474          Diag(Tok, diag::err_expected_class_name);
1475          D.SetIdentifier(0, TildeLoc);
1476        }
1477        goto PastIdentifier;
1478      }
1479
1480      // If we reached this point, token is not identifier and not '~'.
1481
1482      if (afterCXXScope) {
1483        Diag(Tok, diag::err_expected_unqualified_id);
1484        D.SetIdentifier(0, Tok.getLocation());
1485        D.setInvalidType(true);
1486        goto PastIdentifier;
1487      }
1488    }
1489
1490    if (Tok.is(tok::kw_operator)) {
1491      SourceLocation OperatorLoc = Tok.getLocation();
1492
1493      // First try the name of an overloaded operator
1494      if (OverloadedOperatorKind Op = TryParseOperatorFunctionId()) {
1495        D.setOverloadedOperator(Op, OperatorLoc);
1496      } else {
1497        // This must be a conversion function (C++ [class.conv.fct]).
1498        if (TypeTy *ConvType = ParseConversionFunctionId())
1499          D.setConversionFunction(ConvType, OperatorLoc);
1500        else
1501          D.SetIdentifier(0, Tok.getLocation());
1502      }
1503      goto PastIdentifier;
1504    }
1505  }
1506
1507  // If we reached this point, we are either in C/ObjC or the token didn't
1508  // satisfy any of the C++-specific checks.
1509
1510  if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
1511    assert(!getLang().CPlusPlus &&
1512           "There's a C++-specific check for tok::identifier above");
1513    assert(Tok.getIdentifierInfo() && "Not an identifier?");
1514    D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1515    ConsumeToken();
1516  } else if (Tok.is(tok::l_paren)) {
1517    // direct-declarator: '(' declarator ')'
1518    // direct-declarator: '(' attributes declarator ')'
1519    // Example: 'char (*X)'   or 'int (*XX)(void)'
1520    ParseParenDeclarator(D);
1521  } else if (D.mayOmitIdentifier()) {
1522    // This could be something simple like "int" (in which case the declarator
1523    // portion is empty), if an abstract-declarator is allowed.
1524    D.SetIdentifier(0, Tok.getLocation());
1525  } else {
1526    if (getLang().CPlusPlus)
1527      Diag(Tok, diag::err_expected_unqualified_id);
1528    else
1529      Diag(Tok, diag::err_expected_ident_lparen);
1530    D.SetIdentifier(0, Tok.getLocation());
1531    D.setInvalidType(true);
1532  }
1533
1534 PastIdentifier:
1535  assert(D.isPastIdentifier() &&
1536         "Haven't past the location of the identifier yet?");
1537
1538  while (1) {
1539    if (Tok.is(tok::l_paren)) {
1540      // The paren may be part of a C++ direct initializer, eg. "int x(1);".
1541      // In such a case, check if we actually have a function declarator; if it
1542      // is not, the declarator has been fully parsed.
1543      if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
1544        // When not in file scope, warn for ambiguous function declarators, just
1545        // in case the author intended it as a variable definition.
1546        bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
1547        if (!isCXXFunctionDeclarator(warnIfAmbiguous))
1548          break;
1549      }
1550      ParseFunctionDeclarator(ConsumeParen(), D);
1551    } else if (Tok.is(tok::l_square)) {
1552      ParseBracketDeclarator(D);
1553    } else {
1554      break;
1555    }
1556  }
1557}
1558
1559/// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
1560/// only called before the identifier, so these are most likely just grouping
1561/// parens for precedence.  If we find that these are actually function
1562/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
1563///
1564///       direct-declarator:
1565///         '(' declarator ')'
1566/// [GNU]   '(' attributes declarator ')'
1567///         direct-declarator '(' parameter-type-list ')'
1568///         direct-declarator '(' identifier-list[opt] ')'
1569/// [GNU]   direct-declarator '(' parameter-forward-declarations
1570///                    parameter-type-list[opt] ')'
1571///
1572void Parser::ParseParenDeclarator(Declarator &D) {
1573  SourceLocation StartLoc = ConsumeParen();
1574  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
1575
1576  // Eat any attributes before we look at whether this is a grouping or function
1577  // declarator paren.  If this is a grouping paren, the attribute applies to
1578  // the type being built up, for example:
1579  //     int (__attribute__(()) *x)(long y)
1580  // If this ends up not being a grouping paren, the attribute applies to the
1581  // first argument, for example:
1582  //     int (__attribute__(()) int x)
1583  // In either case, we need to eat any attributes to be able to determine what
1584  // sort of paren this is.
1585  //
1586  AttributeList *AttrList = 0;
1587  bool RequiresArg = false;
1588  if (Tok.is(tok::kw___attribute)) {
1589    AttrList = ParseAttributes();
1590
1591    // We require that the argument list (if this is a non-grouping paren) be
1592    // present even if the attribute list was empty.
1593    RequiresArg = true;
1594  }
1595
1596  // If we haven't past the identifier yet (or where the identifier would be
1597  // stored, if this is an abstract declarator), then this is probably just
1598  // grouping parens. However, if this could be an abstract-declarator, then
1599  // this could also be the start of function arguments (consider 'void()').
1600  bool isGrouping;
1601
1602  if (!D.mayOmitIdentifier()) {
1603    // If this can't be an abstract-declarator, this *must* be a grouping
1604    // paren, because we haven't seen the identifier yet.
1605    isGrouping = true;
1606  } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
1607             (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
1608             isDeclarationSpecifier()) {       // 'int(int)' is a function.
1609    // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
1610    // considered to be a type, not a K&R identifier-list.
1611    isGrouping = false;
1612  } else {
1613    // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
1614    isGrouping = true;
1615  }
1616
1617  // If this is a grouping paren, handle:
1618  // direct-declarator: '(' declarator ')'
1619  // direct-declarator: '(' attributes declarator ')'
1620  if (isGrouping) {
1621    bool hadGroupingParens = D.hasGroupingParens();
1622    D.setGroupingParens(true);
1623    if (AttrList)
1624      D.AddAttributes(AttrList);
1625
1626    ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
1627    // Match the ')'.
1628    MatchRHSPunctuation(tok::r_paren, StartLoc);
1629
1630    D.setGroupingParens(hadGroupingParens);
1631    return;
1632  }
1633
1634  // Okay, if this wasn't a grouping paren, it must be the start of a function
1635  // argument list.  Recognize that this declarator will never have an
1636  // identifier (and remember where it would have been), then call into
1637  // ParseFunctionDeclarator to handle of argument list.
1638  D.SetIdentifier(0, Tok.getLocation());
1639
1640  ParseFunctionDeclarator(StartLoc, D, AttrList, RequiresArg);
1641}
1642
1643/// ParseFunctionDeclarator - We are after the identifier and have parsed the
1644/// declarator D up to a paren, which indicates that we are parsing function
1645/// arguments.
1646///
1647/// If AttrList is non-null, then the caller parsed those arguments immediately
1648/// after the open paren - they should be considered to be the first argument of
1649/// a parameter.  If RequiresArg is true, then the first argument of the
1650/// function is required to be present and required to not be an identifier
1651/// list.
1652///
1653/// This method also handles this portion of the grammar:
1654///       parameter-type-list: [C99 6.7.5]
1655///         parameter-list
1656///         parameter-list ',' '...'
1657///
1658///       parameter-list: [C99 6.7.5]
1659///         parameter-declaration
1660///         parameter-list ',' parameter-declaration
1661///
1662///       parameter-declaration: [C99 6.7.5]
1663///         declaration-specifiers declarator
1664/// [C++]   declaration-specifiers declarator '=' assignment-expression
1665/// [GNU]   declaration-specifiers declarator attributes
1666///         declaration-specifiers abstract-declarator[opt]
1667/// [C++]   declaration-specifiers abstract-declarator[opt]
1668///           '=' assignment-expression
1669/// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
1670///
1671/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]"
1672/// and "exception-specification[opt]"(TODO).
1673///
1674void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
1675                                     AttributeList *AttrList,
1676                                     bool RequiresArg) {
1677  // lparen is already consumed!
1678  assert(D.isPastIdentifier() && "Should not call before identifier!");
1679
1680  // This parameter list may be empty.
1681  if (Tok.is(tok::r_paren)) {
1682    if (RequiresArg) {
1683      Diag(Tok, diag::err_argument_required_after_attribute);
1684      delete AttrList;
1685    }
1686
1687    ConsumeParen();  // Eat the closing ')'.
1688
1689    // cv-qualifier-seq[opt].
1690    DeclSpec DS;
1691    if (getLang().CPlusPlus) {
1692      ParseTypeQualifierListOpt(DS);
1693
1694      // Parse exception-specification[opt].
1695      if (Tok.is(tok::kw_throw))
1696        ParseExceptionSpecification();
1697    }
1698
1699    // Remember that we parsed a function type, and remember the attributes.
1700    // int() -> no prototype, no '...'.
1701    D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus,
1702                                               /*variadic*/ false,
1703                                               /*arglist*/ 0, 0,
1704                                               DS.getTypeQualifiers(),
1705                                               LParenLoc));
1706    return;
1707  }
1708
1709  // Alternatively, this parameter list may be an identifier list form for a
1710  // K&R-style function:  void foo(a,b,c)
1711  if (!getLang().CPlusPlus && Tok.is(tok::identifier) &&
1712      // K&R identifier lists can't have typedefs as identifiers, per
1713      // C99 6.7.5.3p11.
1714      !Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope)) {
1715    if (RequiresArg) {
1716      Diag(Tok, diag::err_argument_required_after_attribute);
1717      delete AttrList;
1718    }
1719
1720    // Identifier list.  Note that '(' identifier-list ')' is only allowed for
1721    // normal declarators, not for abstract-declarators.
1722    return ParseFunctionDeclaratorIdentifierList(LParenLoc, D);
1723  }
1724
1725  // Finally, a normal, non-empty parameter type list.
1726
1727  // Build up an array of information about the parsed arguments.
1728  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1729
1730  // Enter function-declaration scope, limiting any declarators to the
1731  // function prototype scope, including parameter declarators.
1732  EnterScope(Scope::FnScope|Scope::DeclScope);
1733
1734  bool IsVariadic = false;
1735  while (1) {
1736    if (Tok.is(tok::ellipsis)) {
1737      IsVariadic = true;
1738
1739      // Check to see if this is "void(...)" which is not allowed.
1740      if (!getLang().CPlusPlus && ParamInfo.empty()) {
1741        // Otherwise, parse parameter type list.  If it starts with an
1742        // ellipsis,  diagnose the malformed function.
1743        Diag(Tok, diag::err_ellipsis_first_arg);
1744        IsVariadic = false;       // Treat this like 'void()'.
1745      }
1746
1747      ConsumeToken();     // Consume the ellipsis.
1748      break;
1749    }
1750
1751    SourceLocation DSStart = Tok.getLocation();
1752
1753    // Parse the declaration-specifiers.
1754    DeclSpec DS;
1755
1756    // If the caller parsed attributes for the first argument, add them now.
1757    if (AttrList) {
1758      DS.AddAttributes(AttrList);
1759      AttrList = 0;  // Only apply the attributes to the first parameter.
1760    }
1761    ParseDeclarationSpecifiers(DS);
1762
1763    // Parse the declarator.  This is "PrototypeContext", because we must
1764    // accept either 'declarator' or 'abstract-declarator' here.
1765    Declarator ParmDecl(DS, Declarator::PrototypeContext);
1766    ParseDeclarator(ParmDecl);
1767
1768    // Parse GNU attributes, if present.
1769    if (Tok.is(tok::kw___attribute))
1770      ParmDecl.AddAttributes(ParseAttributes());
1771
1772    // Remember this parsed parameter in ParamInfo.
1773    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1774
1775    // If no parameter was specified, verify that *something* was specified,
1776    // otherwise we have a missing type and identifier.
1777    if (DS.getParsedSpecifiers() == DeclSpec::PQ_None &&
1778        ParmDecl.getIdentifier() == 0 && ParmDecl.getNumTypeObjects() == 0) {
1779      // Completely missing, emit error.
1780      Diag(DSStart, diag::err_missing_param);
1781    } else {
1782      // Otherwise, we have something.  Add it and let semantic analysis try
1783      // to grok it and add the result to the ParamInfo we are building.
1784
1785      // Inform the actions module about the parameter declarator, so it gets
1786      // added to the current scope.
1787      DeclTy *Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl);
1788
1789      // Parse the default argument, if any. We parse the default
1790      // arguments in all dialects; the semantic analysis in
1791      // ActOnParamDefaultArgument will reject the default argument in
1792      // C.
1793      if (Tok.is(tok::equal)) {
1794        SourceLocation EqualLoc = Tok.getLocation();
1795
1796        // Consume the '='.
1797        ConsumeToken();
1798
1799        // Parse the default argument
1800        ExprResult DefArgResult = ParseAssignmentExpression();
1801        if (DefArgResult.isInvalid) {
1802          SkipUntil(tok::comma, tok::r_paren, true, true);
1803        } else {
1804          // Inform the actions module about the default argument
1805          Actions.ActOnParamDefaultArgument(Param, EqualLoc, DefArgResult.Val);
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  ExitScope();
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  ExprResult NumElements(false);
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.Val, 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    ExprResult 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.Val))
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    ExprResult Result = ParseExpression();
2028    ExprGuard ResultGuard(Actions, Result);
2029
2030    if (Result.isInvalid || Tok.isNot(tok::r_paren)) {
2031      MatchRHSPunctuation(tok::r_paren, LParenLoc);
2032      return;
2033    }
2034    RParenLoc = ConsumeParen();
2035    const char *PrevSpec = 0;
2036    // Check for duplicate type specifiers (e.g. "int typeof(int)").
2037    if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
2038                           ResultGuard.take()))
2039      Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
2040  }
2041  DS.SetRangeEnd(RParenLoc);
2042}
2043
2044
2045