ParseDecl.cpp revision 00bc645d154f8f30bfbfb2fe508caf087793157c
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)
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<IdentifierInfo *, 8> ProtocolRefs;
417            ParseObjCProtocolReferences(ProtocolRefs, endProtoLoc);
418            llvm::SmallVector<DeclTy *, 8> *ProtocolDecl =
419                    new llvm::SmallVector<DeclTy *, 8>;
420            DS.setProtocolQualifiers(ProtocolDecl);
421            Actions.FindProtocolDeclaration(Loc,
422                      &ProtocolRefs[0], ProtocolRefs.size(),
423                      *ProtocolDecl);
424          }
425          continue;
426        }
427      }
428      // FALL THROUGH.
429    default:
430      // If this is not a declaration specifier token, we're done reading decl
431      // specifiers.  First verify that DeclSpec's are consistent.
432      DS.Finish(Diags, PP.getSourceManager(), getLang());
433      return;
434
435    // GNU attributes support.
436    case tok::kw___attribute:
437      DS.AddAttributes(ParseAttributes());
438      continue;
439
440    // storage-class-specifier
441    case tok::kw_typedef:
442      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec);
443      break;
444    case tok::kw_extern:
445      if (DS.isThreadSpecified())
446        Diag(Tok, diag::ext_thread_before, "extern");
447      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec);
448      break;
449    case tok::kw___private_extern__:
450      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
451                                         PrevSpec);
452      break;
453    case tok::kw_static:
454      if (DS.isThreadSpecified())
455        Diag(Tok, diag::ext_thread_before, "static");
456      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec);
457      break;
458    case tok::kw_auto:
459      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec);
460      break;
461    case tok::kw_register:
462      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec);
463      break;
464    case tok::kw___thread:
465      isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec)*2;
466      break;
467
468    // type-specifiers
469    case tok::kw_short:
470      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec);
471      break;
472    case tok::kw_long:
473      if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
474        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec);
475      else
476        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec);
477      break;
478    case tok::kw_signed:
479      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec);
480      break;
481    case tok::kw_unsigned:
482      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec);
483      break;
484    case tok::kw__Complex:
485      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec);
486      break;
487    case tok::kw__Imaginary:
488      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec);
489      break;
490    case tok::kw_void:
491      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec);
492      break;
493    case tok::kw_char:
494      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec);
495      break;
496    case tok::kw_int:
497      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec);
498      break;
499    case tok::kw_float:
500      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec);
501      break;
502    case tok::kw_double:
503      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec);
504      break;
505    case tok::kw_bool:          // [C++ 2.11p1]
506    case tok::kw__Bool:
507      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec);
508      break;
509    case tok::kw__Decimal32:
510      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec);
511      break;
512    case tok::kw__Decimal64:
513      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec);
514      break;
515    case tok::kw__Decimal128:
516      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec);
517      break;
518
519    case tok::kw_class:
520    case tok::kw_struct:
521    case tok::kw_union:
522      ParseClassSpecifier(DS);
523      continue;
524    case tok::kw_enum:
525      ParseEnumSpecifier(DS);
526      continue;
527
528    // GNU typeof support.
529    case tok::kw_typeof:
530      ParseTypeofSpecifier(DS);
531      continue;
532
533    // type-qualifier
534    case tok::kw_const:
535      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
536                                 getLang())*2;
537      break;
538    case tok::kw_volatile:
539      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
540                                 getLang())*2;
541      break;
542    case tok::kw_restrict:
543      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
544                                 getLang())*2;
545      break;
546
547    // function-specifier
548    case tok::kw_inline:
549      isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec);
550      break;
551    }
552    // If the specifier combination wasn't legal, issue a diagnostic.
553    if (isInvalid) {
554      assert(PrevSpec && "Method did not return previous specifier!");
555      if (isInvalid == 1)  // Error.
556        Diag(Tok, diag::err_invalid_decl_spec_combination, PrevSpec);
557      else                 // extwarn.
558        Diag(Tok, diag::ext_duplicate_declspec, PrevSpec);
559    }
560    DS.SetRangeEnd(Tok.getLocation());
561    ConsumeToken();
562  }
563}
564
565/// ParseTag - Parse "struct-or-union-or-class-or-enum identifier[opt]", where
566/// the first token has already been read and has been turned into an instance
567/// of DeclSpec::TST (TagType).  This returns true if there is an error parsing,
568/// otherwise it returns false and fills in Decl.
569bool Parser::ParseTag(DeclTy *&Decl, unsigned TagType, SourceLocation StartLoc){
570  AttributeList *Attr = 0;
571  // If attributes exist after tag, parse them.
572  if (Tok.is(tok::kw___attribute))
573    Attr = ParseAttributes();
574
575  // Must have either 'struct name' or 'struct {...}'.
576  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) {
577    Diag(Tok, diag::err_expected_ident_lbrace);
578
579    // Skip the rest of this declarator, up until the comma or semicolon.
580    SkipUntil(tok::comma, true);
581    return true;
582  }
583
584  // If an identifier is present, consume and remember it.
585  IdentifierInfo *Name = 0;
586  SourceLocation NameLoc;
587  if (Tok.is(tok::identifier)) {
588    Name = Tok.getIdentifierInfo();
589    NameLoc = ConsumeToken();
590  }
591
592  // There are three options here.  If we have 'struct foo;', then this is a
593  // forward declaration.  If we have 'struct foo {...' then this is a
594  // definition. Otherwise we have something like 'struct foo xyz', a reference.
595  //
596  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
597  // struct foo {..};  void bar() { struct foo; }    <- new foo in bar.
598  // struct foo {..};  void bar() { struct foo x; }  <- use of old foo.
599  //
600  Action::TagKind TK;
601  if (Tok.is(tok::l_brace))
602    TK = Action::TK_Definition;
603  else if (Tok.is(tok::semi))
604    TK = Action::TK_Declaration;
605  else
606    TK = Action::TK_Reference;
607  Decl = Actions.ActOnTag(CurScope, TagType, TK, StartLoc, Name, NameLoc, Attr);
608  return false;
609}
610
611/// ParseStructDeclaration - Parse a struct declaration without the terminating
612/// semicolon.
613///
614///       struct-declaration:
615///         specifier-qualifier-list struct-declarator-list
616/// [GNU]   __extension__ struct-declaration
617/// [GNU]   specifier-qualifier-list
618///       struct-declarator-list:
619///         struct-declarator
620///         struct-declarator-list ',' struct-declarator
621/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
622///       struct-declarator:
623///         declarator
624/// [GNU]   declarator attributes[opt]
625///         declarator[opt] ':' constant-expression
626/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
627///
628void Parser::
629ParseStructDeclaration(DeclSpec &DS,
630                       llvm::SmallVectorImpl<FieldDeclarator> &Fields) {
631  // FIXME: When __extension__ is specified, disable extension diagnostics.
632  while (Tok.is(tok::kw___extension__))
633    ConsumeToken();
634
635  // Parse the common specifier-qualifiers-list piece.
636  SourceLocation DSStart = Tok.getLocation();
637  ParseSpecifierQualifierList(DS);
638  // TODO: Does specifier-qualifier list correctly check that *something* is
639  // specified?
640
641  // If there are no declarators, issue a warning.
642  if (Tok.is(tok::semi)) {
643    Diag(DSStart, diag::w_no_declarators);
644    return;
645  }
646
647  // Read struct-declarators until we find the semicolon.
648  Fields.push_back(FieldDeclarator(DS));
649  while (1) {
650    FieldDeclarator &DeclaratorInfo = Fields.back();
651
652    /// struct-declarator: declarator
653    /// struct-declarator: declarator[opt] ':' constant-expression
654    if (Tok.isNot(tok::colon))
655      ParseDeclarator(DeclaratorInfo.D);
656
657    if (Tok.is(tok::colon)) {
658      ConsumeToken();
659      ExprResult Res = ParseConstantExpression();
660      if (Res.isInvalid)
661        SkipUntil(tok::semi, true, true);
662      else
663        DeclaratorInfo.BitfieldSize = Res.Val;
664    }
665
666    // If attributes exist after the declarator, parse them.
667    if (Tok.is(tok::kw___attribute))
668      DeclaratorInfo.D.AddAttributes(ParseAttributes());
669
670    // If we don't have a comma, it is either the end of the list (a ';')
671    // or an error, bail out.
672    if (Tok.isNot(tok::comma))
673      return;
674
675    // Consume the comma.
676    ConsumeToken();
677
678    // Parse the next declarator.
679    Fields.push_back(FieldDeclarator(DS));
680
681    // Attributes are only allowed on the second declarator.
682    if (Tok.is(tok::kw___attribute))
683      Fields.back().D.AddAttributes(ParseAttributes());
684  }
685}
686
687/// ParseStructUnionBody
688///       struct-contents:
689///         struct-declaration-list
690/// [EXT]   empty
691/// [GNU]   "struct-declaration-list" without terminatoring ';'
692///       struct-declaration-list:
693///         struct-declaration
694///         struct-declaration-list struct-declaration
695/// [OBC]   '@' 'defs' '(' class-name ')'                         [TODO]
696///
697void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
698                                  unsigned TagType, DeclTy *TagDecl) {
699  SourceLocation LBraceLoc = ConsumeBrace();
700
701  // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
702  // C++.
703  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
704    Diag(Tok, diag::ext_empty_struct_union_enum,
705         DeclSpec::getSpecifierName((DeclSpec::TST)TagType));
706
707  llvm::SmallVector<DeclTy*, 32> FieldDecls;
708  llvm::SmallVector<FieldDeclarator, 8> FieldDeclarators;
709
710  // While we still have something to read, read the declarations in the struct.
711  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
712    // Each iteration of this loop reads one struct-declaration.
713
714    // Check for extraneous top-level semicolon.
715    if (Tok.is(tok::semi)) {
716      Diag(Tok, diag::ext_extra_struct_semi);
717      ConsumeToken();
718      continue;
719    }
720
721    // Parse all the comma separated declarators.
722    DeclSpec DS;
723    FieldDeclarators.clear();
724    ParseStructDeclaration(DS, FieldDeclarators);
725
726    // Convert them all to fields.
727    for (unsigned i = 0, e = FieldDeclarators.size(); i != e; ++i) {
728      FieldDeclarator &FD = FieldDeclarators[i];
729      // Install the declarator into the current TagDecl.
730      DeclTy *Field = Actions.ActOnField(CurScope,
731                                         DS.getSourceRange().getBegin(),
732                                         FD.D, FD.BitfieldSize);
733      FieldDecls.push_back(Field);
734    }
735
736
737    if (Tok.is(tok::semi)) {
738      ConsumeToken();
739    } else if (Tok.is(tok::r_brace)) {
740      Diag(Tok.getLocation(), diag::ext_expected_semi_decl_list);
741      break;
742    } else {
743      Diag(Tok, diag::err_expected_semi_decl_list);
744      // Skip to end of block or statement
745      SkipUntil(tok::r_brace, true, true);
746    }
747  }
748
749  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
750
751  Actions.ActOnFields(CurScope,
752                      RecordLoc,TagDecl,&FieldDecls[0],FieldDecls.size(),
753                      LBraceLoc, RBraceLoc);
754
755  AttributeList *AttrList = 0;
756  // If attributes exist after struct contents, parse them.
757  if (Tok.is(tok::kw___attribute))
758    AttrList = ParseAttributes(); // FIXME: where should I put them?
759}
760
761
762/// ParseEnumSpecifier
763///       enum-specifier: [C99 6.7.2.2]
764///         'enum' identifier[opt] '{' enumerator-list '}'
765/// [C99]   'enum' identifier[opt] '{' enumerator-list ',' '}'
766/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
767///                                                 '}' attributes[opt]
768///         'enum' identifier
769/// [GNU]   'enum' attributes[opt] identifier
770void Parser::ParseEnumSpecifier(DeclSpec &DS) {
771  assert(Tok.is(tok::kw_enum) && "Not an enum specifier");
772  SourceLocation StartLoc = ConsumeToken();
773
774  // Parse the tag portion of this.
775  DeclTy *TagDecl;
776  if (ParseTag(TagDecl, DeclSpec::TST_enum, StartLoc))
777    return;
778
779  if (Tok.is(tok::l_brace))
780    ParseEnumBody(StartLoc, TagDecl);
781
782  // TODO: semantic analysis on the declspec for enums.
783  const char *PrevSpec = 0;
784  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, PrevSpec, TagDecl))
785    Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
786}
787
788/// ParseEnumBody - Parse a {} enclosed enumerator-list.
789///       enumerator-list:
790///         enumerator
791///         enumerator-list ',' enumerator
792///       enumerator:
793///         enumeration-constant
794///         enumeration-constant '=' constant-expression
795///       enumeration-constant:
796///         identifier
797///
798void Parser::ParseEnumBody(SourceLocation StartLoc, DeclTy *EnumDecl) {
799  SourceLocation LBraceLoc = ConsumeBrace();
800
801  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
802  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
803    Diag(Tok, diag::ext_empty_struct_union_enum, "enum");
804
805  llvm::SmallVector<DeclTy*, 32> EnumConstantDecls;
806
807  DeclTy *LastEnumConstDecl = 0;
808
809  // Parse the enumerator-list.
810  while (Tok.is(tok::identifier)) {
811    IdentifierInfo *Ident = Tok.getIdentifierInfo();
812    SourceLocation IdentLoc = ConsumeToken();
813
814    SourceLocation EqualLoc;
815    ExprTy *AssignedVal = 0;
816    if (Tok.is(tok::equal)) {
817      EqualLoc = ConsumeToken();
818      ExprResult Res = ParseConstantExpression();
819      if (Res.isInvalid)
820        SkipUntil(tok::comma, tok::r_brace, true, true);
821      else
822        AssignedVal = Res.Val;
823    }
824
825    // Install the enumerator constant into EnumDecl.
826    DeclTy *EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl,
827                                                      LastEnumConstDecl,
828                                                      IdentLoc, Ident,
829                                                      EqualLoc, AssignedVal);
830    EnumConstantDecls.push_back(EnumConstDecl);
831    LastEnumConstDecl = EnumConstDecl;
832
833    if (Tok.isNot(tok::comma))
834      break;
835    SourceLocation CommaLoc = ConsumeToken();
836
837    if (Tok.isNot(tok::identifier) && !getLang().C99)
838      Diag(CommaLoc, diag::ext_c99_enumerator_list_comma);
839  }
840
841  // Eat the }.
842  MatchRHSPunctuation(tok::r_brace, LBraceLoc);
843
844  Actions.ActOnEnumBody(StartLoc, EnumDecl, &EnumConstantDecls[0],
845                        EnumConstantDecls.size());
846
847  DeclTy *AttrList = 0;
848  // If attributes exist after the identifier list, parse them.
849  if (Tok.is(tok::kw___attribute))
850    AttrList = ParseAttributes(); // FIXME: where do they do?
851}
852
853/// isTypeSpecifierQualifier - Return true if the current token could be the
854/// start of a type-qualifier-list.
855bool Parser::isTypeQualifier() const {
856  switch (Tok.getKind()) {
857  default: return false;
858    // type-qualifier
859  case tok::kw_const:
860  case tok::kw_volatile:
861  case tok::kw_restrict:
862    return true;
863  }
864}
865
866/// isTypeSpecifierQualifier - Return true if the current token could be the
867/// start of a specifier-qualifier-list.
868bool Parser::isTypeSpecifierQualifier() const {
869  switch (Tok.getKind()) {
870  default: return false;
871    // GNU attributes support.
872  case tok::kw___attribute:
873    // GNU typeof support.
874  case tok::kw_typeof:
875
876    // type-specifiers
877  case tok::kw_short:
878  case tok::kw_long:
879  case tok::kw_signed:
880  case tok::kw_unsigned:
881  case tok::kw__Complex:
882  case tok::kw__Imaginary:
883  case tok::kw_void:
884  case tok::kw_char:
885  case tok::kw_int:
886  case tok::kw_float:
887  case tok::kw_double:
888  case tok::kw_bool:
889  case tok::kw__Bool:
890  case tok::kw__Decimal32:
891  case tok::kw__Decimal64:
892  case tok::kw__Decimal128:
893
894    // struct-or-union-specifier (C99) or class-specifier (C++)
895  case tok::kw_class:
896  case tok::kw_struct:
897  case tok::kw_union:
898    // enum-specifier
899  case tok::kw_enum:
900
901    // type-qualifier
902  case tok::kw_const:
903  case tok::kw_volatile:
904  case tok::kw_restrict:
905    return true;
906
907    // typedef-name
908  case tok::identifier:
909    return Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope) != 0;
910  }
911}
912
913/// isDeclarationSpecifier() - Return true if the current token is part of a
914/// declaration specifier.
915bool Parser::isDeclarationSpecifier() const {
916  switch (Tok.getKind()) {
917  default: return false;
918    // storage-class-specifier
919  case tok::kw_typedef:
920  case tok::kw_extern:
921  case tok::kw___private_extern__:
922  case tok::kw_static:
923  case tok::kw_auto:
924  case tok::kw_register:
925  case tok::kw___thread:
926
927    // type-specifiers
928  case tok::kw_short:
929  case tok::kw_long:
930  case tok::kw_signed:
931  case tok::kw_unsigned:
932  case tok::kw__Complex:
933  case tok::kw__Imaginary:
934  case tok::kw_void:
935  case tok::kw_char:
936  case tok::kw_int:
937  case tok::kw_float:
938  case tok::kw_double:
939  case tok::kw_bool:
940  case tok::kw__Bool:
941  case tok::kw__Decimal32:
942  case tok::kw__Decimal64:
943  case tok::kw__Decimal128:
944
945    // struct-or-union-specifier (C99) or class-specifier (C++)
946  case tok::kw_class:
947  case tok::kw_struct:
948  case tok::kw_union:
949    // enum-specifier
950  case tok::kw_enum:
951
952    // type-qualifier
953  case tok::kw_const:
954  case tok::kw_volatile:
955  case tok::kw_restrict:
956
957    // function-specifier
958  case tok::kw_inline:
959
960    // GNU typeof support.
961  case tok::kw_typeof:
962
963    // GNU attributes.
964  case tok::kw___attribute:
965    return true;
966
967    // typedef-name
968  case tok::identifier:
969    return Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope) != 0;
970  }
971}
972
973
974/// ParseTypeQualifierListOpt
975///       type-qualifier-list: [C99 6.7.5]
976///         type-qualifier
977/// [GNU]   attributes
978///         type-qualifier-list type-qualifier
979/// [GNU]   type-qualifier-list attributes
980///
981void Parser::ParseTypeQualifierListOpt(DeclSpec &DS) {
982  while (1) {
983    int isInvalid = false;
984    const char *PrevSpec = 0;
985    SourceLocation Loc = Tok.getLocation();
986
987    switch (Tok.getKind()) {
988    default:
989      // If this is not a type-qualifier token, we're done reading type
990      // qualifiers.  First verify that DeclSpec's are consistent.
991      DS.Finish(Diags, PP.getSourceManager(), getLang());
992      return;
993    case tok::kw_const:
994      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
995                                 getLang())*2;
996      break;
997    case tok::kw_volatile:
998      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
999                                 getLang())*2;
1000      break;
1001    case tok::kw_restrict:
1002      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1003                                 getLang())*2;
1004      break;
1005    case tok::kw___attribute:
1006      DS.AddAttributes(ParseAttributes());
1007      continue; // do *not* consume the next token!
1008    }
1009
1010    // If the specifier combination wasn't legal, issue a diagnostic.
1011    if (isInvalid) {
1012      assert(PrevSpec && "Method did not return previous specifier!");
1013      if (isInvalid == 1)  // Error.
1014        Diag(Tok, diag::err_invalid_decl_spec_combination, PrevSpec);
1015      else                 // extwarn.
1016        Diag(Tok, diag::ext_duplicate_declspec, PrevSpec);
1017    }
1018    ConsumeToken();
1019  }
1020}
1021
1022
1023/// ParseDeclarator - Parse and verify a newly-initialized declarator.
1024///
1025void Parser::ParseDeclarator(Declarator &D) {
1026  /// This implements the 'declarator' production in the C grammar, then checks
1027  /// for well-formedness and issues diagnostics.
1028  ParseDeclaratorInternal(D);
1029}
1030
1031/// ParseDeclaratorInternal
1032///       declarator: [C99 6.7.5]
1033///         pointer[opt] direct-declarator
1034/// [C++]   '&' declarator [C++ 8p4, dcl.decl]
1035/// [GNU]   '&' restrict[opt] attributes[opt] declarator
1036///
1037///       pointer: [C99 6.7.5]
1038///         '*' type-qualifier-list[opt]
1039///         '*' type-qualifier-list[opt] pointer
1040///
1041void Parser::ParseDeclaratorInternal(Declarator &D) {
1042  tok::TokenKind Kind = Tok.getKind();
1043
1044  // Not a pointer or C++ reference.
1045  if (Kind != tok::star && (Kind != tok::amp || !getLang().CPlusPlus))
1046    return ParseDirectDeclarator(D);
1047
1048  // Otherwise, '*' -> pointer or '&' -> reference.
1049  SourceLocation Loc = ConsumeToken();  // Eat the * or &.
1050
1051  if (Kind == tok::star) {
1052    // Is a pointer.
1053    DeclSpec DS;
1054
1055    ParseTypeQualifierListOpt(DS);
1056
1057    // Recursively parse the declarator.
1058    ParseDeclaratorInternal(D);
1059
1060    // Remember that we parsed a pointer type, and remember the type-quals.
1061    D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
1062                                              DS.TakeAttributes()));
1063  } else {
1064    // Is a reference
1065    DeclSpec DS;
1066
1067    // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
1068    // cv-qualifiers are introduced through the use of a typedef or of a
1069    // template type argument, in which case the cv-qualifiers are ignored.
1070    //
1071    // [GNU] Retricted references are allowed.
1072    // [GNU] Attributes on references are allowed.
1073    ParseTypeQualifierListOpt(DS);
1074
1075    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
1076      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1077        Diag(DS.getConstSpecLoc(),
1078             diag::err_invalid_reference_qualifier_application,
1079             "const");
1080      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
1081        Diag(DS.getVolatileSpecLoc(),
1082             diag::err_invalid_reference_qualifier_application,
1083             "volatile");
1084    }
1085
1086    // Recursively parse the declarator.
1087    ParseDeclaratorInternal(D);
1088
1089    // Remember that we parsed a reference type. It doesn't have type-quals.
1090    D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
1091                                                DS.TakeAttributes()));
1092  }
1093}
1094
1095/// ParseDirectDeclarator
1096///       direct-declarator: [C99 6.7.5]
1097///         identifier
1098///         '(' declarator ')'
1099/// [GNU]   '(' attributes declarator ')'
1100/// [C90]   direct-declarator '[' constant-expression[opt] ']'
1101/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1102/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1103/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1104/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
1105///         direct-declarator '(' parameter-type-list ')'
1106///         direct-declarator '(' identifier-list[opt] ')'
1107/// [GNU]   direct-declarator '(' parameter-forward-declarations
1108///                    parameter-type-list[opt] ')'
1109///
1110void Parser::ParseDirectDeclarator(Declarator &D) {
1111  // Parse the first direct-declarator seen.
1112  if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
1113    assert(Tok.getIdentifierInfo() && "Not an identifier?");
1114    D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1115    ConsumeToken();
1116  } else if (Tok.is(tok::l_paren)) {
1117    // direct-declarator: '(' declarator ')'
1118    // direct-declarator: '(' attributes declarator ')'
1119    // Example: 'char (*X)'   or 'int (*XX)(void)'
1120    ParseParenDeclarator(D);
1121  } else if (D.mayOmitIdentifier()) {
1122    // This could be something simple like "int" (in which case the declarator
1123    // portion is empty), if an abstract-declarator is allowed.
1124    D.SetIdentifier(0, Tok.getLocation());
1125  } else {
1126    // Expected identifier or '('.
1127    Diag(Tok, diag::err_expected_ident_lparen);
1128    D.SetIdentifier(0, Tok.getLocation());
1129  }
1130
1131  assert(D.isPastIdentifier() &&
1132         "Haven't past the location of the identifier yet?");
1133
1134  while (1) {
1135    if (Tok.is(tok::l_paren)) {
1136      ParseFunctionDeclarator(ConsumeParen(), D);
1137    } else if (Tok.is(tok::l_square)) {
1138      ParseBracketDeclarator(D);
1139    } else {
1140      break;
1141    }
1142  }
1143}
1144
1145/// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
1146/// only called before the identifier, so these are most likely just grouping
1147/// parens for precedence.  If we find that these are actually function
1148/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
1149///
1150///       direct-declarator:
1151///         '(' declarator ')'
1152/// [GNU]   '(' attributes declarator ')'
1153///
1154void Parser::ParseParenDeclarator(Declarator &D) {
1155  SourceLocation StartLoc = ConsumeParen();
1156  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
1157
1158  // If we haven't past the identifier yet (or where the identifier would be
1159  // stored, if this is an abstract declarator), then this is probably just
1160  // grouping parens. However, if this could be an abstract-declarator, then
1161  // this could also be the start of function arguments (consider 'void()').
1162  bool isGrouping;
1163
1164  if (!D.mayOmitIdentifier()) {
1165    // If this can't be an abstract-declarator, this *must* be a grouping
1166    // paren, because we haven't seen the identifier yet.
1167    isGrouping = true;
1168  } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
1169             isDeclarationSpecifier()) {       // 'int(int)' is a function.
1170    // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
1171    // considered to be a type, not a K&R identifier-list.
1172    isGrouping = false;
1173  } else {
1174    // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
1175    isGrouping = true;
1176  }
1177
1178  // If this is a grouping paren, handle:
1179  // direct-declarator: '(' declarator ')'
1180  // direct-declarator: '(' attributes declarator ')'
1181  if (isGrouping) {
1182    if (Tok.is(tok::kw___attribute))
1183      D.AddAttributes(ParseAttributes());
1184
1185    ParseDeclaratorInternal(D);
1186    // Match the ')'.
1187    MatchRHSPunctuation(tok::r_paren, StartLoc);
1188    return;
1189  }
1190
1191  // Okay, if this wasn't a grouping paren, it must be the start of a function
1192  // argument list.  Recognize that this declarator will never have an
1193  // identifier (and remember where it would have been), then fall through to
1194  // the handling of argument lists.
1195  D.SetIdentifier(0, Tok.getLocation());
1196
1197  ParseFunctionDeclarator(StartLoc, D);
1198}
1199
1200/// ParseFunctionDeclarator - We are after the identifier and have parsed the
1201/// declarator D up to a paren, which indicates that we are parsing function
1202/// arguments.
1203///
1204/// This method also handles this portion of the grammar:
1205///       parameter-type-list: [C99 6.7.5]
1206///         parameter-list
1207///         parameter-list ',' '...'
1208///
1209///       parameter-list: [C99 6.7.5]
1210///         parameter-declaration
1211///         parameter-list ',' parameter-declaration
1212///
1213///       parameter-declaration: [C99 6.7.5]
1214///         declaration-specifiers declarator
1215/// [C++]   declaration-specifiers declarator '=' assignment-expression
1216/// [GNU]   declaration-specifiers declarator attributes
1217///         declaration-specifiers abstract-declarator[opt]
1218/// [C++]   declaration-specifiers abstract-declarator[opt]
1219///           '=' assignment-expression
1220/// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
1221///
1222void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D) {
1223  // lparen is already consumed!
1224  assert(D.isPastIdentifier() && "Should not call before identifier!");
1225
1226  // Okay, this is the parameter list of a function definition, or it is an
1227  // identifier list of a K&R-style function.
1228
1229  if (Tok.is(tok::r_paren)) {
1230    // Remember that we parsed a function type, and remember the attributes.
1231    // int() -> no prototype, no '...'.
1232    D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/ false,
1233                                               /*variadic*/ false,
1234                                               /*arglist*/ 0, 0, LParenLoc));
1235
1236    ConsumeParen();  // Eat the closing ')'.
1237    return;
1238  } else if (Tok.is(tok::identifier) &&
1239             // K&R identifier lists can't have typedefs as identifiers, per
1240             // C99 6.7.5.3p11.
1241             !Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope)) {
1242    // Identifier list.  Note that '(' identifier-list ')' is only allowed for
1243    // normal declarators, not for abstract-declarators.
1244    return ParseFunctionDeclaratorIdentifierList(LParenLoc, D);
1245  }
1246
1247  // Finally, a normal, non-empty parameter type list.
1248
1249  // Build up an array of information about the parsed arguments.
1250  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1251
1252  // Enter function-declaration scope, limiting any declarators to the
1253  // function prototype scope, including parameter declarators.
1254  EnterScope(Scope::FnScope|Scope::DeclScope);
1255
1256  bool IsVariadic = false;
1257  while (1) {
1258    if (Tok.is(tok::ellipsis)) {
1259      IsVariadic = true;
1260
1261      // Check to see if this is "void(...)" which is not allowed.
1262      if (ParamInfo.empty()) {
1263        // Otherwise, parse parameter type list.  If it starts with an
1264        // ellipsis,  diagnose the malformed function.
1265        Diag(Tok, diag::err_ellipsis_first_arg);
1266        IsVariadic = false;       // Treat this like 'void()'.
1267      }
1268
1269      ConsumeToken();     // Consume the ellipsis.
1270      break;
1271    }
1272
1273    SourceLocation DSStart = Tok.getLocation();
1274
1275    // Parse the declaration-specifiers.
1276    DeclSpec DS;
1277    ParseDeclarationSpecifiers(DS);
1278
1279    // Parse the declarator.  This is "PrototypeContext", because we must
1280    // accept either 'declarator' or 'abstract-declarator' here.
1281    Declarator ParmDecl(DS, Declarator::PrototypeContext);
1282    ParseDeclarator(ParmDecl);
1283
1284    // Parse GNU attributes, if present.
1285    if (Tok.is(tok::kw___attribute))
1286      ParmDecl.AddAttributes(ParseAttributes());
1287
1288    // Remember this parsed parameter in ParamInfo.
1289    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1290
1291    // If no parameter was specified, verify that *something* was specified,
1292    // otherwise we have a missing type and identifier.
1293    if (DS.getParsedSpecifiers() == DeclSpec::PQ_None &&
1294        ParmDecl.getIdentifier() == 0 && ParmDecl.getNumTypeObjects() == 0) {
1295      // Completely missing, emit error.
1296      Diag(DSStart, diag::err_missing_param);
1297    } else {
1298      // Otherwise, we have something.  Add it and let semantic analysis try
1299      // to grok it and add the result to the ParamInfo we are building.
1300
1301      // Inform the actions module about the parameter declarator, so it gets
1302      // added to the current scope.
1303      DeclTy *Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl);
1304
1305      // Parse the default argument, if any. We parse the default
1306      // arguments in all dialects; the semantic analysis in
1307      // ActOnParamDefaultArgument will reject the default argument in
1308      // C.
1309      if (Tok.is(tok::equal)) {
1310        SourceLocation EqualLoc = Tok.getLocation();
1311
1312        // Consume the '='.
1313        ConsumeToken();
1314
1315        // Parse the default argument
1316        ExprResult DefArgResult = ParseAssignmentExpression();
1317        if (DefArgResult.isInvalid) {
1318          SkipUntil(tok::comma, tok::r_paren, true, true);
1319        } else {
1320          // Inform the actions module about the default argument
1321          Actions.ActOnParamDefaultArgument(Param, EqualLoc, DefArgResult.Val);
1322        }
1323      }
1324
1325      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1326                             ParmDecl.getIdentifierLoc(), Param));
1327    }
1328
1329    // If the next token is a comma, consume it and keep reading arguments.
1330    if (Tok.isNot(tok::comma)) break;
1331
1332    // Consume the comma.
1333    ConsumeToken();
1334  }
1335
1336  // Leave prototype scope.
1337  ExitScope();
1338
1339  // Remember that we parsed a function type, and remember the attributes.
1340  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
1341                                             &ParamInfo[0], ParamInfo.size(),
1342                                             LParenLoc));
1343
1344  // If we have the closing ')', eat it and we're done.
1345  MatchRHSPunctuation(tok::r_paren, LParenLoc);
1346}
1347
1348/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
1349/// we found a K&R-style identifier list instead of a type argument list.  The
1350/// current token is known to be the first identifier in the list.
1351///
1352///       identifier-list: [C99 6.7.5]
1353///         identifier
1354///         identifier-list ',' identifier
1355///
1356void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
1357                                                   Declarator &D) {
1358  // Build up an array of information about the parsed arguments.
1359  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1360  llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
1361
1362  // If there was no identifier specified for the declarator, either we are in
1363  // an abstract-declarator, or we are in a parameter declarator which was found
1364  // to be abstract.  In abstract-declarators, identifier lists are not valid:
1365  // diagnose this.
1366  if (!D.getIdentifier())
1367    Diag(Tok, diag::ext_ident_list_in_param);
1368
1369  // Tok is known to be the first identifier in the list.  Remember this
1370  // identifier in ParamInfo.
1371  ParamsSoFar.insert(Tok.getIdentifierInfo());
1372  ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
1373                                                 Tok.getLocation(), 0));
1374
1375  ConsumeToken();  // eat the first identifier.
1376
1377  while (Tok.is(tok::comma)) {
1378    // Eat the comma.
1379    ConsumeToken();
1380
1381    // If this isn't an identifier, report the error and skip until ')'.
1382    if (Tok.isNot(tok::identifier)) {
1383      Diag(Tok, diag::err_expected_ident);
1384      SkipUntil(tok::r_paren);
1385      return;
1386    }
1387
1388    IdentifierInfo *ParmII = Tok.getIdentifierInfo();
1389
1390    // Reject 'typedef int y; int test(x, y)', but continue parsing.
1391    if (Actions.isTypeName(*ParmII, CurScope))
1392      Diag(Tok, diag::err_unexpected_typedef_ident, ParmII->getName());
1393
1394    // Verify that the argument identifier has not already been mentioned.
1395    if (!ParamsSoFar.insert(ParmII)) {
1396      Diag(Tok.getLocation(), diag::err_param_redefinition, ParmII->getName());
1397    } else {
1398      // Remember this identifier in ParamInfo.
1399      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1400                                                     Tok.getLocation(), 0));
1401    }
1402
1403    // Eat the identifier.
1404    ConsumeToken();
1405  }
1406
1407  // Remember that we parsed a function type, and remember the attributes.  This
1408  // function type is always a K&R style function type, which is not varargs and
1409  // has no prototype.
1410  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
1411                                             &ParamInfo[0], ParamInfo.size(),
1412                                             LParenLoc));
1413
1414  // If we have the closing ')', eat it and we're done.
1415  MatchRHSPunctuation(tok::r_paren, LParenLoc);
1416}
1417
1418/// [C90]   direct-declarator '[' constant-expression[opt] ']'
1419/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1420/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1421/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1422/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
1423void Parser::ParseBracketDeclarator(Declarator &D) {
1424  SourceLocation StartLoc = ConsumeBracket();
1425
1426  // If valid, this location is the position where we read the 'static' keyword.
1427  SourceLocation StaticLoc;
1428  if (Tok.is(tok::kw_static))
1429    StaticLoc = ConsumeToken();
1430
1431  // If there is a type-qualifier-list, read it now.
1432  DeclSpec DS;
1433  ParseTypeQualifierListOpt(DS);
1434
1435  // If we haven't already read 'static', check to see if there is one after the
1436  // type-qualifier-list.
1437  if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
1438    StaticLoc = ConsumeToken();
1439
1440  // Handle "direct-declarator [ type-qual-list[opt] * ]".
1441  bool isStar = false;
1442  ExprResult NumElements(false);
1443
1444  // Handle the case where we have '[*]' as the array size.  However, a leading
1445  // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
1446  // the the token after the star is a ']'.  Since stars in arrays are
1447  // infrequent, use of lookahead is not costly here.
1448  if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
1449    ConsumeToken();  // Eat the '*'.
1450
1451    if (StaticLoc.isValid())
1452      Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
1453    StaticLoc = SourceLocation();  // Drop the static.
1454    isStar = true;
1455  } else if (Tok.isNot(tok::r_square)) {
1456    // Parse the assignment-expression now.
1457    NumElements = ParseAssignmentExpression();
1458  }
1459
1460  // If there was an error parsing the assignment-expression, recover.
1461  if (NumElements.isInvalid) {
1462    // If the expression was invalid, skip it.
1463    SkipUntil(tok::r_square);
1464    return;
1465  }
1466
1467  MatchRHSPunctuation(tok::r_square, StartLoc);
1468
1469  // If C99 isn't enabled, emit an ext-warn if the arg list wasn't empty and if
1470  // it was not a constant expression.
1471  if (!getLang().C99) {
1472    // TODO: check C90 array constant exprness.
1473    if (isStar || StaticLoc.isValid() ||
1474        0/*TODO: NumElts is not a C90 constantexpr */)
1475      Diag(StartLoc, diag::ext_c99_array_usage);
1476  }
1477
1478  // Remember that we parsed a pointer type, and remember the type-quals.
1479  D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
1480                                          StaticLoc.isValid(), isStar,
1481                                          NumElements.Val, StartLoc));
1482}
1483
1484/// [GNU] typeof-specifier:
1485///         typeof ( expressions )
1486///         typeof ( type-name )
1487///
1488void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
1489  assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
1490  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1491  SourceLocation StartLoc = ConsumeToken();
1492
1493  if (Tok.isNot(tok::l_paren)) {
1494    Diag(Tok, diag::err_expected_lparen_after, BuiltinII->getName());
1495    return;
1496  }
1497  SourceLocation LParenLoc = ConsumeParen(), RParenLoc;
1498
1499  if (isTypeSpecifierQualifier()) {
1500    TypeTy *Ty = ParseTypeName();
1501
1502    assert(Ty && "Parser::ParseTypeofSpecifier(): missing type");
1503
1504    if (Tok.isNot(tok::r_paren)) {
1505      MatchRHSPunctuation(tok::r_paren, LParenLoc);
1506      return;
1507    }
1508    RParenLoc = ConsumeParen();
1509    const char *PrevSpec = 0;
1510    // Check for duplicate type specifiers (e.g. "int typeof(int)").
1511    if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, Ty))
1512      Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
1513  } else { // we have an expression.
1514    ExprResult Result = ParseExpression();
1515
1516    if (Result.isInvalid || Tok.isNot(tok::r_paren)) {
1517      MatchRHSPunctuation(tok::r_paren, LParenLoc);
1518      return;
1519    }
1520    RParenLoc = ConsumeParen();
1521    const char *PrevSpec = 0;
1522    // Check for duplicate type specifiers (e.g. "int typeof(int)").
1523    if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
1524                           Result.Val))
1525      Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
1526  }
1527}
1528
1529
1530