ParseDecl.cpp revision 7a0ab5f387722c83e19c7133b46b16988eb19e45
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/Scope.h"
17#include "ExtensionRAIIObject.h"
18#include "AstGuard.h"
19#include "llvm/ADT/SmallSet.h"
20using namespace clang;
21
22//===----------------------------------------------------------------------===//
23// C99 6.7: Declarations.
24//===----------------------------------------------------------------------===//
25
26/// ParseTypeName
27///       type-name: [C99 6.7.6]
28///         specifier-qualifier-list abstract-declarator[opt]
29///
30/// Called type-id in C++.
31Parser::TypeTy *Parser::ParseTypeName() {
32  // Parse the common declaration-specifiers piece.
33  DeclSpec DS;
34  ParseSpecifierQualifierList(DS);
35
36  // Parse the abstract-declarator, if present.
37  Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
38  ParseDeclarator(DeclaratorInfo);
39
40  return Actions.ActOnTypeName(CurScope, DeclaratorInfo).Val;
41}
42
43/// ParseAttributes - Parse a non-empty attributes list.
44///
45/// [GNU] attributes:
46///         attribute
47///         attributes attribute
48///
49/// [GNU]  attribute:
50///          '__attribute__' '(' '(' attribute-list ')' ')'
51///
52/// [GNU]  attribute-list:
53///          attrib
54///          attribute_list ',' attrib
55///
56/// [GNU]  attrib:
57///          empty
58///          attrib-name
59///          attrib-name '(' identifier ')'
60///          attrib-name '(' identifier ',' nonempty-expr-list ')'
61///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
62///
63/// [GNU]  attrib-name:
64///          identifier
65///          typespec
66///          typequal
67///          storageclass
68///
69/// FIXME: The GCC grammar/code for this construct implies we need two
70/// token lookahead. Comment from gcc: "If they start with an identifier
71/// which is followed by a comma or close parenthesis, then the arguments
72/// start with that identifier; otherwise they are an expression list."
73///
74/// At the moment, I am not doing 2 token lookahead. I am also unaware of
75/// any attributes that don't work (based on my limited testing). Most
76/// attributes are very simple in practice. Until we find a bug, I don't see
77/// a pressing need to implement the 2 token lookahead.
78
79AttributeList *Parser::ParseAttributes() {
80  assert(Tok.is(tok::kw___attribute) && "Not an attribute list!");
81
82  AttributeList *CurrAttr = 0;
83
84  while (Tok.is(tok::kw___attribute)) {
85    ConsumeToken();
86    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
87                         "attribute")) {
88      SkipUntil(tok::r_paren, true); // skip until ) or ;
89      return CurrAttr;
90    }
91    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
92      SkipUntil(tok::r_paren, true); // skip until ) or ;
93      return CurrAttr;
94    }
95    // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
96    while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
97           Tok.is(tok::comma)) {
98
99      if (Tok.is(tok::comma)) {
100        // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
101        ConsumeToken();
102        continue;
103      }
104      // we have an identifier or declaration specifier (const, int, etc.)
105      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
106      SourceLocation AttrNameLoc = ConsumeToken();
107
108      // check if we have a "paramterized" attribute
109      if (Tok.is(tok::l_paren)) {
110        ConsumeParen(); // ignore the left paren loc for now
111
112        if (Tok.is(tok::identifier)) {
113          IdentifierInfo *ParmName = Tok.getIdentifierInfo();
114          SourceLocation ParmLoc = ConsumeToken();
115
116          if (Tok.is(tok::r_paren)) {
117            // __attribute__(( mode(byte) ))
118            ConsumeParen(); // ignore the right paren loc for now
119            CurrAttr = new AttributeList(AttrName, AttrNameLoc,
120                                         ParmName, ParmLoc, 0, 0, CurrAttr);
121          } else if (Tok.is(tok::comma)) {
122            ConsumeToken();
123            // __attribute__(( format(printf, 1, 2) ))
124            ExprVector ArgExprs(Actions);
125            bool ArgExprsOk = true;
126
127            // now parse the non-empty comma separated list of expressions
128            while (1) {
129              OwningExprResult ArgExpr(ParseAssignmentExpression());
130              if (ArgExpr.isInvalid()) {
131                ArgExprsOk = false;
132                SkipUntil(tok::r_paren);
133                break;
134              } else {
135                ArgExprs.push_back(ArgExpr.release());
136              }
137              if (Tok.isNot(tok::comma))
138                break;
139              ConsumeToken(); // Eat the comma, move to the next argument
140            }
141            if (ArgExprsOk && Tok.is(tok::r_paren)) {
142              ConsumeParen(); // ignore the right paren loc for now
143              CurrAttr = new AttributeList(AttrName, AttrNameLoc, ParmName,
144                           ParmLoc, ArgExprs.take(), ArgExprs.size(), CurrAttr);
145            }
146          }
147        } else { // not an identifier
148          // parse a possibly empty comma separated list of expressions
149          if (Tok.is(tok::r_paren)) {
150            // __attribute__(( nonnull() ))
151            ConsumeParen(); // ignore the right paren loc for now
152            CurrAttr = new AttributeList(AttrName, AttrNameLoc,
153                                         0, SourceLocation(), 0, 0, CurrAttr);
154          } else {
155            // __attribute__(( aligned(16) ))
156            ExprVector ArgExprs(Actions);
157            bool ArgExprsOk = true;
158
159            // now parse the list of expressions
160            while (1) {
161              OwningExprResult ArgExpr(ParseAssignmentExpression());
162              if (ArgExpr.isInvalid()) {
163                ArgExprsOk = false;
164                SkipUntil(tok::r_paren);
165                break;
166              } else {
167                ArgExprs.push_back(ArgExpr.release());
168              }
169              if (Tok.isNot(tok::comma))
170                break;
171              ConsumeToken(); // Eat the comma, move to the next argument
172            }
173            // Match the ')'.
174            if (ArgExprsOk && Tok.is(tok::r_paren)) {
175              ConsumeParen(); // ignore the right paren loc for now
176              CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0,
177                           SourceLocation(), ArgExprs.take(), ArgExprs.size(),
178                           CurrAttr);
179            }
180          }
181        }
182      } else {
183        CurrAttr = new AttributeList(AttrName, AttrNameLoc,
184                                     0, SourceLocation(), 0, 0, CurrAttr);
185      }
186    }
187    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
188      SkipUntil(tok::r_paren, false);
189    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
190      SkipUntil(tok::r_paren, false);
191  }
192  return CurrAttr;
193}
194
195/// FuzzyParseMicrosoftDeclSpec. When -fms-extensions is enabled, this
196/// routine is called to skip/ignore tokens that comprise the MS declspec.
197void Parser::FuzzyParseMicrosoftDeclSpec() {
198  assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
199  ConsumeToken();
200  if (Tok.is(tok::l_paren)) {
201    unsigned short savedParenCount = ParenCount;
202    do {
203      ConsumeAnyToken();
204    } while (ParenCount > savedParenCount && Tok.isNot(tok::eof));
205  }
206  return;
207}
208
209/// ParseDeclaration - Parse a full 'declaration', which consists of
210/// declaration-specifiers, some number of declarators, and a semicolon.
211/// 'Context' should be a Declarator::TheContext value.
212///
213///       declaration: [C99 6.7]
214///         block-declaration ->
215///           simple-declaration
216///           others                   [FIXME]
217/// [C++]   template-declaration
218/// [C++]   namespace-definition
219/// [C++]   using-directive
220/// [C++]   using-declaration [TODO]
221///         others... [FIXME]
222///
223Parser::DeclTy *Parser::ParseDeclaration(unsigned Context) {
224  switch (Tok.getKind()) {
225  case tok::kw_export:
226  case tok::kw_template:
227    return ParseTemplateDeclaration(Context);
228  case tok::kw_namespace:
229    return ParseNamespace(Context);
230  case tok::kw_using:
231    return ParseUsingDirectiveOrDeclaration(Context);
232  default:
233    return ParseSimpleDeclaration(Context);
234  }
235}
236
237///       simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
238///         declaration-specifiers init-declarator-list[opt] ';'
239///[C90/C++]init-declarator-list ';'                             [TODO]
240/// [OMP]   threadprivate-directive                              [TODO]
241Parser::DeclTy *Parser::ParseSimpleDeclaration(unsigned Context) {
242  // Parse the common declaration-specifiers piece.
243  DeclSpec DS;
244  ParseDeclarationSpecifiers(DS);
245
246  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
247  // declaration-specifiers init-declarator-list[opt] ';'
248  if (Tok.is(tok::semi)) {
249    ConsumeToken();
250    return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
251  }
252
253  Declarator DeclaratorInfo(DS, (Declarator::TheContext)Context);
254  ParseDeclarator(DeclaratorInfo);
255
256  return ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo);
257}
258
259
260/// ParseInitDeclaratorListAfterFirstDeclarator - Parse 'declaration' after
261/// parsing 'declaration-specifiers declarator'.  This method is split out this
262/// way to handle the ambiguity between top-level function-definitions and
263/// declarations.
264///
265///       init-declarator-list: [C99 6.7]
266///         init-declarator
267///         init-declarator-list ',' init-declarator
268///       init-declarator: [C99 6.7]
269///         declarator
270///         declarator '=' initializer
271/// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
272/// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
273/// [C++]   declarator initializer[opt]
274///
275/// [C++] initializer:
276/// [C++]   '=' initializer-clause
277/// [C++]   '(' expression-list ')'
278///
279Parser::DeclTy *Parser::
280ParseInitDeclaratorListAfterFirstDeclarator(Declarator &D) {
281
282  // Declarators may be grouped together ("int X, *Y, Z();").  Provide info so
283  // that they can be chained properly if the actions want this.
284  Parser::DeclTy *LastDeclInGroup = 0;
285
286  // At this point, we know that it is not a function definition.  Parse the
287  // rest of the init-declarator-list.
288  while (1) {
289    // If a simple-asm-expr is present, parse it.
290    if (Tok.is(tok::kw_asm)) {
291      OwningExprResult AsmLabel(ParseSimpleAsm());
292      if (AsmLabel.isInvalid()) {
293        SkipUntil(tok::semi);
294        return 0;
295      }
296
297      D.setAsmLabel(AsmLabel.release());
298    }
299
300    // If attributes are present, parse them.
301    if (Tok.is(tok::kw___attribute))
302      D.AddAttributes(ParseAttributes());
303
304    // Inform the current actions module that we just parsed this declarator.
305    LastDeclInGroup = Actions.ActOnDeclarator(CurScope, D, LastDeclInGroup);
306
307    // Parse declarator '=' initializer.
308    if (Tok.is(tok::equal)) {
309      ConsumeToken();
310      OwningExprResult Init(ParseInitializer());
311      if (Init.isInvalid()) {
312        SkipUntil(tok::semi);
313        return 0;
314      }
315      Actions.AddInitializerToDecl(LastDeclInGroup, move_convert(Init));
316    } else if (Tok.is(tok::l_paren)) {
317      // Parse C++ direct initializer: '(' expression-list ')'
318      SourceLocation LParenLoc = ConsumeParen();
319      ExprVector Exprs(Actions);
320      CommaLocsTy CommaLocs;
321
322      bool InvalidExpr = false;
323      if (ParseExpressionList(Exprs, CommaLocs)) {
324        SkipUntil(tok::r_paren);
325        InvalidExpr = true;
326      }
327      // Match the ')'.
328      SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
329
330      if (!InvalidExpr) {
331        assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
332               "Unexpected number of commas!");
333        Actions.AddCXXDirectInitializerToDecl(LastDeclInGroup, LParenLoc,
334                                              Exprs.take(), Exprs.size(),
335                                              &CommaLocs[0], RParenLoc);
336      }
337    } else {
338      Actions.ActOnUninitializedDecl(LastDeclInGroup);
339    }
340
341    // If we don't have a comma, it is either the end of the list (a ';') or an
342    // error, bail out.
343    if (Tok.isNot(tok::comma))
344      break;
345
346    // Consume the comma.
347    ConsumeToken();
348
349    // Parse the next declarator.
350    D.clear();
351
352    // Accept attributes in an init-declarator.  In the first declarator in a
353    // declaration, these would be part of the declspec.  In subsequent
354    // declarators, they become part of the declarator itself, so that they
355    // don't apply to declarators after *this* one.  Examples:
356    //    short __attribute__((common)) var;    -> declspec
357    //    short var __attribute__((common));    -> declarator
358    //    short x, __attribute__((common)) var;    -> declarator
359    if (Tok.is(tok::kw___attribute))
360      D.AddAttributes(ParseAttributes());
361
362    ParseDeclarator(D);
363  }
364
365  if (Tok.is(tok::semi)) {
366    ConsumeToken();
367    return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup);
368  }
369  // If this is an ObjC2 for-each loop, this is a successful declarator
370  // parse.  The syntax for these looks like:
371  // 'for' '(' declaration 'in' expr ')' statement
372  if (D.getContext()  == Declarator::ForContext && isTokIdentifier_in()) {
373    return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup);
374  }
375  Diag(Tok, diag::err_parse_error);
376  // Skip to end of block or statement
377  SkipUntil(tok::r_brace, true, true);
378  if (Tok.is(tok::semi))
379    ConsumeToken();
380  return 0;
381}
382
383/// ParseSpecifierQualifierList
384///        specifier-qualifier-list:
385///          type-specifier specifier-qualifier-list[opt]
386///          type-qualifier specifier-qualifier-list[opt]
387/// [GNU]    attributes     specifier-qualifier-list[opt]
388///
389void Parser::ParseSpecifierQualifierList(DeclSpec &DS) {
390  /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
391  /// parse declaration-specifiers and complain about extra stuff.
392  ParseDeclarationSpecifiers(DS);
393
394  // Validate declspec for type-name.
395  unsigned Specs = DS.getParsedSpecifiers();
396  if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers())
397    Diag(Tok, diag::err_typename_requires_specqual);
398
399  // Issue diagnostic and remove storage class if present.
400  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
401    if (DS.getStorageClassSpecLoc().isValid())
402      Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
403    else
404      Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
405    DS.ClearStorageClassSpecs();
406  }
407
408  // Issue diagnostic and remove function specfier if present.
409  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
410    if (DS.isInlineSpecified())
411      Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
412    if (DS.isVirtualSpecified())
413      Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
414    if (DS.isExplicitSpecified())
415      Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
416    DS.ClearFunctionSpecs();
417  }
418}
419
420/// ParseDeclarationSpecifiers
421///       declaration-specifiers: [C99 6.7]
422///         storage-class-specifier declaration-specifiers[opt]
423///         type-specifier declaration-specifiers[opt]
424/// [C99]   function-specifier declaration-specifiers[opt]
425/// [GNU]   attributes declaration-specifiers[opt]
426///
427///       storage-class-specifier: [C99 6.7.1]
428///         'typedef'
429///         'extern'
430///         'static'
431///         'auto'
432///         'register'
433/// [C++]   'mutable'
434/// [GNU]   '__thread'
435///       function-specifier: [C99 6.7.4]
436/// [C99]   'inline'
437/// [C++]   'virtual'
438/// [C++]   'explicit'
439///
440void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
441                                        TemplateParameterLists *TemplateParams){
442  DS.SetRangeStart(Tok.getLocation());
443  while (1) {
444    int isInvalid = false;
445    const char *PrevSpec = 0;
446    SourceLocation Loc = Tok.getLocation();
447
448    switch (Tok.getKind()) {
449    default:
450      // Try to parse a type-specifier; if we found one, continue. If it's not
451      // a type, this falls through.
452      if (ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, TemplateParams))
453        continue;
454
455    DoneWithDeclSpec:
456      // If this is not a declaration specifier token, we're done reading decl
457      // specifiers.  First verify that DeclSpec's are consistent.
458      DS.Finish(Diags, PP.getSourceManager(), getLang());
459      return;
460
461    case tok::coloncolon: // ::foo::bar
462      // Annotate C++ scope specifiers.  If we get one, loop.
463      if (TryAnnotateCXXScopeToken())
464        continue;
465      goto DoneWithDeclSpec;
466
467    case tok::annot_cxxscope: {
468      if (DS.hasTypeSpecifier())
469        goto DoneWithDeclSpec;
470
471      // We are looking for a qualified typename.
472      if (NextToken().isNot(tok::identifier))
473        goto DoneWithDeclSpec;
474
475      CXXScopeSpec SS;
476      SS.setScopeRep(Tok.getAnnotationValue());
477      SS.setRange(Tok.getAnnotationRange());
478
479      // If the next token is the name of the class type that the C++ scope
480      // denotes, followed by a '(', then this is a constructor declaration.
481      // We're done with the decl-specifiers.
482      if (Actions.isCurrentClassName(*NextToken().getIdentifierInfo(),
483                                     CurScope, &SS) &&
484          GetLookAheadToken(2).is(tok::l_paren))
485        goto DoneWithDeclSpec;
486
487      TypeTy *TypeRep = Actions.isTypeName(*NextToken().getIdentifierInfo(),
488                                           CurScope, &SS);
489      if (TypeRep == 0)
490        goto DoneWithDeclSpec;
491
492      ConsumeToken(); // The C++ scope.
493
494      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typedef, Loc, PrevSpec,
495                                     TypeRep);
496      if (isInvalid)
497        break;
498
499      DS.SetRangeEnd(Tok.getLocation());
500      ConsumeToken(); // The typename.
501
502      continue;
503    }
504
505      // typedef-name
506    case tok::identifier: {
507      // In C++, check to see if this is a scope specifier like foo::bar::, if
508      // so handle it as such.  This is important for ctor parsing.
509      if (getLang().CPlusPlus &&
510        TryAnnotateCXXScopeToken())
511          continue;
512
513      // This identifier can only be a typedef name if we haven't already seen
514      // a type-specifier.  Without this check we misparse:
515      //  typedef int X; struct Y { short X; };  as 'short int'.
516      if (DS.hasTypeSpecifier())
517        goto DoneWithDeclSpec;
518
519      // It has to be available as a typedef too!
520      TypeTy *TypeRep = Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope);
521      if (TypeRep == 0)
522        goto DoneWithDeclSpec;
523
524      // C++: If the identifier is actually the name of the class type
525      // being defined and the next token is a '(', then this is a
526      // constructor declaration. We're done with the decl-specifiers
527      // and will treat this token as an identifier.
528      if (getLang().CPlusPlus &&
529          CurScope->isCXXClassScope() &&
530          Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) &&
531          NextToken().getKind() == tok::l_paren)
532        goto DoneWithDeclSpec;
533
534      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typedef, Loc, PrevSpec,
535                                     TypeRep);
536      if (isInvalid)
537        break;
538
539      DS.SetRangeEnd(Tok.getLocation());
540      ConsumeToken(); // The identifier
541
542      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
543      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
544      // Objective-C interface.  If we don't have Objective-C or a '<', this is
545      // just a normal reference to a typedef name.
546      if (!Tok.is(tok::less) || !getLang().ObjC1)
547        continue;
548
549      SourceLocation EndProtoLoc;
550      llvm::SmallVector<DeclTy *, 8> ProtocolDecl;
551      ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
552      DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size());
553
554      DS.SetRangeEnd(EndProtoLoc);
555
556      // Need to support trailing type qualifiers (e.g. "id<p> const").
557      // If a type specifier follows, it will be diagnosed elsewhere.
558      continue;
559    }
560    // GNU attributes support.
561    case tok::kw___attribute:
562      DS.AddAttributes(ParseAttributes());
563      continue;
564
565    // Microsoft declspec support.
566    case tok::kw___declspec:
567      if (!PP.getLangOptions().Microsoft)
568        goto DoneWithDeclSpec;
569      FuzzyParseMicrosoftDeclSpec();
570      continue;
571
572    // Microsoft single token adornments.
573    case tok::kw___forceinline:
574    case tok::kw___w64:
575    case tok::kw___cdecl:
576    case tok::kw___stdcall:
577    case tok::kw___fastcall:
578      if (!PP.getLangOptions().Microsoft)
579        goto DoneWithDeclSpec;
580      // Just ignore it.
581      break;
582
583    // storage-class-specifier
584    case tok::kw_typedef:
585      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec);
586      break;
587    case tok::kw_extern:
588      if (DS.isThreadSpecified())
589        Diag(Tok, diag::ext_thread_before) << "extern";
590      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec);
591      break;
592    case tok::kw___private_extern__:
593      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
594                                         PrevSpec);
595      break;
596    case tok::kw_static:
597      if (DS.isThreadSpecified())
598        Diag(Tok, diag::ext_thread_before) << "static";
599      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec);
600      break;
601    case tok::kw_auto:
602      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec);
603      break;
604    case tok::kw_register:
605      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec);
606      break;
607    case tok::kw_mutable:
608      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec);
609      break;
610    case tok::kw___thread:
611      isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec)*2;
612      break;
613
614      continue;
615
616    // function-specifier
617    case tok::kw_inline:
618      isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec);
619      break;
620
621    case tok::kw_virtual:
622      isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec);
623      break;
624
625    case tok::kw_explicit:
626      isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec);
627      break;
628
629    case tok::less:
630      // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
631      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
632      // but we support it.
633      if (DS.hasTypeSpecifier() || !getLang().ObjC1)
634        goto DoneWithDeclSpec;
635
636      {
637        SourceLocation EndProtoLoc;
638        llvm::SmallVector<DeclTy *, 8> ProtocolDecl;
639        ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
640        DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size());
641        DS.SetRangeEnd(EndProtoLoc);
642
643        Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
644          << SourceRange(Loc, EndProtoLoc);
645        // Need to support trailing type qualifiers (e.g. "id<p> const").
646        // If a type specifier follows, it will be diagnosed elsewhere.
647        continue;
648      }
649    }
650    // If the specifier combination wasn't legal, issue a diagnostic.
651    if (isInvalid) {
652      assert(PrevSpec && "Method did not return previous specifier!");
653      // Pick between error or extwarn.
654      unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination
655                                       : diag::ext_duplicate_declspec;
656      Diag(Tok, DiagID) << PrevSpec;
657    }
658    DS.SetRangeEnd(Tok.getLocation());
659    ConsumeToken();
660  }
661}
662
663/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
664/// primarily follow the C++ grammar with additions for C99 and GNU,
665/// which together subsume the C grammar. Note that the C++
666/// type-specifier also includes the C type-qualifier (for const,
667/// volatile, and C99 restrict). Returns true if a type-specifier was
668/// found (and parsed), false otherwise.
669///
670///       type-specifier: [C++ 7.1.5]
671///         simple-type-specifier
672///         class-specifier
673///         enum-specifier
674///         elaborated-type-specifier  [TODO]
675///         cv-qualifier
676///
677///       cv-qualifier: [C++ 7.1.5.1]
678///         'const'
679///         'volatile'
680/// [C99]   'restrict'
681///
682///       simple-type-specifier: [ C++ 7.1.5.2]
683///         '::'[opt] nested-name-specifier[opt] type-name [TODO]
684///         '::'[opt] nested-name-specifier 'template' template-id [TODO]
685///         'char'
686///         'wchar_t'
687///         'bool'
688///         'short'
689///         'int'
690///         'long'
691///         'signed'
692///         'unsigned'
693///         'float'
694///         'double'
695///         'void'
696/// [C99]   '_Bool'
697/// [C99]   '_Complex'
698/// [C99]   '_Imaginary'  // Removed in TC2?
699/// [GNU]   '_Decimal32'
700/// [GNU]   '_Decimal64'
701/// [GNU]   '_Decimal128'
702/// [GNU]   typeof-specifier
703/// [OBJC]  class-name objc-protocol-refs[opt]    [TODO]
704/// [OBJC]  typedef-name objc-protocol-refs[opt]  [TODO]
705bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, int& isInvalid,
706                                        const char *&PrevSpec,
707                                        TemplateParameterLists *TemplateParams){
708  SourceLocation Loc = Tok.getLocation();
709
710  switch (Tok.getKind()) {
711  case tok::identifier:   // foo::bar
712    // Annotate typenames and C++ scope specifiers.  If we get one, just
713    // recurse to handle whatever we get.
714    if (TryAnnotateTypeOrScopeToken())
715      return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec,TemplateParams);
716    // Otherwise, not a type specifier.
717    return false;
718  case tok::coloncolon:   // ::foo::bar
719    if (NextToken().is(tok::kw_new) ||    // ::new
720        NextToken().is(tok::kw_delete))   // ::delete
721      return false;
722
723    // Annotate typenames and C++ scope specifiers.  If we get one, just
724    // recurse to handle whatever we get.
725    if (TryAnnotateTypeOrScopeToken())
726      return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec,TemplateParams);
727    // Otherwise, not a type specifier.
728    return false;
729
730  // simple-type-specifier:
731  case tok::annot_typename: {
732    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typedef, Loc, PrevSpec,
733                                   Tok.getAnnotationValue());
734    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
735    ConsumeToken(); // The typename
736
737    // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
738    // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
739    // Objective-C interface.  If we don't have Objective-C or a '<', this is
740    // just a normal reference to a typedef name.
741    if (!Tok.is(tok::less) || !getLang().ObjC1)
742      return true;
743
744    SourceLocation EndProtoLoc;
745    llvm::SmallVector<DeclTy *, 8> ProtocolDecl;
746    ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
747    DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size());
748
749    DS.SetRangeEnd(EndProtoLoc);
750    return true;
751  }
752
753  case tok::kw_short:
754    isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec);
755    break;
756  case tok::kw_long:
757    if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
758      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec);
759    else
760      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec);
761    break;
762  case tok::kw_signed:
763    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec);
764    break;
765  case tok::kw_unsigned:
766    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec);
767    break;
768  case tok::kw__Complex:
769    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec);
770    break;
771  case tok::kw__Imaginary:
772    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec);
773    break;
774  case tok::kw_void:
775    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec);
776    break;
777  case tok::kw_char:
778    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec);
779    break;
780  case tok::kw_int:
781    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec);
782    break;
783  case tok::kw_float:
784    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec);
785    break;
786  case tok::kw_double:
787    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec);
788    break;
789  case tok::kw_wchar_t:
790    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec);
791    break;
792  case tok::kw_bool:
793  case tok::kw__Bool:
794    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec);
795    break;
796  case tok::kw__Decimal32:
797    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec);
798    break;
799  case tok::kw__Decimal64:
800    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec);
801    break;
802  case tok::kw__Decimal128:
803    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec);
804    break;
805
806  // class-specifier:
807  case tok::kw_class:
808  case tok::kw_struct:
809  case tok::kw_union:
810    ParseClassSpecifier(DS, TemplateParams);
811    return true;
812
813  // enum-specifier:
814  case tok::kw_enum:
815    ParseEnumSpecifier(DS);
816    return true;
817
818  // cv-qualifier:
819  case tok::kw_const:
820    isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
821                               getLang())*2;
822    break;
823  case tok::kw_volatile:
824    isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
825                               getLang())*2;
826    break;
827  case tok::kw_restrict:
828    isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
829                               getLang())*2;
830    break;
831
832  // GNU typeof support.
833  case tok::kw_typeof:
834    ParseTypeofSpecifier(DS);
835    return true;
836
837  case tok::kw___cdecl:
838  case tok::kw___stdcall:
839  case tok::kw___fastcall:
840    return PP.getLangOptions().Microsoft;
841
842  default:
843    // Not a type-specifier; do nothing.
844    return false;
845  }
846
847  // If the specifier combination wasn't legal, issue a diagnostic.
848  if (isInvalid) {
849    assert(PrevSpec && "Method did not return previous specifier!");
850    // Pick between error or extwarn.
851    unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination
852                                     : diag::ext_duplicate_declspec;
853    Diag(Tok, DiagID) << PrevSpec;
854  }
855  DS.SetRangeEnd(Tok.getLocation());
856  ConsumeToken(); // whatever we parsed above.
857  return true;
858}
859
860/// ParseStructDeclaration - Parse a struct declaration without the terminating
861/// semicolon.
862///
863///       struct-declaration:
864///         specifier-qualifier-list struct-declarator-list
865/// [GNU]   __extension__ struct-declaration
866/// [GNU]   specifier-qualifier-list
867///       struct-declarator-list:
868///         struct-declarator
869///         struct-declarator-list ',' struct-declarator
870/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
871///       struct-declarator:
872///         declarator
873/// [GNU]   declarator attributes[opt]
874///         declarator[opt] ':' constant-expression
875/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
876///
877void Parser::
878ParseStructDeclaration(DeclSpec &DS,
879                       llvm::SmallVectorImpl<FieldDeclarator> &Fields) {
880  if (Tok.is(tok::kw___extension__)) {
881    // __extension__ silences extension warnings in the subexpression.
882    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
883    ConsumeToken();
884    return ParseStructDeclaration(DS, Fields);
885  }
886
887  // Parse the common specifier-qualifiers-list piece.
888  SourceLocation DSStart = Tok.getLocation();
889  ParseSpecifierQualifierList(DS);
890
891  // If there are no declarators, issue a warning.
892  if (Tok.is(tok::semi)) {
893    Diag(DSStart, diag::w_no_declarators);
894    return;
895  }
896
897  // Read struct-declarators until we find the semicolon.
898  Fields.push_back(FieldDeclarator(DS));
899  while (1) {
900    FieldDeclarator &DeclaratorInfo = Fields.back();
901
902    /// struct-declarator: declarator
903    /// struct-declarator: declarator[opt] ':' constant-expression
904    if (Tok.isNot(tok::colon))
905      ParseDeclarator(DeclaratorInfo.D);
906
907    if (Tok.is(tok::colon)) {
908      ConsumeToken();
909      OwningExprResult Res(ParseConstantExpression());
910      if (Res.isInvalid())
911        SkipUntil(tok::semi, true, true);
912      else
913        DeclaratorInfo.BitfieldSize = Res.release();
914    }
915
916    // If attributes exist after the declarator, parse them.
917    if (Tok.is(tok::kw___attribute))
918      DeclaratorInfo.D.AddAttributes(ParseAttributes());
919
920    // If we don't have a comma, it is either the end of the list (a ';')
921    // or an error, bail out.
922    if (Tok.isNot(tok::comma))
923      return;
924
925    // Consume the comma.
926    ConsumeToken();
927
928    // Parse the next declarator.
929    Fields.push_back(FieldDeclarator(DS));
930
931    // Attributes are only allowed on the second declarator.
932    if (Tok.is(tok::kw___attribute))
933      Fields.back().D.AddAttributes(ParseAttributes());
934  }
935}
936
937/// ParseStructUnionBody
938///       struct-contents:
939///         struct-declaration-list
940/// [EXT]   empty
941/// [GNU]   "struct-declaration-list" without terminatoring ';'
942///       struct-declaration-list:
943///         struct-declaration
944///         struct-declaration-list struct-declaration
945/// [OBC]   '@' 'defs' '(' class-name ')'
946///
947void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
948                                  unsigned TagType, DeclTy *TagDecl) {
949  SourceLocation LBraceLoc = ConsumeBrace();
950
951  // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
952  // C++.
953  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
954    Diag(Tok, diag::ext_empty_struct_union_enum)
955      << DeclSpec::getSpecifierName((DeclSpec::TST)TagType);
956
957  llvm::SmallVector<DeclTy*, 32> FieldDecls;
958  llvm::SmallVector<FieldDeclarator, 8> FieldDeclarators;
959
960  // While we still have something to read, read the declarations in the struct.
961  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
962    // Each iteration of this loop reads one struct-declaration.
963
964    // Check for extraneous top-level semicolon.
965    if (Tok.is(tok::semi)) {
966      Diag(Tok, diag::ext_extra_struct_semi);
967      ConsumeToken();
968      continue;
969    }
970
971    // Parse all the comma separated declarators.
972    DeclSpec DS;
973    FieldDeclarators.clear();
974    if (!Tok.is(tok::at)) {
975      ParseStructDeclaration(DS, FieldDeclarators);
976
977      // Convert them all to fields.
978      for (unsigned i = 0, e = FieldDeclarators.size(); i != e; ++i) {
979        FieldDeclarator &FD = FieldDeclarators[i];
980        // Install the declarator into the current TagDecl.
981        DeclTy *Field = Actions.ActOnField(CurScope, TagDecl,
982                                           DS.getSourceRange().getBegin(),
983                                           FD.D, FD.BitfieldSize);
984        FieldDecls.push_back(Field);
985      }
986    } else { // Handle @defs
987      ConsumeToken();
988      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
989        Diag(Tok, diag::err_unexpected_at);
990        SkipUntil(tok::semi, true, true);
991        continue;
992      }
993      ConsumeToken();
994      ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
995      if (!Tok.is(tok::identifier)) {
996        Diag(Tok, diag::err_expected_ident);
997        SkipUntil(tok::semi, true, true);
998        continue;
999      }
1000      llvm::SmallVector<DeclTy*, 16> Fields;
1001      Actions.ActOnDefs(CurScope, TagDecl, Tok.getLocation(),
1002                        Tok.getIdentifierInfo(), Fields);
1003      FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
1004      ConsumeToken();
1005      ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
1006    }
1007
1008    if (Tok.is(tok::semi)) {
1009      ConsumeToken();
1010    } else if (Tok.is(tok::r_brace)) {
1011      Diag(Tok, diag::ext_expected_semi_decl_list);
1012      break;
1013    } else {
1014      Diag(Tok, diag::err_expected_semi_decl_list);
1015      // Skip to end of block or statement
1016      SkipUntil(tok::r_brace, true, true);
1017    }
1018  }
1019
1020  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1021
1022  AttributeList *AttrList = 0;
1023  // If attributes exist after struct contents, parse them.
1024  if (Tok.is(tok::kw___attribute))
1025    AttrList = ParseAttributes();
1026
1027  Actions.ActOnFields(CurScope,
1028                      RecordLoc,TagDecl,&FieldDecls[0],FieldDecls.size(),
1029                      LBraceLoc, RBraceLoc,
1030                      AttrList);
1031}
1032
1033
1034/// ParseEnumSpecifier
1035///       enum-specifier: [C99 6.7.2.2]
1036///         'enum' identifier[opt] '{' enumerator-list '}'
1037///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
1038/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
1039///                                                 '}' attributes[opt]
1040///         'enum' identifier
1041/// [GNU]   'enum' attributes[opt] identifier
1042///
1043/// [C++] elaborated-type-specifier:
1044/// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
1045///
1046void Parser::ParseEnumSpecifier(DeclSpec &DS) {
1047  assert(Tok.is(tok::kw_enum) && "Not an enum specifier");
1048  SourceLocation StartLoc = ConsumeToken();
1049
1050  // Parse the tag portion of this.
1051
1052  AttributeList *Attr = 0;
1053  // If attributes exist after tag, parse them.
1054  if (Tok.is(tok::kw___attribute))
1055    Attr = ParseAttributes();
1056
1057  CXXScopeSpec SS;
1058  if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS)) {
1059    if (Tok.isNot(tok::identifier)) {
1060      Diag(Tok, diag::err_expected_ident);
1061      if (Tok.isNot(tok::l_brace)) {
1062        // Has no name and is not a definition.
1063        // Skip the rest of this declarator, up until the comma or semicolon.
1064        SkipUntil(tok::comma, true);
1065        return;
1066      }
1067    }
1068  }
1069
1070  // Must have either 'enum name' or 'enum {...}'.
1071  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) {
1072    Diag(Tok, diag::err_expected_ident_lbrace);
1073
1074    // Skip the rest of this declarator, up until the comma or semicolon.
1075    SkipUntil(tok::comma, true);
1076    return;
1077  }
1078
1079  // If an identifier is present, consume and remember it.
1080  IdentifierInfo *Name = 0;
1081  SourceLocation NameLoc;
1082  if (Tok.is(tok::identifier)) {
1083    Name = Tok.getIdentifierInfo();
1084    NameLoc = ConsumeToken();
1085  }
1086
1087  // There are three options here.  If we have 'enum foo;', then this is a
1088  // forward declaration.  If we have 'enum foo {...' then this is a
1089  // definition. Otherwise we have something like 'enum foo xyz', a reference.
1090  //
1091  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
1092  // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
1093  // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
1094  //
1095  Action::TagKind TK;
1096  if (Tok.is(tok::l_brace))
1097    TK = Action::TK_Definition;
1098  else if (Tok.is(tok::semi))
1099    TK = Action::TK_Declaration;
1100  else
1101    TK = Action::TK_Reference;
1102  DeclTy *TagDecl = Actions.ActOnTag(CurScope, DeclSpec::TST_enum, TK, StartLoc,
1103                                     SS, Name, NameLoc, Attr,
1104                                     Action::MultiTemplateParamsArg(Actions));
1105
1106  if (Tok.is(tok::l_brace))
1107    ParseEnumBody(StartLoc, TagDecl);
1108
1109  // TODO: semantic analysis on the declspec for enums.
1110  const char *PrevSpec = 0;
1111  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, PrevSpec, TagDecl))
1112    Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
1113}
1114
1115/// ParseEnumBody - Parse a {} enclosed enumerator-list.
1116///       enumerator-list:
1117///         enumerator
1118///         enumerator-list ',' enumerator
1119///       enumerator:
1120///         enumeration-constant
1121///         enumeration-constant '=' constant-expression
1122///       enumeration-constant:
1123///         identifier
1124///
1125void Parser::ParseEnumBody(SourceLocation StartLoc, DeclTy *EnumDecl) {
1126  // Enter the scope of the enum body and start the definition.
1127  ParseScope EnumScope(this, Scope::DeclScope);
1128  Actions.ActOnEnumStartDefinition(CurScope, EnumDecl);
1129
1130  SourceLocation LBraceLoc = ConsumeBrace();
1131
1132  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
1133  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1134    Diag(Tok, diag::ext_empty_struct_union_enum) << "enum";
1135
1136  llvm::SmallVector<DeclTy*, 32> EnumConstantDecls;
1137
1138  DeclTy *LastEnumConstDecl = 0;
1139
1140  // Parse the enumerator-list.
1141  while (Tok.is(tok::identifier)) {
1142    IdentifierInfo *Ident = Tok.getIdentifierInfo();
1143    SourceLocation IdentLoc = ConsumeToken();
1144
1145    SourceLocation EqualLoc;
1146    OwningExprResult AssignedVal(Actions);
1147    if (Tok.is(tok::equal)) {
1148      EqualLoc = ConsumeToken();
1149      AssignedVal = ParseConstantExpression();
1150      if (AssignedVal.isInvalid())
1151        SkipUntil(tok::comma, tok::r_brace, true, true);
1152    }
1153
1154    // Install the enumerator constant into EnumDecl.
1155    DeclTy *EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl,
1156                                                      LastEnumConstDecl,
1157                                                      IdentLoc, Ident,
1158                                                      EqualLoc,
1159                                                      AssignedVal.release());
1160    EnumConstantDecls.push_back(EnumConstDecl);
1161    LastEnumConstDecl = EnumConstDecl;
1162
1163    if (Tok.isNot(tok::comma))
1164      break;
1165    SourceLocation CommaLoc = ConsumeToken();
1166
1167    if (Tok.isNot(tok::identifier) && !getLang().C99)
1168      Diag(CommaLoc, diag::ext_c99_enumerator_list_comma);
1169  }
1170
1171  // Eat the }.
1172  MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1173
1174  Actions.ActOnEnumBody(StartLoc, EnumDecl, &EnumConstantDecls[0],
1175                        EnumConstantDecls.size());
1176
1177  DeclTy *AttrList = 0;
1178  // If attributes exist after the identifier list, parse them.
1179  if (Tok.is(tok::kw___attribute))
1180    AttrList = ParseAttributes(); // FIXME: where do they do?
1181}
1182
1183/// isTypeSpecifierQualifier - Return true if the current token could be the
1184/// start of a type-qualifier-list.
1185bool Parser::isTypeQualifier() const {
1186  switch (Tok.getKind()) {
1187  default: return false;
1188    // type-qualifier
1189  case tok::kw_const:
1190  case tok::kw_volatile:
1191  case tok::kw_restrict:
1192    return true;
1193  }
1194}
1195
1196/// isTypeSpecifierQualifier - Return true if the current token could be the
1197/// start of a specifier-qualifier-list.
1198bool Parser::isTypeSpecifierQualifier() {
1199  switch (Tok.getKind()) {
1200  default: return false;
1201
1202  case tok::identifier:   // foo::bar
1203    // Annotate typenames and C++ scope specifiers.  If we get one, just
1204    // recurse to handle whatever we get.
1205    if (TryAnnotateTypeOrScopeToken())
1206      return isTypeSpecifierQualifier();
1207    // Otherwise, not a type specifier.
1208    return false;
1209  case tok::coloncolon:   // ::foo::bar
1210    if (NextToken().is(tok::kw_new) ||    // ::new
1211        NextToken().is(tok::kw_delete))   // ::delete
1212      return false;
1213
1214    // Annotate typenames and C++ scope specifiers.  If we get one, just
1215    // recurse to handle whatever we get.
1216    if (TryAnnotateTypeOrScopeToken())
1217      return isTypeSpecifierQualifier();
1218    // Otherwise, not a type specifier.
1219    return false;
1220
1221    // GNU attributes support.
1222  case tok::kw___attribute:
1223    // GNU typeof support.
1224  case tok::kw_typeof:
1225
1226    // type-specifiers
1227  case tok::kw_short:
1228  case tok::kw_long:
1229  case tok::kw_signed:
1230  case tok::kw_unsigned:
1231  case tok::kw__Complex:
1232  case tok::kw__Imaginary:
1233  case tok::kw_void:
1234  case tok::kw_char:
1235  case tok::kw_wchar_t:
1236  case tok::kw_int:
1237  case tok::kw_float:
1238  case tok::kw_double:
1239  case tok::kw_bool:
1240  case tok::kw__Bool:
1241  case tok::kw__Decimal32:
1242  case tok::kw__Decimal64:
1243  case tok::kw__Decimal128:
1244
1245    // struct-or-union-specifier (C99) or class-specifier (C++)
1246  case tok::kw_class:
1247  case tok::kw_struct:
1248  case tok::kw_union:
1249    // enum-specifier
1250  case tok::kw_enum:
1251
1252    // type-qualifier
1253  case tok::kw_const:
1254  case tok::kw_volatile:
1255  case tok::kw_restrict:
1256
1257    // typedef-name
1258  case tok::annot_typename:
1259    return true;
1260
1261    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
1262  case tok::less:
1263    return getLang().ObjC1;
1264
1265  case tok::kw___cdecl:
1266  case tok::kw___stdcall:
1267  case tok::kw___fastcall:
1268    return PP.getLangOptions().Microsoft;
1269  }
1270}
1271
1272/// isDeclarationSpecifier() - Return true if the current token is part of a
1273/// declaration specifier.
1274bool Parser::isDeclarationSpecifier() {
1275  switch (Tok.getKind()) {
1276  default: return false;
1277
1278  case tok::identifier:   // foo::bar
1279    // Annotate typenames and C++ scope specifiers.  If we get one, just
1280    // recurse to handle whatever we get.
1281    if (TryAnnotateTypeOrScopeToken())
1282      return isDeclarationSpecifier();
1283    // Otherwise, not a declaration specifier.
1284    return false;
1285  case tok::coloncolon:   // ::foo::bar
1286    if (NextToken().is(tok::kw_new) ||    // ::new
1287        NextToken().is(tok::kw_delete))   // ::delete
1288      return false;
1289
1290    // Annotate typenames and C++ scope specifiers.  If we get one, just
1291    // recurse to handle whatever we get.
1292    if (TryAnnotateTypeOrScopeToken())
1293      return isDeclarationSpecifier();
1294    // Otherwise, not a declaration specifier.
1295    return false;
1296
1297    // storage-class-specifier
1298  case tok::kw_typedef:
1299  case tok::kw_extern:
1300  case tok::kw___private_extern__:
1301  case tok::kw_static:
1302  case tok::kw_auto:
1303  case tok::kw_register:
1304  case tok::kw___thread:
1305
1306    // type-specifiers
1307  case tok::kw_short:
1308  case tok::kw_long:
1309  case tok::kw_signed:
1310  case tok::kw_unsigned:
1311  case tok::kw__Complex:
1312  case tok::kw__Imaginary:
1313  case tok::kw_void:
1314  case tok::kw_char:
1315  case tok::kw_wchar_t:
1316  case tok::kw_int:
1317  case tok::kw_float:
1318  case tok::kw_double:
1319  case tok::kw_bool:
1320  case tok::kw__Bool:
1321  case tok::kw__Decimal32:
1322  case tok::kw__Decimal64:
1323  case tok::kw__Decimal128:
1324
1325    // struct-or-union-specifier (C99) or class-specifier (C++)
1326  case tok::kw_class:
1327  case tok::kw_struct:
1328  case tok::kw_union:
1329    // enum-specifier
1330  case tok::kw_enum:
1331
1332    // type-qualifier
1333  case tok::kw_const:
1334  case tok::kw_volatile:
1335  case tok::kw_restrict:
1336
1337    // function-specifier
1338  case tok::kw_inline:
1339  case tok::kw_virtual:
1340  case tok::kw_explicit:
1341
1342    // typedef-name
1343  case tok::annot_typename:
1344
1345    // GNU typeof support.
1346  case tok::kw_typeof:
1347
1348    // GNU attributes.
1349  case tok::kw___attribute:
1350    return true;
1351
1352    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
1353  case tok::less:
1354    return getLang().ObjC1;
1355
1356  case tok::kw___cdecl:
1357  case tok::kw___stdcall:
1358  case tok::kw___fastcall:
1359    return PP.getLangOptions().Microsoft;
1360  }
1361}
1362
1363
1364/// ParseTypeQualifierListOpt
1365///       type-qualifier-list: [C99 6.7.5]
1366///         type-qualifier
1367/// [GNU]   attributes                        [ only if AttributesAllowed=true ]
1368///         type-qualifier-list type-qualifier
1369/// [GNU]   type-qualifier-list attributes    [ only if AttributesAllowed=true ]
1370///
1371void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, bool AttributesAllowed) {
1372  while (1) {
1373    int isInvalid = false;
1374    const char *PrevSpec = 0;
1375    SourceLocation Loc = Tok.getLocation();
1376
1377    switch (Tok.getKind()) {
1378    case tok::kw_const:
1379      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
1380                                 getLang())*2;
1381      break;
1382    case tok::kw_volatile:
1383      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
1384                                 getLang())*2;
1385      break;
1386    case tok::kw_restrict:
1387      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1388                                 getLang())*2;
1389      break;
1390    case tok::kw___ptr64:
1391    case tok::kw___cdecl:
1392    case tok::kw___stdcall:
1393    case tok::kw___fastcall:
1394      if (!PP.getLangOptions().Microsoft)
1395        goto DoneWithTypeQuals;
1396      // Just ignore it.
1397      break;
1398    case tok::kw___attribute:
1399      if (AttributesAllowed) {
1400        DS.AddAttributes(ParseAttributes());
1401        continue; // do *not* consume the next token!
1402      }
1403      // otherwise, FALL THROUGH!
1404    default:
1405      DoneWithTypeQuals:
1406      // If this is not a type-qualifier token, we're done reading type
1407      // qualifiers.  First verify that DeclSpec's are consistent.
1408      DS.Finish(Diags, PP.getSourceManager(), getLang());
1409      return;
1410    }
1411
1412    // If the specifier combination wasn't legal, issue a diagnostic.
1413    if (isInvalid) {
1414      assert(PrevSpec && "Method did not return previous specifier!");
1415      // Pick between error or extwarn.
1416      unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination
1417                                      : diag::ext_duplicate_declspec;
1418      Diag(Tok, DiagID) << PrevSpec;
1419    }
1420    ConsumeToken();
1421  }
1422}
1423
1424
1425/// ParseDeclarator - Parse and verify a newly-initialized declarator.
1426///
1427void Parser::ParseDeclarator(Declarator &D) {
1428  /// This implements the 'declarator' production in the C grammar, then checks
1429  /// for well-formedness and issues diagnostics.
1430  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
1431}
1432
1433/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
1434/// is parsed by the function passed to it. Pass null, and the direct-declarator
1435/// isn't parsed at all, making this function effectively parse the C++
1436/// ptr-operator production.
1437///
1438///       declarator: [C99 6.7.5]
1439///         pointer[opt] direct-declarator
1440/// [C++]   '&' declarator [C++ 8p4, dcl.decl]
1441/// [GNU]   '&' restrict[opt] attributes[opt] declarator
1442///
1443///       pointer: [C99 6.7.5]
1444///         '*' type-qualifier-list[opt]
1445///         '*' type-qualifier-list[opt] pointer
1446///
1447///       ptr-operator:
1448///         '*' cv-qualifier-seq[opt]
1449///         '&'
1450/// [GNU]   '&' restrict[opt] attributes[opt]
1451///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] [TODO]
1452void Parser::ParseDeclaratorInternal(Declarator &D,
1453                                     DirectDeclParseFunction DirectDeclParser) {
1454  tok::TokenKind Kind = Tok.getKind();
1455
1456  // Not a pointer, C++ reference, or block.
1457  if (Kind != tok::star && (Kind != tok::amp || !getLang().CPlusPlus) &&
1458      (Kind != tok::caret || !getLang().Blocks)) {
1459    if (DirectDeclParser)
1460      (this->*DirectDeclParser)(D);
1461    return;
1462  }
1463
1464  // Otherwise, '*' -> pointer, '^' -> block, '&' -> reference.
1465  SourceLocation Loc = ConsumeToken();  // Eat the * or &.
1466
1467  if (Kind == tok::star || (Kind == tok::caret && getLang().Blocks)) {
1468    // Is a pointer.
1469    DeclSpec DS;
1470
1471    ParseTypeQualifierListOpt(DS);
1472
1473    // Recursively parse the declarator.
1474    ParseDeclaratorInternal(D, DirectDeclParser);
1475    if (Kind == tok::star)
1476      // Remember that we parsed a pointer type, and remember the type-quals.
1477      D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
1478                                                DS.TakeAttributes()));
1479    else
1480      // Remember that we parsed a Block type, and remember the type-quals.
1481      D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
1482                                                     Loc));
1483  } else {
1484    // Is a reference
1485    DeclSpec DS;
1486
1487    // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
1488    // cv-qualifiers are introduced through the use of a typedef or of a
1489    // template type argument, in which case the cv-qualifiers are ignored.
1490    //
1491    // [GNU] Retricted references are allowed.
1492    // [GNU] Attributes on references are allowed.
1493    ParseTypeQualifierListOpt(DS);
1494
1495    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
1496      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1497        Diag(DS.getConstSpecLoc(),
1498             diag::err_invalid_reference_qualifier_application) << "const";
1499      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
1500        Diag(DS.getVolatileSpecLoc(),
1501             diag::err_invalid_reference_qualifier_application) << "volatile";
1502    }
1503
1504    // Recursively parse the declarator.
1505    ParseDeclaratorInternal(D, DirectDeclParser);
1506
1507    if (D.getNumTypeObjects() > 0) {
1508      // C++ [dcl.ref]p4: There shall be no references to references.
1509      DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
1510      if (InnerChunk.Kind == DeclaratorChunk::Reference) {
1511        if (const IdentifierInfo *II = D.getIdentifier())
1512          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
1513           << II;
1514        else
1515          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
1516            << "type name";
1517
1518        // Once we've complained about the reference-to-reference, we
1519        // can go ahead and build the (technically ill-formed)
1520        // declarator: reference collapsing will take care of it.
1521      }
1522    }
1523
1524    // Remember that we parsed a reference type. It doesn't have type-quals.
1525    D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
1526                                                DS.TakeAttributes()));
1527  }
1528}
1529
1530/// ParseDirectDeclarator
1531///       direct-declarator: [C99 6.7.5]
1532/// [C99]   identifier
1533///         '(' declarator ')'
1534/// [GNU]   '(' attributes declarator ')'
1535/// [C90]   direct-declarator '[' constant-expression[opt] ']'
1536/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1537/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1538/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1539/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
1540///         direct-declarator '(' parameter-type-list ')'
1541///         direct-declarator '(' identifier-list[opt] ')'
1542/// [GNU]   direct-declarator '(' parameter-forward-declarations
1543///                    parameter-type-list[opt] ')'
1544/// [C++]   direct-declarator '(' parameter-declaration-clause ')'
1545///                    cv-qualifier-seq[opt] exception-specification[opt]
1546/// [C++]   declarator-id
1547///
1548///       declarator-id: [C++ 8]
1549///         id-expression
1550///         '::'[opt] nested-name-specifier[opt] type-name
1551///
1552///       id-expression: [C++ 5.1]
1553///         unqualified-id
1554///         qualified-id            [TODO]
1555///
1556///       unqualified-id: [C++ 5.1]
1557///         identifier
1558///         operator-function-id
1559///         conversion-function-id  [TODO]
1560///          '~' class-name
1561///         template-id             [TODO]
1562///
1563void Parser::ParseDirectDeclarator(Declarator &D) {
1564  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
1565
1566  if (getLang().CPlusPlus) {
1567    if (D.mayHaveIdentifier()) {
1568      bool afterCXXScope = ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec());
1569      if (afterCXXScope) {
1570        // Change the declaration context for name lookup, until this function
1571        // is exited (and the declarator has been parsed).
1572        DeclScopeObj.EnterDeclaratorScope();
1573      }
1574
1575      if (Tok.is(tok::identifier)) {
1576        assert(Tok.getIdentifierInfo() && "Not an identifier?");
1577
1578        // If this identifier is followed by a '<', we may have a template-id.
1579        DeclTy *Template;
1580        if (NextToken().is(tok::less) &&
1581            (Template = Actions.isTemplateName(*Tok.getIdentifierInfo(),
1582                                               CurScope))) {
1583          IdentifierInfo *II = Tok.getIdentifierInfo();
1584          AnnotateTemplateIdToken(Template, 0);
1585          // FIXME: Set the declarator to a template-id. How? I don't
1586          // know... for now, just use the identifier.
1587          D.SetIdentifier(II, Tok.getLocation());
1588        }
1589        // If this identifier is the name of the current class, it's a
1590        // constructor name.
1591        else if (Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope))
1592          D.setConstructor(Actions.isTypeName(*Tok.getIdentifierInfo(),
1593                                              CurScope),
1594                           Tok.getLocation());
1595        // This is a normal identifier.
1596        else
1597          D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1598        ConsumeToken();
1599        goto PastIdentifier;
1600      } else if (Tok.is(tok::kw_operator)) {
1601        SourceLocation OperatorLoc = Tok.getLocation();
1602
1603        // First try the name of an overloaded operator
1604        if (OverloadedOperatorKind Op = TryParseOperatorFunctionId()) {
1605          D.setOverloadedOperator(Op, OperatorLoc);
1606        } else {
1607          // This must be a conversion function (C++ [class.conv.fct]).
1608          if (TypeTy *ConvType = ParseConversionFunctionId())
1609            D.setConversionFunction(ConvType, OperatorLoc);
1610          else
1611            D.SetIdentifier(0, Tok.getLocation());
1612        }
1613        goto PastIdentifier;
1614      } else if (Tok.is(tok::tilde)) {
1615        // This should be a C++ destructor.
1616        SourceLocation TildeLoc = ConsumeToken();
1617        if (Tok.is(tok::identifier)) {
1618          if (TypeTy *Type = ParseClassName())
1619            D.setDestructor(Type, TildeLoc);
1620          else
1621            D.SetIdentifier(0, TildeLoc);
1622        } else {
1623          Diag(Tok, diag::err_expected_class_name);
1624          D.SetIdentifier(0, TildeLoc);
1625        }
1626        goto PastIdentifier;
1627      }
1628
1629      // If we reached this point, token is not identifier and not '~'.
1630
1631      if (afterCXXScope) {
1632        Diag(Tok, diag::err_expected_unqualified_id);
1633        D.SetIdentifier(0, Tok.getLocation());
1634        D.setInvalidType(true);
1635        goto PastIdentifier;
1636      }
1637    }
1638  }
1639
1640  // If we reached this point, we are either in C/ObjC or the token didn't
1641  // satisfy any of the C++-specific checks.
1642
1643  if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
1644    assert(!getLang().CPlusPlus &&
1645           "There's a C++-specific check for tok::identifier above");
1646    assert(Tok.getIdentifierInfo() && "Not an identifier?");
1647    D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1648    ConsumeToken();
1649  } else if (Tok.is(tok::l_paren)) {
1650    // direct-declarator: '(' declarator ')'
1651    // direct-declarator: '(' attributes declarator ')'
1652    // Example: 'char (*X)'   or 'int (*XX)(void)'
1653    ParseParenDeclarator(D);
1654  } else if (D.mayOmitIdentifier()) {
1655    // This could be something simple like "int" (in which case the declarator
1656    // portion is empty), if an abstract-declarator is allowed.
1657    D.SetIdentifier(0, Tok.getLocation());
1658  } else {
1659    if (getLang().CPlusPlus)
1660      Diag(Tok, diag::err_expected_unqualified_id);
1661    else
1662      Diag(Tok, diag::err_expected_ident_lparen);
1663    D.SetIdentifier(0, Tok.getLocation());
1664    D.setInvalidType(true);
1665  }
1666
1667 PastIdentifier:
1668  assert(D.isPastIdentifier() &&
1669         "Haven't past the location of the identifier yet?");
1670
1671  while (1) {
1672    if (Tok.is(tok::l_paren)) {
1673      // The paren may be part of a C++ direct initializer, eg. "int x(1);".
1674      // In such a case, check if we actually have a function declarator; if it
1675      // is not, the declarator has been fully parsed.
1676      if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
1677        // When not in file scope, warn for ambiguous function declarators, just
1678        // in case the author intended it as a variable definition.
1679        bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
1680        if (!isCXXFunctionDeclarator(warnIfAmbiguous))
1681          break;
1682      }
1683      ParseFunctionDeclarator(ConsumeParen(), D);
1684    } else if (Tok.is(tok::l_square)) {
1685      ParseBracketDeclarator(D);
1686    } else {
1687      break;
1688    }
1689  }
1690}
1691
1692/// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
1693/// only called before the identifier, so these are most likely just grouping
1694/// parens for precedence.  If we find that these are actually function
1695/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
1696///
1697///       direct-declarator:
1698///         '(' declarator ')'
1699/// [GNU]   '(' attributes declarator ')'
1700///         direct-declarator '(' parameter-type-list ')'
1701///         direct-declarator '(' identifier-list[opt] ')'
1702/// [GNU]   direct-declarator '(' parameter-forward-declarations
1703///                    parameter-type-list[opt] ')'
1704///
1705void Parser::ParseParenDeclarator(Declarator &D) {
1706  SourceLocation StartLoc = ConsumeParen();
1707  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
1708
1709  // Eat any attributes before we look at whether this is a grouping or function
1710  // declarator paren.  If this is a grouping paren, the attribute applies to
1711  // the type being built up, for example:
1712  //     int (__attribute__(()) *x)(long y)
1713  // If this ends up not being a grouping paren, the attribute applies to the
1714  // first argument, for example:
1715  //     int (__attribute__(()) int x)
1716  // In either case, we need to eat any attributes to be able to determine what
1717  // sort of paren this is.
1718  //
1719  AttributeList *AttrList = 0;
1720  bool RequiresArg = false;
1721  if (Tok.is(tok::kw___attribute)) {
1722    AttrList = ParseAttributes();
1723
1724    // We require that the argument list (if this is a non-grouping paren) be
1725    // present even if the attribute list was empty.
1726    RequiresArg = true;
1727  }
1728  // Eat any Microsoft extensions.
1729  if ((Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
1730      (Tok.is(tok::kw___fastcall))) && PP.getLangOptions().Microsoft)
1731    ConsumeToken();
1732
1733  // If we haven't past the identifier yet (or where the identifier would be
1734  // stored, if this is an abstract declarator), then this is probably just
1735  // grouping parens. However, if this could be an abstract-declarator, then
1736  // this could also be the start of function arguments (consider 'void()').
1737  bool isGrouping;
1738
1739  if (!D.mayOmitIdentifier()) {
1740    // If this can't be an abstract-declarator, this *must* be a grouping
1741    // paren, because we haven't seen the identifier yet.
1742    isGrouping = true;
1743  } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
1744             (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
1745             isDeclarationSpecifier()) {       // 'int(int)' is a function.
1746    // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
1747    // considered to be a type, not a K&R identifier-list.
1748    isGrouping = false;
1749  } else {
1750    // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
1751    isGrouping = true;
1752  }
1753
1754  // If this is a grouping paren, handle:
1755  // direct-declarator: '(' declarator ')'
1756  // direct-declarator: '(' attributes declarator ')'
1757  if (isGrouping) {
1758    bool hadGroupingParens = D.hasGroupingParens();
1759    D.setGroupingParens(true);
1760    if (AttrList)
1761      D.AddAttributes(AttrList);
1762
1763    ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
1764    // Match the ')'.
1765    MatchRHSPunctuation(tok::r_paren, StartLoc);
1766
1767    D.setGroupingParens(hadGroupingParens);
1768    return;
1769  }
1770
1771  // Okay, if this wasn't a grouping paren, it must be the start of a function
1772  // argument list.  Recognize that this declarator will never have an
1773  // identifier (and remember where it would have been), then call into
1774  // ParseFunctionDeclarator to handle of argument list.
1775  D.SetIdentifier(0, Tok.getLocation());
1776
1777  ParseFunctionDeclarator(StartLoc, D, AttrList, RequiresArg);
1778}
1779
1780/// ParseFunctionDeclarator - We are after the identifier and have parsed the
1781/// declarator D up to a paren, which indicates that we are parsing function
1782/// arguments.
1783///
1784/// If AttrList is non-null, then the caller parsed those arguments immediately
1785/// after the open paren - they should be considered to be the first argument of
1786/// a parameter.  If RequiresArg is true, then the first argument of the
1787/// function is required to be present and required to not be an identifier
1788/// list.
1789///
1790/// This method also handles this portion of the grammar:
1791///       parameter-type-list: [C99 6.7.5]
1792///         parameter-list
1793///         parameter-list ',' '...'
1794///
1795///       parameter-list: [C99 6.7.5]
1796///         parameter-declaration
1797///         parameter-list ',' parameter-declaration
1798///
1799///       parameter-declaration: [C99 6.7.5]
1800///         declaration-specifiers declarator
1801/// [C++]   declaration-specifiers declarator '=' assignment-expression
1802/// [GNU]   declaration-specifiers declarator attributes
1803///         declaration-specifiers abstract-declarator[opt]
1804/// [C++]   declaration-specifiers abstract-declarator[opt]
1805///           '=' assignment-expression
1806/// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
1807///
1808/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]"
1809/// and "exception-specification[opt]"(TODO).
1810///
1811void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
1812                                     AttributeList *AttrList,
1813                                     bool RequiresArg) {
1814  // lparen is already consumed!
1815  assert(D.isPastIdentifier() && "Should not call before identifier!");
1816
1817  // This parameter list may be empty.
1818  if (Tok.is(tok::r_paren)) {
1819    if (RequiresArg) {
1820      Diag(Tok, diag::err_argument_required_after_attribute);
1821      delete AttrList;
1822    }
1823
1824    ConsumeParen();  // Eat the closing ')'.
1825
1826    // cv-qualifier-seq[opt].
1827    DeclSpec DS;
1828    if (getLang().CPlusPlus) {
1829      ParseTypeQualifierListOpt(DS, false /*no attributes*/);
1830
1831      // Parse exception-specification[opt].
1832      if (Tok.is(tok::kw_throw))
1833        ParseExceptionSpecification();
1834    }
1835
1836    // Remember that we parsed a function type, and remember the attributes.
1837    // int() -> no prototype, no '...'.
1838    D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus,
1839                                               /*variadic*/ false,
1840                                               /*arglist*/ 0, 0,
1841                                               DS.getTypeQualifiers(),
1842                                               LParenLoc));
1843    return;
1844  }
1845
1846  // Alternatively, this parameter list may be an identifier list form for a
1847  // K&R-style function:  void foo(a,b,c)
1848  if (!getLang().CPlusPlus && Tok.is(tok::identifier) &&
1849      // K&R identifier lists can't have typedefs as identifiers, per
1850      // C99 6.7.5.3p11.
1851      !Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope)) {
1852    if (RequiresArg) {
1853      Diag(Tok, diag::err_argument_required_after_attribute);
1854      delete AttrList;
1855    }
1856
1857    // Identifier list.  Note that '(' identifier-list ')' is only allowed for
1858    // normal declarators, not for abstract-declarators.
1859    return ParseFunctionDeclaratorIdentifierList(LParenLoc, D);
1860  }
1861
1862  // Finally, a normal, non-empty parameter type list.
1863
1864  // Build up an array of information about the parsed arguments.
1865  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1866
1867  // Enter function-declaration scope, limiting any declarators to the
1868  // function prototype scope, including parameter declarators.
1869  ParseScope PrototypeScope(this, Scope::FnScope|Scope::DeclScope);
1870
1871  bool IsVariadic = false;
1872  while (1) {
1873    if (Tok.is(tok::ellipsis)) {
1874      IsVariadic = true;
1875
1876      // Check to see if this is "void(...)" which is not allowed.
1877      if (!getLang().CPlusPlus && ParamInfo.empty()) {
1878        // Otherwise, parse parameter type list.  If it starts with an
1879        // ellipsis,  diagnose the malformed function.
1880        Diag(Tok, diag::err_ellipsis_first_arg);
1881        IsVariadic = false;       // Treat this like 'void()'.
1882      }
1883
1884      ConsumeToken();     // Consume the ellipsis.
1885      break;
1886    }
1887
1888    SourceLocation DSStart = Tok.getLocation();
1889
1890    // Parse the declaration-specifiers.
1891    DeclSpec DS;
1892
1893    // If the caller parsed attributes for the first argument, add them now.
1894    if (AttrList) {
1895      DS.AddAttributes(AttrList);
1896      AttrList = 0;  // Only apply the attributes to the first parameter.
1897    }
1898    ParseDeclarationSpecifiers(DS);
1899
1900    // Parse the declarator.  This is "PrototypeContext", because we must
1901    // accept either 'declarator' or 'abstract-declarator' here.
1902    Declarator ParmDecl(DS, Declarator::PrototypeContext);
1903    ParseDeclarator(ParmDecl);
1904
1905    // Parse GNU attributes, if present.
1906    if (Tok.is(tok::kw___attribute))
1907      ParmDecl.AddAttributes(ParseAttributes());
1908
1909    // Remember this parsed parameter in ParamInfo.
1910    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1911
1912    // DefArgToks is used when the parsing of default arguments needs
1913    // to be delayed.
1914    CachedTokens *DefArgToks = 0;
1915
1916    // If no parameter was specified, verify that *something* was specified,
1917    // otherwise we have a missing type and identifier.
1918    if (DS.getParsedSpecifiers() == DeclSpec::PQ_None &&
1919        ParmDecl.getIdentifier() == 0 && ParmDecl.getNumTypeObjects() == 0) {
1920      // Completely missing, emit error.
1921      Diag(DSStart, diag::err_missing_param);
1922    } else {
1923      // Otherwise, we have something.  Add it and let semantic analysis try
1924      // to grok it and add the result to the ParamInfo we are building.
1925
1926      // Inform the actions module about the parameter declarator, so it gets
1927      // added to the current scope.
1928      DeclTy *Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl);
1929
1930      // Parse the default argument, if any. We parse the default
1931      // arguments in all dialects; the semantic analysis in
1932      // ActOnParamDefaultArgument will reject the default argument in
1933      // C.
1934      if (Tok.is(tok::equal)) {
1935        SourceLocation EqualLoc = Tok.getLocation();
1936
1937        // Parse the default argument
1938        if (D.getContext() == Declarator::MemberContext) {
1939          // If we're inside a class definition, cache the tokens
1940          // corresponding to the default argument. We'll actually parse
1941          // them when we see the end of the class definition.
1942          // FIXME: Templates will require something similar.
1943          // FIXME: Can we use a smart pointer for Toks?
1944          DefArgToks = new CachedTokens;
1945
1946          if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
1947                                    tok::semi, false)) {
1948            delete DefArgToks;
1949            DefArgToks = 0;
1950            Actions.ActOnParamDefaultArgumentError(Param);
1951          } else
1952            Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc);
1953        } else {
1954          // Consume the '='.
1955          ConsumeToken();
1956
1957          OwningExprResult DefArgResult(ParseAssignmentExpression());
1958          if (DefArgResult.isInvalid()) {
1959            Actions.ActOnParamDefaultArgumentError(Param);
1960            SkipUntil(tok::comma, tok::r_paren, true, true);
1961          } else {
1962            // Inform the actions module about the default argument
1963            Actions.ActOnParamDefaultArgument(Param, EqualLoc,
1964                                              DefArgResult.release());
1965          }
1966        }
1967      }
1968
1969      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1970                                          ParmDecl.getIdentifierLoc(), Param,
1971                                          DefArgToks));
1972    }
1973
1974    // If the next token is a comma, consume it and keep reading arguments.
1975    if (Tok.isNot(tok::comma)) break;
1976
1977    // Consume the comma.
1978    ConsumeToken();
1979  }
1980
1981  // Leave prototype scope.
1982  PrototypeScope.Exit();
1983
1984  // If we have the closing ')', eat it.
1985  MatchRHSPunctuation(tok::r_paren, LParenLoc);
1986
1987  DeclSpec DS;
1988  if (getLang().CPlusPlus) {
1989    // Parse cv-qualifier-seq[opt].
1990    ParseTypeQualifierListOpt(DS, false /*no attributes*/);
1991
1992    // Parse exception-specification[opt].
1993    if (Tok.is(tok::kw_throw))
1994      ParseExceptionSpecification();
1995  }
1996
1997  // Remember that we parsed a function type, and remember the attributes.
1998  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
1999                                             &ParamInfo[0], ParamInfo.size(),
2000                                             DS.getTypeQualifiers(),
2001                                             LParenLoc));
2002}
2003
2004/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
2005/// we found a K&R-style identifier list instead of a type argument list.  The
2006/// current token is known to be the first identifier in the list.
2007///
2008///       identifier-list: [C99 6.7.5]
2009///         identifier
2010///         identifier-list ',' identifier
2011///
2012void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
2013                                                   Declarator &D) {
2014  // Build up an array of information about the parsed arguments.
2015  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
2016  llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
2017
2018  // If there was no identifier specified for the declarator, either we are in
2019  // an abstract-declarator, or we are in a parameter declarator which was found
2020  // to be abstract.  In abstract-declarators, identifier lists are not valid:
2021  // diagnose this.
2022  if (!D.getIdentifier())
2023    Diag(Tok, diag::ext_ident_list_in_param);
2024
2025  // Tok is known to be the first identifier in the list.  Remember this
2026  // identifier in ParamInfo.
2027  ParamsSoFar.insert(Tok.getIdentifierInfo());
2028  ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
2029                                                 Tok.getLocation(), 0));
2030
2031  ConsumeToken();  // eat the first identifier.
2032
2033  while (Tok.is(tok::comma)) {
2034    // Eat the comma.
2035    ConsumeToken();
2036
2037    // If this isn't an identifier, report the error and skip until ')'.
2038    if (Tok.isNot(tok::identifier)) {
2039      Diag(Tok, diag::err_expected_ident);
2040      SkipUntil(tok::r_paren);
2041      return;
2042    }
2043
2044    IdentifierInfo *ParmII = Tok.getIdentifierInfo();
2045
2046    // Reject 'typedef int y; int test(x, y)', but continue parsing.
2047    if (Actions.isTypeName(*ParmII, CurScope))
2048      Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
2049
2050    // Verify that the argument identifier has not already been mentioned.
2051    if (!ParamsSoFar.insert(ParmII)) {
2052      Diag(Tok, diag::err_param_redefinition) << ParmII;
2053    } else {
2054      // Remember this identifier in ParamInfo.
2055      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
2056                                                     Tok.getLocation(), 0));
2057    }
2058
2059    // Eat the identifier.
2060    ConsumeToken();
2061  }
2062
2063  // Remember that we parsed a function type, and remember the attributes.  This
2064  // function type is always a K&R style function type, which is not varargs and
2065  // has no prototype.
2066  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
2067                                             &ParamInfo[0], ParamInfo.size(),
2068                                             /*TypeQuals*/0, LParenLoc));
2069
2070  // If we have the closing ')', eat it and we're done.
2071  MatchRHSPunctuation(tok::r_paren, LParenLoc);
2072}
2073
2074/// [C90]   direct-declarator '[' constant-expression[opt] ']'
2075/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2076/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2077/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2078/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
2079void Parser::ParseBracketDeclarator(Declarator &D) {
2080  SourceLocation StartLoc = ConsumeBracket();
2081
2082  // C array syntax has many features, but by-far the most common is [] and [4].
2083  // This code does a fast path to handle some of the most obvious cases.
2084  if (Tok.getKind() == tok::r_square) {
2085    MatchRHSPunctuation(tok::r_square, StartLoc);
2086    // Remember that we parsed the empty array type.
2087    OwningExprResult NumElements(Actions);
2088    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0, StartLoc));
2089    return;
2090  } else if (Tok.getKind() == tok::numeric_constant &&
2091             GetLookAheadToken(1).is(tok::r_square)) {
2092    // [4] is very common.  Parse the numeric constant expression.
2093    OwningExprResult ExprRes(Actions, Actions.ActOnNumericConstant(Tok));
2094    ConsumeToken();
2095
2096    MatchRHSPunctuation(tok::r_square, StartLoc);
2097
2098    // If there was an error parsing the assignment-expression, recover.
2099    if (ExprRes.isInvalid())
2100      ExprRes.release();  // Deallocate expr, just use [].
2101
2102    // Remember that we parsed a array type, and remember its features.
2103    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0,
2104                                            ExprRes.release(), StartLoc));
2105    return;
2106  }
2107
2108  // If valid, this location is the position where we read the 'static' keyword.
2109  SourceLocation StaticLoc;
2110  if (Tok.is(tok::kw_static))
2111    StaticLoc = ConsumeToken();
2112
2113  // If there is a type-qualifier-list, read it now.
2114  // Type qualifiers in an array subscript are a C99 feature.
2115  DeclSpec DS;
2116  ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2117
2118  // If we haven't already read 'static', check to see if there is one after the
2119  // type-qualifier-list.
2120  if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
2121    StaticLoc = ConsumeToken();
2122
2123  // Handle "direct-declarator [ type-qual-list[opt] * ]".
2124  bool isStar = false;
2125  OwningExprResult NumElements(Actions);
2126
2127  // Handle the case where we have '[*]' as the array size.  However, a leading
2128  // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
2129  // the the token after the star is a ']'.  Since stars in arrays are
2130  // infrequent, use of lookahead is not costly here.
2131  if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
2132    ConsumeToken();  // Eat the '*'.
2133
2134    if (StaticLoc.isValid()) {
2135      Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
2136      StaticLoc = SourceLocation();  // Drop the static.
2137    }
2138    isStar = true;
2139  } else if (Tok.isNot(tok::r_square)) {
2140    // Note, in C89, this production uses the constant-expr production instead
2141    // of assignment-expr.  The only difference is that assignment-expr allows
2142    // things like '=' and '*='.  Sema rejects these in C89 mode because they
2143    // are not i-c-e's, so we don't need to distinguish between the two here.
2144
2145    // Parse the assignment-expression now.
2146    NumElements = ParseAssignmentExpression();
2147  }
2148
2149  // If there was an error parsing the assignment-expression, recover.
2150  if (NumElements.isInvalid()) {
2151    // If the expression was invalid, skip it.
2152    SkipUntil(tok::r_square);
2153    return;
2154  }
2155
2156  MatchRHSPunctuation(tok::r_square, StartLoc);
2157
2158  // Remember that we parsed a array type, and remember its features.
2159  D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
2160                                          StaticLoc.isValid(), isStar,
2161                                          NumElements.release(), StartLoc));
2162}
2163
2164/// [GNU]   typeof-specifier:
2165///           typeof ( expressions )
2166///           typeof ( type-name )
2167/// [GNU/C++] typeof unary-expression
2168///
2169void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
2170  assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
2171  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
2172  SourceLocation StartLoc = ConsumeToken();
2173
2174  if (Tok.isNot(tok::l_paren)) {
2175    if (!getLang().CPlusPlus) {
2176      Diag(Tok, diag::err_expected_lparen_after_id) << BuiltinII;
2177      return;
2178    }
2179
2180    OwningExprResult Result(ParseCastExpression(true/*isUnaryExpression*/));
2181    if (Result.isInvalid())
2182      return;
2183
2184    const char *PrevSpec = 0;
2185    // Check for duplicate type specifiers.
2186    if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
2187                           Result.release()))
2188      Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
2189
2190    // FIXME: Not accurate, the range gets one token more than it should.
2191    DS.SetRangeEnd(Tok.getLocation());
2192    return;
2193  }
2194
2195  SourceLocation LParenLoc = ConsumeParen(), RParenLoc;
2196
2197  if (isTypeIdInParens()) {
2198    TypeTy *Ty = ParseTypeName();
2199
2200    assert(Ty && "Parser::ParseTypeofSpecifier(): missing type");
2201
2202    if (Tok.isNot(tok::r_paren)) {
2203      MatchRHSPunctuation(tok::r_paren, LParenLoc);
2204      return;
2205    }
2206    RParenLoc = ConsumeParen();
2207    const char *PrevSpec = 0;
2208    // Check for duplicate type specifiers (e.g. "int typeof(int)").
2209    if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, Ty))
2210      Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
2211  } else { // we have an expression.
2212    OwningExprResult Result(ParseExpression());
2213
2214    if (Result.isInvalid() || Tok.isNot(tok::r_paren)) {
2215      MatchRHSPunctuation(tok::r_paren, LParenLoc);
2216      return;
2217    }
2218    RParenLoc = ConsumeParen();
2219    const char *PrevSpec = 0;
2220    // Check for duplicate type specifiers (e.g. "int typeof(int)").
2221    if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
2222                           Result.release()))
2223      Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
2224  }
2225  DS.SetRangeEnd(RParenLoc);
2226}
2227
2228
2229