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