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