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