ParseDecl.cpp revision bce6135441fd489527a9ad1776d0472335be596d
1//===--- ParseDecl.cpp - Declaration Parsing ------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements the Declaration portions of the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
15#include "clang/Parse/DeclSpec.h"
16#include "clang/Parse/Scope.h"
17#include "llvm/ADT/SmallSet.h"
18using namespace clang;
19
20//===----------------------------------------------------------------------===//
21// C99 6.7: Declarations.
22//===----------------------------------------------------------------------===//
23
24/// ParseTypeName
25///       type-name: [C99 6.7.6]
26///         specifier-qualifier-list abstract-declarator[opt]
27Parser::TypeTy *Parser::ParseTypeName() {
28  // Parse the common declaration-specifiers piece.
29  DeclSpec DS;
30  ParseSpecifierQualifierList(DS);
31
32  // Parse the abstract-declarator, if present.
33  Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
34  ParseDeclarator(DeclaratorInfo);
35
36  return Actions.ActOnTypeName(CurScope, DeclaratorInfo).Val;
37}
38
39/// ParseAttributes - Parse a non-empty attributes list.
40///
41/// [GNU] attributes:
42///         attribute
43///         attributes attribute
44///
45/// [GNU]  attribute:
46///          '__attribute__' '(' '(' attribute-list ')' ')'
47///
48/// [GNU]  attribute-list:
49///          attrib
50///          attribute_list ',' attrib
51///
52/// [GNU]  attrib:
53///          empty
54///          attrib-name
55///          attrib-name '(' identifier ')'
56///          attrib-name '(' identifier ',' nonempty-expr-list ')'
57///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
58///
59/// [GNU]  attrib-name:
60///          identifier
61///          typespec
62///          typequal
63///          storageclass
64///
65/// FIXME: The GCC grammar/code for this construct implies we need two
66/// token lookahead. Comment from gcc: "If they start with an identifier
67/// which is followed by a comma or close parenthesis, then the arguments
68/// start with that identifier; otherwise they are an expression list."
69///
70/// At the moment, I am not doing 2 token lookahead. I am also unaware of
71/// any attributes that don't work (based on my limited testing). Most
72/// attributes are very simple in practice. Until we find a bug, I don't see
73/// a pressing need to implement the 2 token lookahead.
74
75AttributeList *Parser::ParseAttributes() {
76  assert(Tok.is(tok::kw___attribute) && "Not an attribute list!");
77
78  AttributeList *CurrAttr = 0;
79
80  while (Tok.is(tok::kw___attribute)) {
81    ConsumeToken();
82    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
83                         "attribute")) {
84      SkipUntil(tok::r_paren, true); // skip until ) or ;
85      return CurrAttr;
86    }
87    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
88      SkipUntil(tok::r_paren, true); // skip until ) or ;
89      return CurrAttr;
90    }
91    // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
92    while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
93           Tok.is(tok::comma)) {
94
95      if (Tok.is(tok::comma)) {
96        // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
97        ConsumeToken();
98        continue;
99      }
100      // we have an identifier or declaration specifier (const, int, etc.)
101      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
102      SourceLocation AttrNameLoc = ConsumeToken();
103
104      // check if we have a "paramterized" attribute
105      if (Tok.is(tok::l_paren)) {
106        ConsumeParen(); // ignore the left paren loc for now
107
108        if (Tok.is(tok::identifier)) {
109          IdentifierInfo *ParmName = Tok.getIdentifierInfo();
110          SourceLocation ParmLoc = ConsumeToken();
111
112          if (Tok.is(tok::r_paren)) {
113            // __attribute__(( mode(byte) ))
114            ConsumeParen(); // ignore the right paren loc for now
115            CurrAttr = new AttributeList(AttrName, AttrNameLoc,
116                                         ParmName, ParmLoc, 0, 0, CurrAttr);
117          } else if (Tok.is(tok::comma)) {
118            ConsumeToken();
119            // __attribute__(( format(printf, 1, 2) ))
120            llvm::SmallVector<ExprTy*, 8> ArgExprs;
121            bool ArgExprsOk = true;
122
123            // now parse the non-empty comma separated list of expressions
124            while (1) {
125              ExprResult ArgExpr = ParseAssignmentExpression();
126              if (ArgExpr.isInvalid) {
127                ArgExprsOk = false;
128                SkipUntil(tok::r_paren);
129                break;
130              } else {
131                ArgExprs.push_back(ArgExpr.Val);
132              }
133              if (Tok.isNot(tok::comma))
134                break;
135              ConsumeToken(); // Eat the comma, move to the next argument
136            }
137            if (ArgExprsOk && Tok.is(tok::r_paren)) {
138              ConsumeParen(); // ignore the right paren loc for now
139              CurrAttr = new AttributeList(AttrName, AttrNameLoc, ParmName,
140                           ParmLoc, &ArgExprs[0], ArgExprs.size(), CurrAttr);
141            }
142          }
143        } else { // not an identifier
144          // parse a possibly empty comma separated list of expressions
145          if (Tok.is(tok::r_paren)) {
146            // __attribute__(( nonnull() ))
147            ConsumeParen(); // ignore the right paren loc for now
148            CurrAttr = new AttributeList(AttrName, AttrNameLoc,
149                                         0, SourceLocation(), 0, 0, CurrAttr);
150          } else {
151            // __attribute__(( aligned(16) ))
152            llvm::SmallVector<ExprTy*, 8> ArgExprs;
153            bool ArgExprsOk = true;
154
155            // now parse the list of expressions
156            while (1) {
157              ExprResult ArgExpr = ParseAssignmentExpression();
158              if (ArgExpr.isInvalid) {
159                ArgExprsOk = false;
160                SkipUntil(tok::r_paren);
161                break;
162              } else {
163                ArgExprs.push_back(ArgExpr.Val);
164              }
165              if (Tok.isNot(tok::comma))
166                break;
167              ConsumeToken(); // Eat the comma, move to the next argument
168            }
169            // Match the ')'.
170            if (ArgExprsOk && Tok.is(tok::r_paren)) {
171              ConsumeParen(); // ignore the right paren loc for now
172              CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0,
173                           SourceLocation(), &ArgExprs[0], ArgExprs.size(),
174                           CurrAttr);
175            }
176          }
177        }
178      } else {
179        CurrAttr = new AttributeList(AttrName, AttrNameLoc,
180                                     0, SourceLocation(), 0, 0, CurrAttr);
181      }
182    }
183    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
184      SkipUntil(tok::r_paren, false);
185    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
186      SkipUntil(tok::r_paren, false);
187  }
188  return CurrAttr;
189}
190
191/// ParseDeclaration - Parse a full 'declaration', which consists of
192/// declaration-specifiers, some number of declarators, and a semicolon.
193/// 'Context' should be a Declarator::TheContext value.
194///
195///       declaration: [C99 6.7]
196///         block-declaration ->
197///           simple-declaration
198///           others                   [FIXME]
199/// [C++]   namespace-definition
200///         others... [FIXME]
201///
202Parser::DeclTy *Parser::ParseDeclaration(unsigned Context) {
203  switch (Tok.getKind()) {
204  case tok::kw_namespace:
205    return ParseNamespace(Context);
206  default:
207    return ParseSimpleDeclaration(Context);
208  }
209}
210
211///       simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
212///         declaration-specifiers init-declarator-list[opt] ';'
213///[C90/C++]init-declarator-list ';'                             [TODO]
214/// [OMP]   threadprivate-directive                              [TODO]
215Parser::DeclTy *Parser::ParseSimpleDeclaration(unsigned Context) {
216  // Parse the common declaration-specifiers piece.
217  DeclSpec DS;
218  ParseDeclarationSpecifiers(DS);
219
220  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
221  // declaration-specifiers init-declarator-list[opt] ';'
222  if (Tok.is(tok::semi)) {
223    ConsumeToken();
224    return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
225  }
226
227  Declarator DeclaratorInfo(DS, (Declarator::TheContext)Context);
228  ParseDeclarator(DeclaratorInfo);
229
230  return ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo);
231}
232
233
234/// ParseInitDeclaratorListAfterFirstDeclarator - Parse 'declaration' after
235/// parsing 'declaration-specifiers declarator'.  This method is split out this
236/// way to handle the ambiguity between top-level function-definitions and
237/// declarations.
238///
239///       init-declarator-list: [C99 6.7]
240///         init-declarator
241///         init-declarator-list ',' init-declarator
242///       init-declarator: [C99 6.7]
243///         declarator
244///         declarator '=' initializer
245/// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
246/// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
247///
248Parser::DeclTy *Parser::
249ParseInitDeclaratorListAfterFirstDeclarator(Declarator &D) {
250
251  // Declarators may be grouped together ("int X, *Y, Z();").  Provide info so
252  // that they can be chained properly if the actions want this.
253  Parser::DeclTy *LastDeclInGroup = 0;
254
255  // At this point, we know that it is not a function definition.  Parse the
256  // rest of the init-declarator-list.
257  while (1) {
258    // If a simple-asm-expr is present, parse it.
259    if (Tok.is(tok::kw_asm))
260      ParseSimpleAsm();
261
262    // If attributes are present, parse them.
263    if (Tok.is(tok::kw___attribute))
264      D.AddAttributes(ParseAttributes());
265
266    // Inform the current actions module that we just parsed this declarator.
267    // FIXME: pass asm & attributes.
268    LastDeclInGroup = Actions.ActOnDeclarator(CurScope, D, LastDeclInGroup);
269
270    // Parse declarator '=' initializer.
271    ExprResult Init;
272    if (Tok.is(tok::equal)) {
273      ConsumeToken();
274      Init = ParseInitializer();
275      if (Init.isInvalid) {
276        SkipUntil(tok::semi);
277        return 0;
278      }
279      Actions.AddInitializerToDecl(LastDeclInGroup, Init.Val);
280    }
281
282    // If we don't have a comma, it is either the end of the list (a ';') or an
283    // error, bail out.
284    if (Tok.isNot(tok::comma))
285      break;
286
287    // Consume the comma.
288    ConsumeToken();
289
290    // Parse the next declarator.
291    D.clear();
292    ParseDeclarator(D);
293  }
294
295  if (Tok.is(tok::semi)) {
296    ConsumeToken();
297    return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup);
298  }
299  // If this is an ObjC2 for-each loop, this is a successful declarator
300  // parse.  The syntax for these looks like:
301  // 'for' '(' declaration 'in' expr ')' statement
302  if (D.getContext()  == Declarator::ForContext && isTokIdentifier_in()) {
303    return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup);
304  }
305  Diag(Tok, diag::err_parse_error);
306  // Skip to end of block or statement
307  SkipUntil(tok::r_brace, true, true);
308  if (Tok.is(tok::semi))
309    ConsumeToken();
310  return 0;
311}
312
313/// ParseSpecifierQualifierList
314///        specifier-qualifier-list:
315///          type-specifier specifier-qualifier-list[opt]
316///          type-qualifier specifier-qualifier-list[opt]
317/// [GNU]    attributes     specifier-qualifier-list[opt]
318///
319void Parser::ParseSpecifierQualifierList(DeclSpec &DS) {
320  /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
321  /// parse declaration-specifiers and complain about extra stuff.
322  ParseDeclarationSpecifiers(DS);
323
324  // Validate declspec for type-name.
325  unsigned Specs = DS.getParsedSpecifiers();
326  if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers())
327    Diag(Tok, diag::err_typename_requires_specqual);
328
329  // Issue diagnostic and remove storage class if present.
330  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
331    if (DS.getStorageClassSpecLoc().isValid())
332      Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
333    else
334      Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
335    DS.ClearStorageClassSpecs();
336  }
337
338  // Issue diagnostic and remove function specfier if present.
339  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
340    Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
341    DS.ClearFunctionSpecs();
342  }
343}
344
345/// ParseDeclarationSpecifiers
346///       declaration-specifiers: [C99 6.7]
347///         storage-class-specifier declaration-specifiers[opt]
348///         type-specifier declaration-specifiers[opt]
349///         type-qualifier declaration-specifiers[opt]
350/// [C99]   function-specifier declaration-specifiers[opt]
351/// [GNU]   attributes declaration-specifiers[opt]
352///
353///       storage-class-specifier: [C99 6.7.1]
354///         'typedef'
355///         'extern'
356///         'static'
357///         'auto'
358///         'register'
359/// [GNU]   '__thread'
360///       type-specifier: [C99 6.7.2]
361///         'void'
362///         'char'
363///         'short'
364///         'int'
365///         'long'
366///         'float'
367///         'double'
368///         'signed'
369///         'unsigned'
370///         struct-or-union-specifier
371///         enum-specifier
372///         typedef-name
373/// [C++]   'bool'
374/// [C99]   '_Bool'
375/// [C99]   '_Complex'
376/// [C99]   '_Imaginary'  // Removed in TC2?
377/// [GNU]   '_Decimal32'
378/// [GNU]   '_Decimal64'
379/// [GNU]   '_Decimal128'
380/// [GNU]   typeof-specifier
381/// [OBJC]  class-name objc-protocol-refs[opt]    [TODO]
382/// [OBJC]  typedef-name objc-protocol-refs[opt]  [TODO]
383///       type-qualifier:
384///         'const'
385///         'volatile'
386/// [C99]   'restrict'
387///       function-specifier: [C99 6.7.4]
388/// [C99]   'inline'
389///
390void Parser::ParseDeclarationSpecifiers(DeclSpec &DS) {
391  DS.SetRangeStart(Tok.getLocation());
392  while (1) {
393    int isInvalid = false;
394    const char *PrevSpec = 0;
395    SourceLocation Loc = Tok.getLocation();
396
397    switch (Tok.getKind()) {
398      // typedef-name
399    case tok::identifier:
400      // This identifier can only be a typedef name if we haven't already seen
401      // a type-specifier.  Without this check we misparse:
402      //  typedef int X; struct Y { short X; };  as 'short int'.
403      if (!DS.hasTypeSpecifier()) {
404        // It has to be available as a typedef too!
405        if (void *TypeRep = Actions.isTypeName(*Tok.getIdentifierInfo(),
406                                               CurScope)) {
407          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typedef, Loc, PrevSpec,
408                                         TypeRep);
409          if (isInvalid)
410            break;
411          // FIXME: restrict this to "id" and ObjC classnames.
412          DS.SetRangeEnd(Tok.getLocation());
413          ConsumeToken(); // The identifier
414          if (Tok.is(tok::less)) {
415            SourceLocation endProtoLoc;
416            llvm::SmallVector<IdentifierLocPair, 8> ProtocolRefs;
417            ParseObjCProtocolReferences(ProtocolRefs, endProtoLoc);
418
419            // FIXME: New'ing this here seems wrong, why not have the action do
420            // it?
421            llvm::SmallVector<DeclTy *, 8> *ProtocolDecl =
422                    new llvm::SmallVector<DeclTy *, 8>;
423            DS.setProtocolQualifiers(ProtocolDecl);
424            Actions.FindProtocolDeclaration(Loc,
425                      &ProtocolRefs[0], ProtocolRefs.size(),
426                      *ProtocolDecl);
427          }
428          continue;
429        }
430      }
431      // FALL THROUGH.
432    default:
433    DoneWithDeclSpec:
434      // If this is not a declaration specifier token, we're done reading decl
435      // specifiers.  First verify that DeclSpec's are consistent.
436      DS.Finish(Diags, PP.getSourceManager(), getLang());
437      return;
438
439    // GNU attributes support.
440    case tok::kw___attribute:
441      DS.AddAttributes(ParseAttributes());
442      continue;
443
444    // storage-class-specifier
445    case tok::kw_typedef:
446      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec);
447      break;
448    case tok::kw_extern:
449      if (DS.isThreadSpecified())
450        Diag(Tok, diag::ext_thread_before, "extern");
451      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec);
452      break;
453    case tok::kw___private_extern__:
454      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
455                                         PrevSpec);
456      break;
457    case tok::kw_static:
458      if (DS.isThreadSpecified())
459        Diag(Tok, diag::ext_thread_before, "static");
460      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec);
461      break;
462    case tok::kw_auto:
463      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec);
464      break;
465    case tok::kw_register:
466      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec);
467      break;
468    case tok::kw___thread:
469      isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec)*2;
470      break;
471
472    // type-specifiers
473    case tok::kw_short:
474      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec);
475      break;
476    case tok::kw_long:
477      if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
478        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec);
479      else
480        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec);
481      break;
482    case tok::kw_signed:
483      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec);
484      break;
485    case tok::kw_unsigned:
486      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec);
487      break;
488    case tok::kw__Complex:
489      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec);
490      break;
491    case tok::kw__Imaginary:
492      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec);
493      break;
494    case tok::kw_void:
495      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec);
496      break;
497    case tok::kw_char:
498      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec);
499      break;
500    case tok::kw_int:
501      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec);
502      break;
503    case tok::kw_float:
504      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec);
505      break;
506    case tok::kw_double:
507      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec);
508      break;
509    case tok::kw_bool:          // [C++ 2.11p1]
510    case tok::kw__Bool:
511      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec);
512      break;
513    case tok::kw__Decimal32:
514      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec);
515      break;
516    case tok::kw__Decimal64:
517      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec);
518      break;
519    case tok::kw__Decimal128:
520      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec);
521      break;
522
523    case tok::kw_class:
524    case tok::kw_struct:
525    case tok::kw_union:
526      ParseClassSpecifier(DS);
527      continue;
528    case tok::kw_enum:
529      ParseEnumSpecifier(DS);
530      continue;
531
532    // GNU typeof support.
533    case tok::kw_typeof:
534      ParseTypeofSpecifier(DS);
535      continue;
536
537    // type-qualifier
538    case tok::kw_const:
539      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
540                                 getLang())*2;
541      break;
542    case tok::kw_volatile:
543      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
544                                 getLang())*2;
545      break;
546    case tok::kw_restrict:
547      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
548                                 getLang())*2;
549      break;
550
551    // function-specifier
552    case tok::kw_inline:
553      isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec);
554      break;
555
556    case tok::less:
557      // GCC supports types like "<SomeProtocol>" as a synonym for
558      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
559      // but we support it.
560      if (DS.hasTypeSpecifier())
561        goto DoneWithDeclSpec;
562
563      {
564        SourceLocation EndProtoLoc;
565        llvm::SmallVector<IdentifierLocPair, 8> ProtocolRefs;
566        ParseObjCProtocolReferences(ProtocolRefs, EndProtoLoc);
567        llvm::SmallVector<DeclTy *, 8> *ProtocolDecl =
568                new llvm::SmallVector<DeclTy *, 8>;
569        DS.setProtocolQualifiers(ProtocolDecl);
570        Actions.FindProtocolDeclaration(Loc,
571                                        &ProtocolRefs[0], ProtocolRefs.size(),
572                                        *ProtocolDecl);
573        Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id,
574             SourceRange(Loc, EndProtoLoc));
575        continue;
576      }
577    }
578    // If the specifier combination wasn't legal, issue a diagnostic.
579    if (isInvalid) {
580      assert(PrevSpec && "Method did not return previous specifier!");
581      if (isInvalid == 1)  // Error.
582        Diag(Tok, diag::err_invalid_decl_spec_combination, PrevSpec);
583      else                 // extwarn.
584        Diag(Tok, diag::ext_duplicate_declspec, PrevSpec);
585    }
586    DS.SetRangeEnd(Tok.getLocation());
587    ConsumeToken();
588  }
589}
590
591/// ParseTag - Parse "struct-or-union-or-class-or-enum identifier[opt]", where
592/// the first token has already been read and has been turned into an instance
593/// of DeclSpec::TST (TagType).  This returns true if there is an error parsing,
594/// otherwise it returns false and fills in Decl.
595bool Parser::ParseTag(DeclTy *&Decl, unsigned TagType, SourceLocation StartLoc){
596  AttributeList *Attr = 0;
597  // If attributes exist after tag, parse them.
598  if (Tok.is(tok::kw___attribute))
599    Attr = ParseAttributes();
600
601  // Must have either 'struct name' or 'struct {...}'.
602  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) {
603    Diag(Tok, diag::err_expected_ident_lbrace);
604
605    // Skip the rest of this declarator, up until the comma or semicolon.
606    SkipUntil(tok::comma, true);
607    return true;
608  }
609
610  // If an identifier is present, consume and remember it.
611  IdentifierInfo *Name = 0;
612  SourceLocation NameLoc;
613  if (Tok.is(tok::identifier)) {
614    Name = Tok.getIdentifierInfo();
615    NameLoc = ConsumeToken();
616  }
617
618  // There are three options here.  If we have 'struct foo;', then this is a
619  // forward declaration.  If we have 'struct foo {...' then this is a
620  // definition. Otherwise we have something like 'struct foo xyz', a reference.
621  //
622  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
623  // struct foo {..};  void bar() { struct foo; }    <- new foo in bar.
624  // struct foo {..};  void bar() { struct foo x; }  <- use of old foo.
625  //
626  Action::TagKind TK;
627  if (Tok.is(tok::l_brace))
628    TK = Action::TK_Definition;
629  else if (Tok.is(tok::semi))
630    TK = Action::TK_Declaration;
631  else
632    TK = Action::TK_Reference;
633  Decl = Actions.ActOnTag(CurScope, TagType, TK, StartLoc, Name, NameLoc, Attr);
634  return false;
635}
636
637/// ParseStructDeclaration - Parse a struct declaration without the terminating
638/// semicolon.
639///
640///       struct-declaration:
641///         specifier-qualifier-list struct-declarator-list
642/// [GNU]   __extension__ struct-declaration
643/// [GNU]   specifier-qualifier-list
644///       struct-declarator-list:
645///         struct-declarator
646///         struct-declarator-list ',' struct-declarator
647/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
648///       struct-declarator:
649///         declarator
650/// [GNU]   declarator attributes[opt]
651///         declarator[opt] ':' constant-expression
652/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
653///
654void Parser::
655ParseStructDeclaration(DeclSpec &DS,
656                       llvm::SmallVectorImpl<FieldDeclarator> &Fields) {
657  // FIXME: When __extension__ is specified, disable extension diagnostics.
658  while (Tok.is(tok::kw___extension__))
659    ConsumeToken();
660
661  // Parse the common specifier-qualifiers-list piece.
662  SourceLocation DSStart = Tok.getLocation();
663  ParseSpecifierQualifierList(DS);
664  // TODO: Does specifier-qualifier list correctly check that *something* is
665  // specified?
666
667  // If there are no declarators, issue a warning.
668  if (Tok.is(tok::semi)) {
669    Diag(DSStart, diag::w_no_declarators);
670    return;
671  }
672
673  // Read struct-declarators until we find the semicolon.
674  Fields.push_back(FieldDeclarator(DS));
675  while (1) {
676    FieldDeclarator &DeclaratorInfo = Fields.back();
677
678    /// struct-declarator: declarator
679    /// struct-declarator: declarator[opt] ':' constant-expression
680    if (Tok.isNot(tok::colon))
681      ParseDeclarator(DeclaratorInfo.D);
682
683    if (Tok.is(tok::colon)) {
684      ConsumeToken();
685      ExprResult Res = ParseConstantExpression();
686      if (Res.isInvalid)
687        SkipUntil(tok::semi, true, true);
688      else
689        DeclaratorInfo.BitfieldSize = Res.Val;
690    }
691
692    // If attributes exist after the declarator, parse them.
693    if (Tok.is(tok::kw___attribute))
694      DeclaratorInfo.D.AddAttributes(ParseAttributes());
695
696    // If we don't have a comma, it is either the end of the list (a ';')
697    // or an error, bail out.
698    if (Tok.isNot(tok::comma))
699      return;
700
701    // Consume the comma.
702    ConsumeToken();
703
704    // Parse the next declarator.
705    Fields.push_back(FieldDeclarator(DS));
706
707    // Attributes are only allowed on the second declarator.
708    if (Tok.is(tok::kw___attribute))
709      Fields.back().D.AddAttributes(ParseAttributes());
710  }
711}
712
713/// ParseStructUnionBody
714///       struct-contents:
715///         struct-declaration-list
716/// [EXT]   empty
717/// [GNU]   "struct-declaration-list" without terminatoring ';'
718///       struct-declaration-list:
719///         struct-declaration
720///         struct-declaration-list struct-declaration
721/// [OBC]   '@' 'defs' '(' class-name ')'
722///
723void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
724                                  unsigned TagType, DeclTy *TagDecl) {
725  SourceLocation LBraceLoc = ConsumeBrace();
726
727  // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
728  // C++.
729  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
730    Diag(Tok, diag::ext_empty_struct_union_enum,
731         DeclSpec::getSpecifierName((DeclSpec::TST)TagType));
732
733  llvm::SmallVector<DeclTy*, 32> FieldDecls;
734  llvm::SmallVector<FieldDeclarator, 8> FieldDeclarators;
735
736  // While we still have something to read, read the declarations in the struct.
737  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
738    // Each iteration of this loop reads one struct-declaration.
739
740    // Check for extraneous top-level semicolon.
741    if (Tok.is(tok::semi)) {
742      Diag(Tok, diag::ext_extra_struct_semi);
743      ConsumeToken();
744      continue;
745    }
746
747    // Parse all the comma separated declarators.
748    DeclSpec DS;
749    FieldDeclarators.clear();
750    if (!Tok.is(tok::at)) {
751      ParseStructDeclaration(DS, FieldDeclarators);
752
753      // Convert them all to fields.
754      for (unsigned i = 0, e = FieldDeclarators.size(); i != e; ++i) {
755        FieldDeclarator &FD = FieldDeclarators[i];
756        // Install the declarator into the current TagDecl.
757        DeclTy *Field = Actions.ActOnField(CurScope,
758                                           DS.getSourceRange().getBegin(),
759                                           FD.D, FD.BitfieldSize);
760        FieldDecls.push_back(Field);
761      }
762    } else { // Handle @defs
763      ConsumeToken();
764      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
765        Diag(Tok, diag::err_unexpected_at);
766        SkipUntil(tok::semi, true, true);
767        continue;
768      }
769      ConsumeToken();
770      ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
771      if (!Tok.is(tok::identifier)) {
772        Diag(Tok, diag::err_expected_ident);
773        SkipUntil(tok::semi, true, true);
774        continue;
775      }
776      llvm::SmallVector<DeclTy*, 16> Fields;
777      Actions.ActOnDefs(CurScope, Tok.getLocation(), Tok.getIdentifierInfo(),
778          Fields);
779      FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
780      ConsumeToken();
781      ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
782    }
783
784    if (Tok.is(tok::semi)) {
785      ConsumeToken();
786    } else if (Tok.is(tok::r_brace)) {
787      Diag(Tok.getLocation(), diag::ext_expected_semi_decl_list);
788      break;
789    } else {
790      Diag(Tok, diag::err_expected_semi_decl_list);
791      // Skip to end of block or statement
792      SkipUntil(tok::r_brace, true, true);
793    }
794  }
795
796  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
797
798  Actions.ActOnFields(CurScope,
799                      RecordLoc,TagDecl,&FieldDecls[0],FieldDecls.size(),
800                      LBraceLoc, RBraceLoc);
801
802  AttributeList *AttrList = 0;
803  // If attributes exist after struct contents, parse them.
804  if (Tok.is(tok::kw___attribute))
805    AttrList = ParseAttributes(); // FIXME: where should I put them?
806}
807
808
809/// ParseEnumSpecifier
810///       enum-specifier: [C99 6.7.2.2]
811///         'enum' identifier[opt] '{' enumerator-list '}'
812/// [C99]   'enum' identifier[opt] '{' enumerator-list ',' '}'
813/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
814///                                                 '}' attributes[opt]
815///         'enum' identifier
816/// [GNU]   'enum' attributes[opt] identifier
817void Parser::ParseEnumSpecifier(DeclSpec &DS) {
818  assert(Tok.is(tok::kw_enum) && "Not an enum specifier");
819  SourceLocation StartLoc = ConsumeToken();
820
821  // Parse the tag portion of this.
822  DeclTy *TagDecl;
823  if (ParseTag(TagDecl, DeclSpec::TST_enum, StartLoc))
824    return;
825
826  if (Tok.is(tok::l_brace))
827    ParseEnumBody(StartLoc, TagDecl);
828
829  // TODO: semantic analysis on the declspec for enums.
830  const char *PrevSpec = 0;
831  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, PrevSpec, TagDecl))
832    Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
833}
834
835/// ParseEnumBody - Parse a {} enclosed enumerator-list.
836///       enumerator-list:
837///         enumerator
838///         enumerator-list ',' enumerator
839///       enumerator:
840///         enumeration-constant
841///         enumeration-constant '=' constant-expression
842///       enumeration-constant:
843///         identifier
844///
845void Parser::ParseEnumBody(SourceLocation StartLoc, DeclTy *EnumDecl) {
846  SourceLocation LBraceLoc = ConsumeBrace();
847
848  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
849  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
850    Diag(Tok, diag::ext_empty_struct_union_enum, "enum");
851
852  llvm::SmallVector<DeclTy*, 32> EnumConstantDecls;
853
854  DeclTy *LastEnumConstDecl = 0;
855
856  // Parse the enumerator-list.
857  while (Tok.is(tok::identifier)) {
858    IdentifierInfo *Ident = Tok.getIdentifierInfo();
859    SourceLocation IdentLoc = ConsumeToken();
860
861    SourceLocation EqualLoc;
862    ExprTy *AssignedVal = 0;
863    if (Tok.is(tok::equal)) {
864      EqualLoc = ConsumeToken();
865      ExprResult Res = ParseConstantExpression();
866      if (Res.isInvalid)
867        SkipUntil(tok::comma, tok::r_brace, true, true);
868      else
869        AssignedVal = Res.Val;
870    }
871
872    // Install the enumerator constant into EnumDecl.
873    DeclTy *EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl,
874                                                      LastEnumConstDecl,
875                                                      IdentLoc, Ident,
876                                                      EqualLoc, AssignedVal);
877    EnumConstantDecls.push_back(EnumConstDecl);
878    LastEnumConstDecl = EnumConstDecl;
879
880    if (Tok.isNot(tok::comma))
881      break;
882    SourceLocation CommaLoc = ConsumeToken();
883
884    if (Tok.isNot(tok::identifier) && !getLang().C99)
885      Diag(CommaLoc, diag::ext_c99_enumerator_list_comma);
886  }
887
888  // Eat the }.
889  MatchRHSPunctuation(tok::r_brace, LBraceLoc);
890
891  Actions.ActOnEnumBody(StartLoc, EnumDecl, &EnumConstantDecls[0],
892                        EnumConstantDecls.size());
893
894  DeclTy *AttrList = 0;
895  // If attributes exist after the identifier list, parse them.
896  if (Tok.is(tok::kw___attribute))
897    AttrList = ParseAttributes(); // FIXME: where do they do?
898}
899
900/// isTypeSpecifierQualifier - Return true if the current token could be the
901/// start of a type-qualifier-list.
902bool Parser::isTypeQualifier() const {
903  switch (Tok.getKind()) {
904  default: return false;
905    // type-qualifier
906  case tok::kw_const:
907  case tok::kw_volatile:
908  case tok::kw_restrict:
909    return true;
910  }
911}
912
913/// isTypeSpecifierQualifier - Return true if the current token could be the
914/// start of a specifier-qualifier-list.
915bool Parser::isTypeSpecifierQualifier() const {
916  switch (Tok.getKind()) {
917  default: return false;
918    // GNU attributes support.
919  case tok::kw___attribute:
920    // GNU typeof support.
921  case tok::kw_typeof:
922    // GNU bizarre protocol extension. FIXME: make an extension?
923  case tok::less:
924
925    // type-specifiers
926  case tok::kw_short:
927  case tok::kw_long:
928  case tok::kw_signed:
929  case tok::kw_unsigned:
930  case tok::kw__Complex:
931  case tok::kw__Imaginary:
932  case tok::kw_void:
933  case tok::kw_char:
934  case tok::kw_int:
935  case tok::kw_float:
936  case tok::kw_double:
937  case tok::kw_bool:
938  case tok::kw__Bool:
939  case tok::kw__Decimal32:
940  case tok::kw__Decimal64:
941  case tok::kw__Decimal128:
942
943    // struct-or-union-specifier (C99) or class-specifier (C++)
944  case tok::kw_class:
945  case tok::kw_struct:
946  case tok::kw_union:
947    // enum-specifier
948  case tok::kw_enum:
949
950    // type-qualifier
951  case tok::kw_const:
952  case tok::kw_volatile:
953  case tok::kw_restrict:
954    return true;
955
956    // typedef-name
957  case tok::identifier:
958    return Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope) != 0;
959  }
960}
961
962/// isDeclarationSpecifier() - Return true if the current token is part of a
963/// declaration specifier.
964bool Parser::isDeclarationSpecifier() const {
965  switch (Tok.getKind()) {
966  default: return false;
967    // storage-class-specifier
968  case tok::kw_typedef:
969  case tok::kw_extern:
970  case tok::kw___private_extern__:
971  case tok::kw_static:
972  case tok::kw_auto:
973  case tok::kw_register:
974  case tok::kw___thread:
975
976    // type-specifiers
977  case tok::kw_short:
978  case tok::kw_long:
979  case tok::kw_signed:
980  case tok::kw_unsigned:
981  case tok::kw__Complex:
982  case tok::kw__Imaginary:
983  case tok::kw_void:
984  case tok::kw_char:
985  case tok::kw_int:
986  case tok::kw_float:
987  case tok::kw_double:
988  case tok::kw_bool:
989  case tok::kw__Bool:
990  case tok::kw__Decimal32:
991  case tok::kw__Decimal64:
992  case tok::kw__Decimal128:
993
994    // struct-or-union-specifier (C99) or class-specifier (C++)
995  case tok::kw_class:
996  case tok::kw_struct:
997  case tok::kw_union:
998    // enum-specifier
999  case tok::kw_enum:
1000
1001    // type-qualifier
1002  case tok::kw_const:
1003  case tok::kw_volatile:
1004  case tok::kw_restrict:
1005
1006    // function-specifier
1007  case tok::kw_inline:
1008
1009    // GNU typeof support.
1010  case tok::kw_typeof:
1011
1012    // GNU attributes.
1013  case tok::kw___attribute:
1014
1015    // GNU bizarre protocol extension. FIXME: make an extension?
1016  case tok::less:
1017    return true;
1018
1019    // typedef-name
1020  case tok::identifier:
1021    return Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope) != 0;
1022  }
1023}
1024
1025
1026/// ParseTypeQualifierListOpt
1027///       type-qualifier-list: [C99 6.7.5]
1028///         type-qualifier
1029/// [GNU]   attributes
1030///         type-qualifier-list type-qualifier
1031/// [GNU]   type-qualifier-list attributes
1032///
1033void Parser::ParseTypeQualifierListOpt(DeclSpec &DS) {
1034  while (1) {
1035    int isInvalid = false;
1036    const char *PrevSpec = 0;
1037    SourceLocation Loc = Tok.getLocation();
1038
1039    switch (Tok.getKind()) {
1040    default:
1041      // If this is not a type-qualifier token, we're done reading type
1042      // qualifiers.  First verify that DeclSpec's are consistent.
1043      DS.Finish(Diags, PP.getSourceManager(), getLang());
1044      return;
1045    case tok::kw_const:
1046      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
1047                                 getLang())*2;
1048      break;
1049    case tok::kw_volatile:
1050      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
1051                                 getLang())*2;
1052      break;
1053    case tok::kw_restrict:
1054      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1055                                 getLang())*2;
1056      break;
1057    case tok::kw___attribute:
1058      DS.AddAttributes(ParseAttributes());
1059      continue; // do *not* consume the next token!
1060    }
1061
1062    // If the specifier combination wasn't legal, issue a diagnostic.
1063    if (isInvalid) {
1064      assert(PrevSpec && "Method did not return previous specifier!");
1065      if (isInvalid == 1)  // Error.
1066        Diag(Tok, diag::err_invalid_decl_spec_combination, PrevSpec);
1067      else                 // extwarn.
1068        Diag(Tok, diag::ext_duplicate_declspec, PrevSpec);
1069    }
1070    ConsumeToken();
1071  }
1072}
1073
1074
1075/// ParseDeclarator - Parse and verify a newly-initialized declarator.
1076///
1077void Parser::ParseDeclarator(Declarator &D) {
1078  /// This implements the 'declarator' production in the C grammar, then checks
1079  /// for well-formedness and issues diagnostics.
1080  ParseDeclaratorInternal(D);
1081}
1082
1083/// ParseDeclaratorInternal
1084///       declarator: [C99 6.7.5]
1085///         pointer[opt] direct-declarator
1086/// [C++]   '&' declarator [C++ 8p4, dcl.decl]
1087/// [GNU]   '&' restrict[opt] attributes[opt] declarator
1088///
1089///       pointer: [C99 6.7.5]
1090///         '*' type-qualifier-list[opt]
1091///         '*' type-qualifier-list[opt] pointer
1092///
1093void Parser::ParseDeclaratorInternal(Declarator &D) {
1094  tok::TokenKind Kind = Tok.getKind();
1095
1096  // Not a pointer or C++ reference.
1097  if (Kind != tok::star && (Kind != tok::amp || !getLang().CPlusPlus))
1098    return ParseDirectDeclarator(D);
1099
1100  // Otherwise, '*' -> pointer or '&' -> reference.
1101  SourceLocation Loc = ConsumeToken();  // Eat the * or &.
1102
1103  if (Kind == tok::star) {
1104    // Is a pointer.
1105    DeclSpec DS;
1106
1107    ParseTypeQualifierListOpt(DS);
1108
1109    // Recursively parse the declarator.
1110    ParseDeclaratorInternal(D);
1111
1112    // Remember that we parsed a pointer type, and remember the type-quals.
1113    D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
1114                                              DS.TakeAttributes()));
1115  } else {
1116    // Is a reference
1117    DeclSpec DS;
1118
1119    // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
1120    // cv-qualifiers are introduced through the use of a typedef or of a
1121    // template type argument, in which case the cv-qualifiers are ignored.
1122    //
1123    // [GNU] Retricted references are allowed.
1124    // [GNU] Attributes on references are allowed.
1125    ParseTypeQualifierListOpt(DS);
1126
1127    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
1128      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1129        Diag(DS.getConstSpecLoc(),
1130             diag::err_invalid_reference_qualifier_application,
1131             "const");
1132      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
1133        Diag(DS.getVolatileSpecLoc(),
1134             diag::err_invalid_reference_qualifier_application,
1135             "volatile");
1136    }
1137
1138    // Recursively parse the declarator.
1139    ParseDeclaratorInternal(D);
1140
1141    // Remember that we parsed a reference type. It doesn't have type-quals.
1142    D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
1143                                                DS.TakeAttributes()));
1144  }
1145}
1146
1147/// ParseDirectDeclarator
1148///       direct-declarator: [C99 6.7.5]
1149///         identifier
1150///         '(' declarator ')'
1151/// [GNU]   '(' attributes declarator ')'
1152/// [C90]   direct-declarator '[' constant-expression[opt] ']'
1153/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1154/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1155/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1156/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
1157///         direct-declarator '(' parameter-type-list ')'
1158///         direct-declarator '(' identifier-list[opt] ')'
1159/// [GNU]   direct-declarator '(' parameter-forward-declarations
1160///                    parameter-type-list[opt] ')'
1161///
1162void Parser::ParseDirectDeclarator(Declarator &D) {
1163  // Parse the first direct-declarator seen.
1164  if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
1165    assert(Tok.getIdentifierInfo() && "Not an identifier?");
1166    D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1167    ConsumeToken();
1168  } else if (Tok.is(tok::l_paren)) {
1169    // direct-declarator: '(' declarator ')'
1170    // direct-declarator: '(' attributes declarator ')'
1171    // Example: 'char (*X)'   or 'int (*XX)(void)'
1172    ParseParenDeclarator(D);
1173  } else if (D.mayOmitIdentifier()) {
1174    // This could be something simple like "int" (in which case the declarator
1175    // portion is empty), if an abstract-declarator is allowed.
1176    D.SetIdentifier(0, Tok.getLocation());
1177  } else {
1178    // Expected identifier or '('.
1179    Diag(Tok, diag::err_expected_ident_lparen);
1180    D.SetIdentifier(0, Tok.getLocation());
1181  }
1182
1183  assert(D.isPastIdentifier() &&
1184         "Haven't past the location of the identifier yet?");
1185
1186  while (1) {
1187    if (Tok.is(tok::l_paren)) {
1188      ParseFunctionDeclarator(ConsumeParen(), D);
1189    } else if (Tok.is(tok::l_square)) {
1190      ParseBracketDeclarator(D);
1191    } else {
1192      break;
1193    }
1194  }
1195}
1196
1197/// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
1198/// only called before the identifier, so these are most likely just grouping
1199/// parens for precedence.  If we find that these are actually function
1200/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
1201///
1202///       direct-declarator:
1203///         '(' declarator ')'
1204/// [GNU]   '(' attributes declarator ')'
1205///
1206void Parser::ParseParenDeclarator(Declarator &D) {
1207  SourceLocation StartLoc = ConsumeParen();
1208  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
1209
1210  // If we haven't past the identifier yet (or where the identifier would be
1211  // stored, if this is an abstract declarator), then this is probably just
1212  // grouping parens. However, if this could be an abstract-declarator, then
1213  // this could also be the start of function arguments (consider 'void()').
1214  bool isGrouping;
1215
1216  if (!D.mayOmitIdentifier()) {
1217    // If this can't be an abstract-declarator, this *must* be a grouping
1218    // paren, because we haven't seen the identifier yet.
1219    isGrouping = true;
1220  } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
1221             isDeclarationSpecifier()) {       // 'int(int)' is a function.
1222    // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
1223    // considered to be a type, not a K&R identifier-list.
1224    isGrouping = false;
1225  } else {
1226    // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
1227    isGrouping = true;
1228  }
1229
1230  // If this is a grouping paren, handle:
1231  // direct-declarator: '(' declarator ')'
1232  // direct-declarator: '(' attributes declarator ')'
1233  if (isGrouping) {
1234    if (Tok.is(tok::kw___attribute))
1235      D.AddAttributes(ParseAttributes());
1236
1237    ParseDeclaratorInternal(D);
1238    // Match the ')'.
1239    MatchRHSPunctuation(tok::r_paren, StartLoc);
1240    return;
1241  }
1242
1243  // Okay, if this wasn't a grouping paren, it must be the start of a function
1244  // argument list.  Recognize that this declarator will never have an
1245  // identifier (and remember where it would have been), then fall through to
1246  // the handling of argument lists.
1247  D.SetIdentifier(0, Tok.getLocation());
1248
1249  ParseFunctionDeclarator(StartLoc, D);
1250}
1251
1252/// ParseFunctionDeclarator - We are after the identifier and have parsed the
1253/// declarator D up to a paren, which indicates that we are parsing function
1254/// arguments.
1255///
1256/// This method also handles this portion of the grammar:
1257///       parameter-type-list: [C99 6.7.5]
1258///         parameter-list
1259///         parameter-list ',' '...'
1260///
1261///       parameter-list: [C99 6.7.5]
1262///         parameter-declaration
1263///         parameter-list ',' parameter-declaration
1264///
1265///       parameter-declaration: [C99 6.7.5]
1266///         declaration-specifiers declarator
1267/// [C++]   declaration-specifiers declarator '=' assignment-expression
1268/// [GNU]   declaration-specifiers declarator attributes
1269///         declaration-specifiers abstract-declarator[opt]
1270/// [C++]   declaration-specifiers abstract-declarator[opt]
1271///           '=' assignment-expression
1272/// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
1273///
1274void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D) {
1275  // lparen is already consumed!
1276  assert(D.isPastIdentifier() && "Should not call before identifier!");
1277
1278  // Okay, this is the parameter list of a function definition, or it is an
1279  // identifier list of a K&R-style function.
1280
1281  if (Tok.is(tok::r_paren)) {
1282    // Remember that we parsed a function type, and remember the attributes.
1283    // int() -> no prototype, no '...'.
1284    D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/ false,
1285                                               /*variadic*/ false,
1286                                               /*arglist*/ 0, 0, LParenLoc));
1287
1288    ConsumeParen();  // Eat the closing ')'.
1289    return;
1290  } else if (Tok.is(tok::identifier) &&
1291             // K&R identifier lists can't have typedefs as identifiers, per
1292             // C99 6.7.5.3p11.
1293             !Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope)) {
1294    // Identifier list.  Note that '(' identifier-list ')' is only allowed for
1295    // normal declarators, not for abstract-declarators.
1296    return ParseFunctionDeclaratorIdentifierList(LParenLoc, D);
1297  }
1298
1299  // Finally, a normal, non-empty parameter type list.
1300
1301  // Build up an array of information about the parsed arguments.
1302  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1303
1304  // Enter function-declaration scope, limiting any declarators to the
1305  // function prototype scope, including parameter declarators.
1306  EnterScope(Scope::FnScope|Scope::DeclScope);
1307
1308  bool IsVariadic = false;
1309  while (1) {
1310    if (Tok.is(tok::ellipsis)) {
1311      IsVariadic = true;
1312
1313      // Check to see if this is "void(...)" which is not allowed.
1314      if (ParamInfo.empty()) {
1315        // Otherwise, parse parameter type list.  If it starts with an
1316        // ellipsis,  diagnose the malformed function.
1317        Diag(Tok, diag::err_ellipsis_first_arg);
1318        IsVariadic = false;       // Treat this like 'void()'.
1319      }
1320
1321      ConsumeToken();     // Consume the ellipsis.
1322      break;
1323    }
1324
1325    SourceLocation DSStart = Tok.getLocation();
1326
1327    // Parse the declaration-specifiers.
1328    DeclSpec DS;
1329    ParseDeclarationSpecifiers(DS);
1330
1331    // Parse the declarator.  This is "PrototypeContext", because we must
1332    // accept either 'declarator' or 'abstract-declarator' here.
1333    Declarator ParmDecl(DS, Declarator::PrototypeContext);
1334    ParseDeclarator(ParmDecl);
1335
1336    // Parse GNU attributes, if present.
1337    if (Tok.is(tok::kw___attribute))
1338      ParmDecl.AddAttributes(ParseAttributes());
1339
1340    // Remember this parsed parameter in ParamInfo.
1341    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1342
1343    // If no parameter was specified, verify that *something* was specified,
1344    // otherwise we have a missing type and identifier.
1345    if (DS.getParsedSpecifiers() == DeclSpec::PQ_None &&
1346        ParmDecl.getIdentifier() == 0 && ParmDecl.getNumTypeObjects() == 0) {
1347      // Completely missing, emit error.
1348      Diag(DSStart, diag::err_missing_param);
1349    } else {
1350      // Otherwise, we have something.  Add it and let semantic analysis try
1351      // to grok it and add the result to the ParamInfo we are building.
1352
1353      // Inform the actions module about the parameter declarator, so it gets
1354      // added to the current scope.
1355      DeclTy *Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl);
1356
1357      // Parse the default argument, if any. We parse the default
1358      // arguments in all dialects; the semantic analysis in
1359      // ActOnParamDefaultArgument will reject the default argument in
1360      // C.
1361      if (Tok.is(tok::equal)) {
1362        SourceLocation EqualLoc = Tok.getLocation();
1363
1364        // Consume the '='.
1365        ConsumeToken();
1366
1367        // Parse the default argument
1368        ExprResult DefArgResult = ParseAssignmentExpression();
1369        if (DefArgResult.isInvalid) {
1370          SkipUntil(tok::comma, tok::r_paren, true, true);
1371        } else {
1372          // Inform the actions module about the default argument
1373          Actions.ActOnParamDefaultArgument(Param, EqualLoc, DefArgResult.Val);
1374        }
1375      }
1376
1377      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1378                             ParmDecl.getIdentifierLoc(), Param));
1379    }
1380
1381    // If the next token is a comma, consume it and keep reading arguments.
1382    if (Tok.isNot(tok::comma)) break;
1383
1384    // Consume the comma.
1385    ConsumeToken();
1386  }
1387
1388  // Leave prototype scope.
1389  ExitScope();
1390
1391  // Remember that we parsed a function type, and remember the attributes.
1392  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
1393                                             &ParamInfo[0], ParamInfo.size(),
1394                                             LParenLoc));
1395
1396  // If we have the closing ')', eat it and we're done.
1397  MatchRHSPunctuation(tok::r_paren, LParenLoc);
1398}
1399
1400/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
1401/// we found a K&R-style identifier list instead of a type argument list.  The
1402/// current token is known to be the first identifier in the list.
1403///
1404///       identifier-list: [C99 6.7.5]
1405///         identifier
1406///         identifier-list ',' identifier
1407///
1408void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
1409                                                   Declarator &D) {
1410  // Build up an array of information about the parsed arguments.
1411  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1412  llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
1413
1414  // If there was no identifier specified for the declarator, either we are in
1415  // an abstract-declarator, or we are in a parameter declarator which was found
1416  // to be abstract.  In abstract-declarators, identifier lists are not valid:
1417  // diagnose this.
1418  if (!D.getIdentifier())
1419    Diag(Tok, diag::ext_ident_list_in_param);
1420
1421  // Tok is known to be the first identifier in the list.  Remember this
1422  // identifier in ParamInfo.
1423  ParamsSoFar.insert(Tok.getIdentifierInfo());
1424  ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
1425                                                 Tok.getLocation(), 0));
1426
1427  ConsumeToken();  // eat the first identifier.
1428
1429  while (Tok.is(tok::comma)) {
1430    // Eat the comma.
1431    ConsumeToken();
1432
1433    // If this isn't an identifier, report the error and skip until ')'.
1434    if (Tok.isNot(tok::identifier)) {
1435      Diag(Tok, diag::err_expected_ident);
1436      SkipUntil(tok::r_paren);
1437      return;
1438    }
1439
1440    IdentifierInfo *ParmII = Tok.getIdentifierInfo();
1441
1442    // Reject 'typedef int y; int test(x, y)', but continue parsing.
1443    if (Actions.isTypeName(*ParmII, CurScope))
1444      Diag(Tok, diag::err_unexpected_typedef_ident, ParmII->getName());
1445
1446    // Verify that the argument identifier has not already been mentioned.
1447    if (!ParamsSoFar.insert(ParmII)) {
1448      Diag(Tok.getLocation(), diag::err_param_redefinition, ParmII->getName());
1449    } else {
1450      // Remember this identifier in ParamInfo.
1451      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1452                                                     Tok.getLocation(), 0));
1453    }
1454
1455    // Eat the identifier.
1456    ConsumeToken();
1457  }
1458
1459  // Remember that we parsed a function type, and remember the attributes.  This
1460  // function type is always a K&R style function type, which is not varargs and
1461  // has no prototype.
1462  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
1463                                             &ParamInfo[0], ParamInfo.size(),
1464                                             LParenLoc));
1465
1466  // If we have the closing ')', eat it and we're done.
1467  MatchRHSPunctuation(tok::r_paren, LParenLoc);
1468}
1469
1470/// [C90]   direct-declarator '[' constant-expression[opt] ']'
1471/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1472/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1473/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1474/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
1475void Parser::ParseBracketDeclarator(Declarator &D) {
1476  SourceLocation StartLoc = ConsumeBracket();
1477
1478  // If valid, this location is the position where we read the 'static' keyword.
1479  SourceLocation StaticLoc;
1480  if (Tok.is(tok::kw_static))
1481    StaticLoc = ConsumeToken();
1482
1483  // If there is a type-qualifier-list, read it now.
1484  DeclSpec DS;
1485  ParseTypeQualifierListOpt(DS);
1486
1487  // If we haven't already read 'static', check to see if there is one after the
1488  // type-qualifier-list.
1489  if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
1490    StaticLoc = ConsumeToken();
1491
1492  // Handle "direct-declarator [ type-qual-list[opt] * ]".
1493  bool isStar = false;
1494  ExprResult NumElements(false);
1495
1496  // Handle the case where we have '[*]' as the array size.  However, a leading
1497  // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
1498  // the the token after the star is a ']'.  Since stars in arrays are
1499  // infrequent, use of lookahead is not costly here.
1500  if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
1501    ConsumeToken();  // Eat the '*'.
1502
1503    if (StaticLoc.isValid())
1504      Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
1505    StaticLoc = SourceLocation();  // Drop the static.
1506    isStar = true;
1507  } else if (Tok.isNot(tok::r_square)) {
1508    // Parse the assignment-expression now.
1509    NumElements = ParseAssignmentExpression();
1510  }
1511
1512  // If there was an error parsing the assignment-expression, recover.
1513  if (NumElements.isInvalid) {
1514    // If the expression was invalid, skip it.
1515    SkipUntil(tok::r_square);
1516    return;
1517  }
1518
1519  MatchRHSPunctuation(tok::r_square, StartLoc);
1520
1521  // If C99 isn't enabled, emit an ext-warn if the arg list wasn't empty and if
1522  // it was not a constant expression.
1523  if (!getLang().C99) {
1524    // TODO: check C90 array constant exprness.
1525    if (isStar || StaticLoc.isValid() ||
1526        0/*TODO: NumElts is not a C90 constantexpr */)
1527      Diag(StartLoc, diag::ext_c99_array_usage);
1528  }
1529
1530  // Remember that we parsed a pointer type, and remember the type-quals.
1531  D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
1532                                          StaticLoc.isValid(), isStar,
1533                                          NumElements.Val, StartLoc));
1534}
1535
1536/// [GNU] typeof-specifier:
1537///         typeof ( expressions )
1538///         typeof ( type-name )
1539///
1540void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
1541  assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
1542  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1543  SourceLocation StartLoc = ConsumeToken();
1544
1545  if (Tok.isNot(tok::l_paren)) {
1546    Diag(Tok, diag::err_expected_lparen_after, BuiltinII->getName());
1547    return;
1548  }
1549  SourceLocation LParenLoc = ConsumeParen(), RParenLoc;
1550
1551  if (isTypeSpecifierQualifier()) {
1552    TypeTy *Ty = ParseTypeName();
1553
1554    assert(Ty && "Parser::ParseTypeofSpecifier(): missing type");
1555
1556    if (Tok.isNot(tok::r_paren)) {
1557      MatchRHSPunctuation(tok::r_paren, LParenLoc);
1558      return;
1559    }
1560    RParenLoc = ConsumeParen();
1561    const char *PrevSpec = 0;
1562    // Check for duplicate type specifiers (e.g. "int typeof(int)").
1563    if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, Ty))
1564      Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
1565  } else { // we have an expression.
1566    ExprResult Result = ParseExpression();
1567
1568    if (Result.isInvalid || Tok.isNot(tok::r_paren)) {
1569      MatchRHSPunctuation(tok::r_paren, LParenLoc);
1570      return;
1571    }
1572    RParenLoc = ConsumeParen();
1573    const char *PrevSpec = 0;
1574    // Check for duplicate type specifiers (e.g. "int typeof(int)").
1575    if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
1576                           Result.Val))
1577      Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
1578  }
1579}
1580
1581
1582