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