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