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