ParseDecl.cpp revision 675431d5a8b6aed1bd7322aa2da5cd8eb0ae76b7
1//===--- ParseDecl.cpp - Declaration Parsing ------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements the Declaration portions of the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
15#include "clang/Parse/ParseDiagnostic.h"
16#include "clang/Parse/Scope.h"
17#include "ExtensionRAIIObject.h"
18#include "llvm/ADT/SmallSet.h"
19using namespace clang;
20
21//===----------------------------------------------------------------------===//
22// C99 6.7: Declarations.
23//===----------------------------------------------------------------------===//
24
25/// ParseTypeName
26///       type-name: [C99 6.7.6]
27///         specifier-qualifier-list abstract-declarator[opt]
28///
29/// Called type-id in C++.
30Action::TypeResult Parser::ParseTypeName(SourceRange *Range) {
31  // Parse the common declaration-specifiers piece.
32  DeclSpec DS;
33  ParseSpecifierQualifierList(DS);
34
35  // Parse the abstract-declarator, if present.
36  Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
37  ParseDeclarator(DeclaratorInfo);
38  if (Range)
39    *Range = DeclaratorInfo.getSourceRange();
40
41  if (DeclaratorInfo.isInvalidType())
42    return true;
43
44  return Actions.ActOnTypeName(CurScope, DeclaratorInfo);
45}
46
47/// ParseAttributes - Parse a non-empty attributes list.
48///
49/// [GNU] attributes:
50///         attribute
51///         attributes attribute
52///
53/// [GNU]  attribute:
54///          '__attribute__' '(' '(' attribute-list ')' ')'
55///
56/// [GNU]  attribute-list:
57///          attrib
58///          attribute_list ',' attrib
59///
60/// [GNU]  attrib:
61///          empty
62///          attrib-name
63///          attrib-name '(' identifier ')'
64///          attrib-name '(' identifier ',' nonempty-expr-list ')'
65///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
66///
67/// [GNU]  attrib-name:
68///          identifier
69///          typespec
70///          typequal
71///          storageclass
72///
73/// FIXME: The GCC grammar/code for this construct implies we need two
74/// token lookahead. Comment from gcc: "If they start with an identifier
75/// which is followed by a comma or close parenthesis, then the arguments
76/// start with that identifier; otherwise they are an expression list."
77///
78/// At the moment, I am not doing 2 token lookahead. I am also unaware of
79/// any attributes that don't work (based on my limited testing). Most
80/// attributes are very simple in practice. Until we find a bug, I don't see
81/// a pressing need to implement the 2 token lookahead.
82
83AttributeList *Parser::ParseAttributes(SourceLocation *EndLoc) {
84  assert(Tok.is(tok::kw___attribute) && "Not an attribute list!");
85
86  AttributeList *CurrAttr = 0;
87
88  while (Tok.is(tok::kw___attribute)) {
89    ConsumeToken();
90    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
91                         "attribute")) {
92      SkipUntil(tok::r_paren, true); // skip until ) or ;
93      return CurrAttr;
94    }
95    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
96      SkipUntil(tok::r_paren, true); // skip until ) or ;
97      return CurrAttr;
98    }
99    // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
100    while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
101           Tok.is(tok::comma)) {
102
103      if (Tok.is(tok::comma)) {
104        // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
105        ConsumeToken();
106        continue;
107      }
108      // we have an identifier or declaration specifier (const, int, etc.)
109      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
110      SourceLocation AttrNameLoc = ConsumeToken();
111
112      // check if we have a "paramterized" attribute
113      if (Tok.is(tok::l_paren)) {
114        ConsumeParen(); // ignore the left paren loc for now
115
116        if (Tok.is(tok::identifier)) {
117          IdentifierInfo *ParmName = Tok.getIdentifierInfo();
118          SourceLocation ParmLoc = ConsumeToken();
119
120          if (Tok.is(tok::r_paren)) {
121            // __attribute__(( mode(byte) ))
122            ConsumeParen(); // ignore the right paren loc for now
123            CurrAttr = new AttributeList(AttrName, AttrNameLoc,
124                                         ParmName, ParmLoc, 0, 0, CurrAttr);
125          } else if (Tok.is(tok::comma)) {
126            ConsumeToken();
127            // __attribute__(( format(printf, 1, 2) ))
128            ExprVector ArgExprs(Actions);
129            bool ArgExprsOk = true;
130
131            // now parse the non-empty comma separated list of expressions
132            while (1) {
133              OwningExprResult ArgExpr(ParseAssignmentExpression());
134              if (ArgExpr.isInvalid()) {
135                ArgExprsOk = false;
136                SkipUntil(tok::r_paren);
137                break;
138              } else {
139                ArgExprs.push_back(ArgExpr.release());
140              }
141              if (Tok.isNot(tok::comma))
142                break;
143              ConsumeToken(); // Eat the comma, move to the next argument
144            }
145            if (ArgExprsOk && Tok.is(tok::r_paren)) {
146              ConsumeParen(); // ignore the right paren loc for now
147              CurrAttr = new AttributeList(AttrName, AttrNameLoc, ParmName,
148                           ParmLoc, ArgExprs.take(), ArgExprs.size(), CurrAttr);
149            }
150          }
151        } else { // not an identifier
152          switch (Tok.getKind()) {
153          case tok::r_paren:
154          // parse a possibly empty comma separated list of expressions
155            // __attribute__(( nonnull() ))
156            ConsumeParen(); // ignore the right paren loc for now
157            CurrAttr = new AttributeList(AttrName, AttrNameLoc,
158                                         0, SourceLocation(), 0, 0, CurrAttr);
159            break;
160          case tok::kw_char:
161          case tok::kw_wchar_t:
162          case tok::kw_bool:
163          case tok::kw_short:
164          case tok::kw_int:
165          case tok::kw_long:
166          case tok::kw_signed:
167          case tok::kw_unsigned:
168          case tok::kw_float:
169          case tok::kw_double:
170          case tok::kw_void:
171          case tok::kw_typeof:
172            // If it's a builtin type name, eat it and expect a rparen
173            // __attribute__(( vec_type_hint(char) ))
174            ConsumeToken();
175            CurrAttr = new AttributeList(AttrName, AttrNameLoc,
176                                         0, SourceLocation(), 0, 0, CurrAttr);
177            if (Tok.is(tok::r_paren))
178              ConsumeParen();
179            break;
180          default:
181            // __attribute__(( aligned(16) ))
182            ExprVector ArgExprs(Actions);
183            bool ArgExprsOk = true;
184
185            // now parse the list of expressions
186            while (1) {
187              OwningExprResult ArgExpr(ParseAssignmentExpression());
188              if (ArgExpr.isInvalid()) {
189                ArgExprsOk = false;
190                SkipUntil(tok::r_paren);
191                break;
192              } else {
193                ArgExprs.push_back(ArgExpr.release());
194              }
195              if (Tok.isNot(tok::comma))
196                break;
197              ConsumeToken(); // Eat the comma, move to the next argument
198            }
199            // Match the ')'.
200            if (ArgExprsOk && Tok.is(tok::r_paren)) {
201              ConsumeParen(); // ignore the right paren loc for now
202              CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0,
203                           SourceLocation(), ArgExprs.take(), ArgExprs.size(),
204                           CurrAttr);
205            }
206            break;
207          }
208        }
209      } else {
210        CurrAttr = new AttributeList(AttrName, AttrNameLoc,
211                                     0, SourceLocation(), 0, 0, CurrAttr);
212      }
213    }
214    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
215      SkipUntil(tok::r_paren, false);
216    SourceLocation Loc = Tok.getLocation();;
217    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
218      SkipUntil(tok::r_paren, false);
219    }
220    if (EndLoc)
221      *EndLoc = Loc;
222  }
223  return CurrAttr;
224}
225
226/// ParseMicrosoftDeclSpec - Parse an __declspec construct
227///
228/// [MS] decl-specifier:
229///             __declspec ( extended-decl-modifier-seq )
230///
231/// [MS] extended-decl-modifier-seq:
232///             extended-decl-modifier[opt]
233///             extended-decl-modifier extended-decl-modifier-seq
234
235AttributeList* Parser::ParseMicrosoftDeclSpec(AttributeList *CurrAttr) {
236  assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
237
238  ConsumeToken();
239  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
240                       "declspec")) {
241    SkipUntil(tok::r_paren, true); // skip until ) or ;
242    return CurrAttr;
243  }
244  while (Tok.getIdentifierInfo()) {
245    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
246    SourceLocation AttrNameLoc = ConsumeToken();
247    if (Tok.is(tok::l_paren)) {
248      ConsumeParen();
249      // FIXME: This doesn't parse __declspec(property(get=get_func_name))
250      // correctly.
251      OwningExprResult ArgExpr(ParseAssignmentExpression());
252      if (!ArgExpr.isInvalid()) {
253        ExprTy* ExprList = ArgExpr.take();
254        CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0,
255                                     SourceLocation(), &ExprList, 1,
256                                     CurrAttr, true);
257      }
258      if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
259        SkipUntil(tok::r_paren, false);
260    } else {
261      CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, SourceLocation(),
262                                   0, 0, CurrAttr, true);
263    }
264  }
265  if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
266    SkipUntil(tok::r_paren, false);
267  return CurrAttr;
268}
269
270AttributeList* Parser::ParseMicrosoftTypeAttributes(AttributeList *CurrAttr) {
271  // Treat these like attributes
272  // FIXME: Allow Sema to distinguish between these and real attributes!
273  while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
274         Tok.is(tok::kw___cdecl)    || Tok.is(tok::kw___ptr64) ||
275         Tok.is(tok::kw___w64)) {
276    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
277    SourceLocation AttrNameLoc = ConsumeToken();
278    if (Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64))
279      // FIXME: Support these properly!
280      continue;
281    CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0,
282                                 SourceLocation(), 0, 0, CurrAttr, true);
283  }
284  return CurrAttr;
285}
286
287/// ParseDeclaration - Parse a full 'declaration', which consists of
288/// declaration-specifiers, some number of declarators, and a semicolon.
289/// 'Context' should be a Declarator::TheContext value.  This returns the
290/// location of the semicolon in DeclEnd.
291///
292///       declaration: [C99 6.7]
293///         block-declaration ->
294///           simple-declaration
295///           others                   [FIXME]
296/// [C++]   template-declaration
297/// [C++]   namespace-definition
298/// [C++]   using-directive
299/// [C++]   using-declaration
300/// [C++0x] static_assert-declaration
301///         others... [FIXME]
302///
303Parser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context,
304                                                SourceLocation &DeclEnd) {
305  DeclPtrTy SingleDecl;
306  switch (Tok.getKind()) {
307  case tok::kw_template:
308  case tok::kw_export:
309    SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
310    break;
311  case tok::kw_namespace:
312    SingleDecl = ParseNamespace(Context, DeclEnd);
313    break;
314  case tok::kw_using:
315    SingleDecl = ParseUsingDirectiveOrDeclaration(Context, DeclEnd);
316    break;
317  case tok::kw_static_assert:
318    SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
319    break;
320  default:
321    return ParseSimpleDeclaration(Context, DeclEnd);
322  }
323
324  // This routine returns a DeclGroup, if the thing we parsed only contains a
325  // single decl, convert it now.
326  return Actions.ConvertDeclToDeclGroup(SingleDecl);
327}
328
329///       simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
330///         declaration-specifiers init-declarator-list[opt] ';'
331///[C90/C++]init-declarator-list ';'                             [TODO]
332/// [OMP]   threadprivate-directive                              [TODO]
333///
334/// If RequireSemi is false, this does not check for a ';' at the end of the
335/// declaration.
336Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(unsigned Context,
337                                                      SourceLocation &DeclEnd,
338                                                      bool RequireSemi) {
339  // Parse the common declaration-specifiers piece.
340  DeclSpec DS;
341  ParseDeclarationSpecifiers(DS);
342
343  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
344  // declaration-specifiers init-declarator-list[opt] ';'
345  if (Tok.is(tok::semi)) {
346    ConsumeToken();
347    DeclPtrTy TheDecl = Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
348    return Actions.ConvertDeclToDeclGroup(TheDecl);
349  }
350
351  Declarator DeclaratorInfo(DS, (Declarator::TheContext)Context);
352  ParseDeclarator(DeclaratorInfo);
353
354  DeclGroupPtrTy DG =
355    ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo);
356
357  DeclEnd = Tok.getLocation();
358
359  // If the client wants to check what comes after the declaration, just return
360  // immediately without checking anything!
361  if (!RequireSemi) return DG;
362
363  if (Tok.is(tok::semi)) {
364    ConsumeToken();
365    return DG;
366  }
367
368  Diag(Tok, diag::err_expected_semi_declation);
369  // Skip to end of block or statement
370  SkipUntil(tok::r_brace, true, true);
371  if (Tok.is(tok::semi))
372    ConsumeToken();
373  return DG;
374}
375
376/// \brief Parse 'declaration' after parsing 'declaration-specifiers
377/// declarator'. This method parses the remainder of the declaration
378/// (including any attributes or initializer, among other things) and
379/// finalizes the declaration.
380///
381///       init-declarator: [C99 6.7]
382///         declarator
383///         declarator '=' initializer
384/// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
385/// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
386/// [C++]   declarator initializer[opt]
387///
388/// [C++] initializer:
389/// [C++]   '=' initializer-clause
390/// [C++]   '(' expression-list ')'
391/// [C++0x] '=' 'default'                                                [TODO]
392/// [C++0x] '=' 'delete'
393///
394/// According to the standard grammar, =default and =delete are function
395/// definitions, but that definitely doesn't fit with the parser here.
396///
397Parser::DeclPtrTy Parser::ParseDeclarationAfterDeclarator(Declarator &D,
398                                     const ParsedTemplateInfo &TemplateInfo) {
399  // If a simple-asm-expr is present, parse it.
400  if (Tok.is(tok::kw_asm)) {
401    SourceLocation Loc;
402    OwningExprResult AsmLabel(ParseSimpleAsm(&Loc));
403    if (AsmLabel.isInvalid()) {
404      SkipUntil(tok::semi, true, true);
405      return DeclPtrTy();
406    }
407
408    D.setAsmLabel(AsmLabel.release());
409    D.SetRangeEnd(Loc);
410  }
411
412  // If attributes are present, parse them.
413  if (Tok.is(tok::kw___attribute)) {
414    SourceLocation Loc;
415    AttributeList *AttrList = ParseAttributes(&Loc);
416    D.AddAttributes(AttrList, Loc);
417  }
418
419  // Inform the current actions module that we just parsed this declarator.
420  DeclPtrTy ThisDecl = TemplateInfo.TemplateParams?
421      Actions.ActOnTemplateDeclarator(CurScope,
422                             Action::MultiTemplateParamsArg(Actions,
423                                          TemplateInfo.TemplateParams->data(),
424                                          TemplateInfo.TemplateParams->size()),
425                                    D)
426    : Actions.ActOnDeclarator(CurScope, D);
427
428  // Parse declarator '=' initializer.
429  if (Tok.is(tok::equal)) {
430    ConsumeToken();
431    if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) {
432      SourceLocation DelLoc = ConsumeToken();
433      Actions.SetDeclDeleted(ThisDecl, DelLoc);
434    } else {
435      if (getLang().CPlusPlus)
436        Actions.ActOnCXXEnterDeclInitializer(CurScope, ThisDecl);
437
438      OwningExprResult Init(ParseInitializer());
439
440      if (getLang().CPlusPlus)
441        Actions.ActOnCXXExitDeclInitializer(CurScope, ThisDecl);
442
443      if (Init.isInvalid()) {
444        SkipUntil(tok::semi, true, true);
445        return DeclPtrTy();
446      }
447      Actions.AddInitializerToDecl(ThisDecl, Actions.FullExpr(Init));
448    }
449  } else if (Tok.is(tok::l_paren)) {
450    // Parse C++ direct initializer: '(' expression-list ')'
451    SourceLocation LParenLoc = ConsumeParen();
452    ExprVector Exprs(Actions);
453    CommaLocsTy CommaLocs;
454
455    if (ParseExpressionList(Exprs, CommaLocs)) {
456      SkipUntil(tok::r_paren);
457    } else {
458      // Match the ')'.
459      SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
460
461      assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
462             "Unexpected number of commas!");
463      Actions.AddCXXDirectInitializerToDecl(ThisDecl, LParenLoc,
464                                            move_arg(Exprs),
465                                            CommaLocs.data(), RParenLoc);
466    }
467  } else {
468    Actions.ActOnUninitializedDecl(ThisDecl);
469  }
470
471  return ThisDecl;
472}
473
474/// ParseInitDeclaratorListAfterFirstDeclarator - Parse 'declaration' after
475/// parsing 'declaration-specifiers declarator'.  This method is split out this
476/// way to handle the ambiguity between top-level function-definitions and
477/// declarations.
478///
479///       init-declarator-list: [C99 6.7]
480///         init-declarator
481///         init-declarator-list ',' init-declarator
482///
483/// According to the standard grammar, =default and =delete are function
484/// definitions, but that definitely doesn't fit with the parser here.
485///
486Parser::DeclGroupPtrTy Parser::
487ParseInitDeclaratorListAfterFirstDeclarator(Declarator &D) {
488  // Declarators may be grouped together ("int X, *Y, Z();"). Remember the decls
489  // that we parse together here.
490  llvm::SmallVector<DeclPtrTy, 8> DeclsInGroup;
491
492  // At this point, we know that it is not a function definition.  Parse the
493  // rest of the init-declarator-list.
494  while (1) {
495    DeclPtrTy ThisDecl = ParseDeclarationAfterDeclarator(D);
496    if (ThisDecl.get())
497      DeclsInGroup.push_back(ThisDecl);
498
499    // If we don't have a comma, it is either the end of the list (a ';') or an
500    // error, bail out.
501    if (Tok.isNot(tok::comma))
502      break;
503
504    // Consume the comma.
505    ConsumeToken();
506
507    // Parse the next declarator.
508    D.clear();
509
510    // Accept attributes in an init-declarator.  In the first declarator in a
511    // declaration, these would be part of the declspec.  In subsequent
512    // declarators, they become part of the declarator itself, so that they
513    // don't apply to declarators after *this* one.  Examples:
514    //    short __attribute__((common)) var;    -> declspec
515    //    short var __attribute__((common));    -> declarator
516    //    short x, __attribute__((common)) var;    -> declarator
517    if (Tok.is(tok::kw___attribute)) {
518      SourceLocation Loc;
519      AttributeList *AttrList = ParseAttributes(&Loc);
520      D.AddAttributes(AttrList, Loc);
521    }
522
523    ParseDeclarator(D);
524  }
525
526  return Actions.FinalizeDeclaratorGroup(CurScope, D.getDeclSpec(),
527                                         DeclsInGroup.data(),
528                                         DeclsInGroup.size());
529}
530
531/// ParseSpecifierQualifierList
532///        specifier-qualifier-list:
533///          type-specifier specifier-qualifier-list[opt]
534///          type-qualifier specifier-qualifier-list[opt]
535/// [GNU]    attributes     specifier-qualifier-list[opt]
536///
537void Parser::ParseSpecifierQualifierList(DeclSpec &DS) {
538  /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
539  /// parse declaration-specifiers and complain about extra stuff.
540  ParseDeclarationSpecifiers(DS);
541
542  // Validate declspec for type-name.
543  unsigned Specs = DS.getParsedSpecifiers();
544  if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
545      !DS.getAttributes())
546    Diag(Tok, diag::err_typename_requires_specqual);
547
548  // Issue diagnostic and remove storage class if present.
549  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
550    if (DS.getStorageClassSpecLoc().isValid())
551      Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
552    else
553      Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
554    DS.ClearStorageClassSpecs();
555  }
556
557  // Issue diagnostic and remove function specfier if present.
558  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
559    if (DS.isInlineSpecified())
560      Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
561    if (DS.isVirtualSpecified())
562      Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
563    if (DS.isExplicitSpecified())
564      Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
565    DS.ClearFunctionSpecs();
566  }
567}
568
569/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
570/// specified token is valid after the identifier in a declarator which
571/// immediately follows the declspec.  For example, these things are valid:
572///
573///      int x   [             4];         // direct-declarator
574///      int x   (             int y);     // direct-declarator
575///  int(int x   )                         // direct-declarator
576///      int x   ;                         // simple-declaration
577///      int x   =             17;         // init-declarator-list
578///      int x   ,             y;          // init-declarator-list
579///      int x   __asm__       ("foo");    // init-declarator-list
580///      int x   :             4;          // struct-declarator
581///      int x   {             5};         // C++'0x unified initializers
582///
583/// This is not, because 'x' does not immediately follow the declspec (though
584/// ')' happens to be valid anyway).
585///    int (x)
586///
587static bool isValidAfterIdentifierInDeclarator(const Token &T) {
588  return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
589         T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
590         T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
591}
592
593
594/// ParseImplicitInt - This method is called when we have an non-typename
595/// identifier in a declspec (which normally terminates the decl spec) when
596/// the declspec has no type specifier.  In this case, the declspec is either
597/// malformed or is "implicit int" (in K&R and C89).
598///
599/// This method handles diagnosing this prettily and returns false if the
600/// declspec is done being processed.  If it recovers and thinks there may be
601/// other pieces of declspec after it, it returns true.
602///
603bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
604                              const ParsedTemplateInfo &TemplateInfo,
605                              AccessSpecifier AS) {
606  assert(Tok.is(tok::identifier) && "should have identifier");
607
608  SourceLocation Loc = Tok.getLocation();
609  // If we see an identifier that is not a type name, we normally would
610  // parse it as the identifer being declared.  However, when a typename
611  // is typo'd or the definition is not included, this will incorrectly
612  // parse the typename as the identifier name and fall over misparsing
613  // later parts of the diagnostic.
614  //
615  // As such, we try to do some look-ahead in cases where this would
616  // otherwise be an "implicit-int" case to see if this is invalid.  For
617  // example: "static foo_t x = 4;"  In this case, if we parsed foo_t as
618  // an identifier with implicit int, we'd get a parse error because the
619  // next token is obviously invalid for a type.  Parse these as a case
620  // with an invalid type specifier.
621  assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
622
623  // Since we know that this either implicit int (which is rare) or an
624  // error, we'd do lookahead to try to do better recovery.
625  if (isValidAfterIdentifierInDeclarator(NextToken())) {
626    // If this token is valid for implicit int, e.g. "static x = 4", then
627    // we just avoid eating the identifier, so it will be parsed as the
628    // identifier in the declarator.
629    return false;
630  }
631
632  // Otherwise, if we don't consume this token, we are going to emit an
633  // error anyway.  Try to recover from various common problems.  Check
634  // to see if this was a reference to a tag name without a tag specified.
635  // This is a common problem in C (saying 'foo' instead of 'struct foo').
636  //
637  // C++ doesn't need this, and isTagName doesn't take SS.
638  if (SS == 0) {
639    const char *TagName = 0;
640    tok::TokenKind TagKind = tok::unknown;
641
642    switch (Actions.isTagName(*Tok.getIdentifierInfo(), CurScope)) {
643      default: break;
644      case DeclSpec::TST_enum:  TagName="enum"  ;TagKind=tok::kw_enum  ;break;
645      case DeclSpec::TST_union: TagName="union" ;TagKind=tok::kw_union ;break;
646      case DeclSpec::TST_struct:TagName="struct";TagKind=tok::kw_struct;break;
647      case DeclSpec::TST_class: TagName="class" ;TagKind=tok::kw_class ;break;
648    }
649
650    if (TagName) {
651      Diag(Loc, diag::err_use_of_tag_name_without_tag)
652        << Tok.getIdentifierInfo() << TagName
653        << CodeModificationHint::CreateInsertion(Tok.getLocation(),TagName);
654
655      // Parse this as a tag as if the missing tag were present.
656      if (TagKind == tok::kw_enum)
657        ParseEnumSpecifier(Loc, DS, AS);
658      else
659        ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS);
660      return true;
661    }
662  }
663
664  // Since this is almost certainly an invalid type name, emit a
665  // diagnostic that says it, eat the token, and mark the declspec as
666  // invalid.
667  SourceRange R;
668  if (SS) R = SS->getRange();
669
670  Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
671  const char *PrevSpec;
672  DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec);
673  DS.SetRangeEnd(Tok.getLocation());
674  ConsumeToken();
675
676  // TODO: Could inject an invalid typedef decl in an enclosing scope to
677  // avoid rippling error messages on subsequent uses of the same type,
678  // could be useful if #include was forgotten.
679  return false;
680}
681
682/// ParseDeclarationSpecifiers
683///       declaration-specifiers: [C99 6.7]
684///         storage-class-specifier declaration-specifiers[opt]
685///         type-specifier declaration-specifiers[opt]
686/// [C99]   function-specifier declaration-specifiers[opt]
687/// [GNU]   attributes declaration-specifiers[opt]
688///
689///       storage-class-specifier: [C99 6.7.1]
690///         'typedef'
691///         'extern'
692///         'static'
693///         'auto'
694///         'register'
695/// [C++]   'mutable'
696/// [GNU]   '__thread'
697///       function-specifier: [C99 6.7.4]
698/// [C99]   'inline'
699/// [C++]   'virtual'
700/// [C++]   'explicit'
701///       'friend': [C++ dcl.friend]
702
703///
704void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
705                                        const ParsedTemplateInfo &TemplateInfo,
706                                        AccessSpecifier AS) {
707  DS.SetRangeStart(Tok.getLocation());
708  while (1) {
709    int isInvalid = false;
710    const char *PrevSpec = 0;
711    SourceLocation Loc = Tok.getLocation();
712
713    switch (Tok.getKind()) {
714    default:
715    DoneWithDeclSpec:
716      // If this is not a declaration specifier token, we're done reading decl
717      // specifiers.  First verify that DeclSpec's are consistent.
718      DS.Finish(Diags, PP);
719      return;
720
721    case tok::coloncolon: // ::foo::bar
722      // Annotate C++ scope specifiers.  If we get one, loop.
723      if (TryAnnotateCXXScopeToken())
724        continue;
725      goto DoneWithDeclSpec;
726
727    case tok::annot_cxxscope: {
728      if (DS.hasTypeSpecifier())
729        goto DoneWithDeclSpec;
730
731      // We are looking for a qualified typename.
732      Token Next = NextToken();
733      if (Next.is(tok::annot_template_id) &&
734          static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
735            ->Kind == TNK_Type_template) {
736        // We have a qualified template-id, e.g., N::A<int>
737        CXXScopeSpec SS;
738        ParseOptionalCXXScopeSpecifier(SS);
739        assert(Tok.is(tok::annot_template_id) &&
740               "ParseOptionalCXXScopeSpecifier not working");
741        AnnotateTemplateIdTokenAsType(&SS);
742        continue;
743      }
744
745      if (Next.isNot(tok::identifier))
746        goto DoneWithDeclSpec;
747
748      CXXScopeSpec SS;
749      SS.setScopeRep(Tok.getAnnotationValue());
750      SS.setRange(Tok.getAnnotationRange());
751
752      // If the next token is the name of the class type that the C++ scope
753      // denotes, followed by a '(', then this is a constructor declaration.
754      // We're done with the decl-specifiers.
755      if (Actions.isCurrentClassName(*Next.getIdentifierInfo(),
756                                     CurScope, &SS) &&
757          GetLookAheadToken(2).is(tok::l_paren))
758        goto DoneWithDeclSpec;
759
760      TypeTy *TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
761                                            Next.getLocation(), CurScope, &SS);
762
763      // If the referenced identifier is not a type, then this declspec is
764      // erroneous: We already checked about that it has no type specifier, and
765      // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
766      // typename.
767      if (TypeRep == 0) {
768        ConsumeToken();   // Eat the scope spec so the identifier is current.
769        if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue;
770        goto DoneWithDeclSpec;
771      }
772
773      ConsumeToken(); // The C++ scope.
774
775      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
776                                     TypeRep);
777      if (isInvalid)
778        break;
779
780      DS.SetRangeEnd(Tok.getLocation());
781      ConsumeToken(); // The typename.
782
783      continue;
784    }
785
786    case tok::annot_typename: {
787      if (Tok.getAnnotationValue())
788        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
789                                       Tok.getAnnotationValue());
790      else
791        DS.SetTypeSpecError();
792      DS.SetRangeEnd(Tok.getAnnotationEndLoc());
793      ConsumeToken(); // The typename
794
795      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
796      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
797      // Objective-C interface.  If we don't have Objective-C or a '<', this is
798      // just a normal reference to a typedef name.
799      if (!Tok.is(tok::less) || !getLang().ObjC1)
800        continue;
801
802      SourceLocation EndProtoLoc;
803      llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
804      ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
805      DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size());
806
807      DS.SetRangeEnd(EndProtoLoc);
808      continue;
809    }
810
811      // typedef-name
812    case tok::identifier: {
813      // In C++, check to see if this is a scope specifier like foo::bar::, if
814      // so handle it as such.  This is important for ctor parsing.
815      if (getLang().CPlusPlus && TryAnnotateCXXScopeToken())
816        continue;
817
818      // This identifier can only be a typedef name if we haven't already seen
819      // a type-specifier.  Without this check we misparse:
820      //  typedef int X; struct Y { short X; };  as 'short int'.
821      if (DS.hasTypeSpecifier())
822        goto DoneWithDeclSpec;
823
824      // It has to be available as a typedef too!
825      TypeTy *TypeRep = Actions.getTypeName(*Tok.getIdentifierInfo(),
826                                            Tok.getLocation(), CurScope);
827
828      // If this is not a typedef name, don't parse it as part of the declspec,
829      // it must be an implicit int or an error.
830      if (TypeRep == 0) {
831        if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue;
832        goto DoneWithDeclSpec;
833      }
834
835      // C++: If the identifier is actually the name of the class type
836      // being defined and the next token is a '(', then this is a
837      // constructor declaration. We're done with the decl-specifiers
838      // and will treat this token as an identifier.
839      if (getLang().CPlusPlus && CurScope->isClassScope() &&
840          Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) &&
841          NextToken().getKind() == tok::l_paren)
842        goto DoneWithDeclSpec;
843
844      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
845                                     TypeRep);
846      if (isInvalid)
847        break;
848
849      DS.SetRangeEnd(Tok.getLocation());
850      ConsumeToken(); // The identifier
851
852      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
853      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
854      // Objective-C interface.  If we don't have Objective-C or a '<', this is
855      // just a normal reference to a typedef name.
856      if (!Tok.is(tok::less) || !getLang().ObjC1)
857        continue;
858
859      SourceLocation EndProtoLoc;
860      llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
861      ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
862      DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size());
863
864      DS.SetRangeEnd(EndProtoLoc);
865
866      // Need to support trailing type qualifiers (e.g. "id<p> const").
867      // If a type specifier follows, it will be diagnosed elsewhere.
868      continue;
869    }
870
871      // type-name
872    case tok::annot_template_id: {
873      TemplateIdAnnotation *TemplateId
874        = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
875      if (TemplateId->Kind != TNK_Type_template) {
876        // This template-id does not refer to a type name, so we're
877        // done with the type-specifiers.
878        goto DoneWithDeclSpec;
879      }
880
881      // Turn the template-id annotation token into a type annotation
882      // token, then try again to parse it as a type-specifier.
883      AnnotateTemplateIdTokenAsType();
884      continue;
885    }
886
887    // GNU attributes support.
888    case tok::kw___attribute:
889      DS.AddAttributes(ParseAttributes());
890      continue;
891
892    // Microsoft declspec support.
893    case tok::kw___declspec:
894      DS.AddAttributes(ParseMicrosoftDeclSpec());
895      continue;
896
897    // Microsoft single token adornments.
898    case tok::kw___forceinline:
899      // FIXME: Add handling here!
900      break;
901
902    case tok::kw___ptr64:
903    case tok::kw___w64:
904    case tok::kw___cdecl:
905    case tok::kw___stdcall:
906    case tok::kw___fastcall:
907      DS.AddAttributes(ParseMicrosoftTypeAttributes());
908      continue;
909
910    // storage-class-specifier
911    case tok::kw_typedef:
912      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec);
913      break;
914    case tok::kw_extern:
915      if (DS.isThreadSpecified())
916        Diag(Tok, diag::ext_thread_before) << "extern";
917      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec);
918      break;
919    case tok::kw___private_extern__:
920      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
921                                         PrevSpec);
922      break;
923    case tok::kw_static:
924      if (DS.isThreadSpecified())
925        Diag(Tok, diag::ext_thread_before) << "static";
926      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec);
927      break;
928    case tok::kw_auto:
929      if (getLang().CPlusPlus0x)
930        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec);
931      else
932        isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec);
933      break;
934    case tok::kw_register:
935      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec);
936      break;
937    case tok::kw_mutable:
938      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec);
939      break;
940    case tok::kw___thread:
941      isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec)*2;
942      break;
943
944    // function-specifier
945    case tok::kw_inline:
946      isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec);
947      break;
948    case tok::kw_virtual:
949      isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec);
950      break;
951    case tok::kw_explicit:
952      isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec);
953      break;
954
955    // friend
956    case tok::kw_friend:
957      isInvalid = DS.SetFriendSpec(Loc, PrevSpec);
958      break;
959
960    // type-specifier
961    case tok::kw_short:
962      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec);
963      break;
964    case tok::kw_long:
965      if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
966        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec);
967      else
968        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec);
969      break;
970    case tok::kw_signed:
971      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec);
972      break;
973    case tok::kw_unsigned:
974      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec);
975      break;
976    case tok::kw__Complex:
977      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec);
978      break;
979    case tok::kw__Imaginary:
980      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec);
981      break;
982    case tok::kw_void:
983      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec);
984      break;
985    case tok::kw_char:
986      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec);
987      break;
988    case tok::kw_int:
989      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec);
990      break;
991    case tok::kw_float:
992      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec);
993      break;
994    case tok::kw_double:
995      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec);
996      break;
997    case tok::kw_wchar_t:
998      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec);
999      break;
1000    case tok::kw_bool:
1001    case tok::kw__Bool:
1002      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec);
1003      break;
1004    case tok::kw__Decimal32:
1005      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec);
1006      break;
1007    case tok::kw__Decimal64:
1008      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec);
1009      break;
1010    case tok::kw__Decimal128:
1011      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec);
1012      break;
1013
1014    // class-specifier:
1015    case tok::kw_class:
1016    case tok::kw_struct:
1017    case tok::kw_union: {
1018      tok::TokenKind Kind = Tok.getKind();
1019      ConsumeToken();
1020      ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS);
1021      continue;
1022    }
1023
1024    // enum-specifier:
1025    case tok::kw_enum:
1026      ConsumeToken();
1027      ParseEnumSpecifier(Loc, DS, AS);
1028      continue;
1029
1030    // cv-qualifier:
1031    case tok::kw_const:
1032      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec,getLang())*2;
1033      break;
1034    case tok::kw_volatile:
1035      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
1036                                 getLang())*2;
1037      break;
1038    case tok::kw_restrict:
1039      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1040                                 getLang())*2;
1041      break;
1042
1043    // C++ typename-specifier:
1044    case tok::kw_typename:
1045      if (TryAnnotateTypeOrScopeToken())
1046        continue;
1047      break;
1048
1049    // GNU typeof support.
1050    case tok::kw_typeof:
1051      ParseTypeofSpecifier(DS);
1052      continue;
1053
1054    case tok::kw_decltype:
1055      ParseDecltypeSpecifier(DS);
1056      continue;
1057
1058    case tok::less:
1059      // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
1060      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
1061      // but we support it.
1062      if (DS.hasTypeSpecifier() || !getLang().ObjC1)
1063        goto DoneWithDeclSpec;
1064
1065      {
1066        SourceLocation EndProtoLoc;
1067        llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1068        ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
1069        DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size());
1070        DS.SetRangeEnd(EndProtoLoc);
1071
1072        Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
1073          << CodeModificationHint::CreateInsertion(Loc, "id")
1074          << SourceRange(Loc, EndProtoLoc);
1075        // Need to support trailing type qualifiers (e.g. "id<p> const").
1076        // If a type specifier follows, it will be diagnosed elsewhere.
1077        continue;
1078      }
1079    }
1080    // If the specifier combination wasn't legal, issue a diagnostic.
1081    if (isInvalid) {
1082      assert(PrevSpec && "Method did not return previous specifier!");
1083      // Pick between error or extwarn.
1084      unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination
1085                                       : diag::ext_duplicate_declspec;
1086      Diag(Tok, DiagID) << PrevSpec;
1087    }
1088    DS.SetRangeEnd(Tok.getLocation());
1089    ConsumeToken();
1090  }
1091}
1092
1093/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
1094/// primarily follow the C++ grammar with additions for C99 and GNU,
1095/// which together subsume the C grammar. Note that the C++
1096/// type-specifier also includes the C type-qualifier (for const,
1097/// volatile, and C99 restrict). Returns true if a type-specifier was
1098/// found (and parsed), false otherwise.
1099///
1100///       type-specifier: [C++ 7.1.5]
1101///         simple-type-specifier
1102///         class-specifier
1103///         enum-specifier
1104///         elaborated-type-specifier  [TODO]
1105///         cv-qualifier
1106///
1107///       cv-qualifier: [C++ 7.1.5.1]
1108///         'const'
1109///         'volatile'
1110/// [C99]   'restrict'
1111///
1112///       simple-type-specifier: [ C++ 7.1.5.2]
1113///         '::'[opt] nested-name-specifier[opt] type-name [TODO]
1114///         '::'[opt] nested-name-specifier 'template' template-id [TODO]
1115///         'char'
1116///         'wchar_t'
1117///         'bool'
1118///         'short'
1119///         'int'
1120///         'long'
1121///         'signed'
1122///         'unsigned'
1123///         'float'
1124///         'double'
1125///         'void'
1126/// [C99]   '_Bool'
1127/// [C99]   '_Complex'
1128/// [C99]   '_Imaginary'  // Removed in TC2?
1129/// [GNU]   '_Decimal32'
1130/// [GNU]   '_Decimal64'
1131/// [GNU]   '_Decimal128'
1132/// [GNU]   typeof-specifier
1133/// [OBJC]  class-name objc-protocol-refs[opt]    [TODO]
1134/// [OBJC]  typedef-name objc-protocol-refs[opt]  [TODO]
1135/// [C++0x] 'decltype' ( expression )
1136bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, int& isInvalid,
1137                                        const char *&PrevSpec,
1138                                      const ParsedTemplateInfo &TemplateInfo) {
1139  SourceLocation Loc = Tok.getLocation();
1140
1141  switch (Tok.getKind()) {
1142  case tok::identifier:   // foo::bar
1143  case tok::kw_typename:  // typename foo::bar
1144    // Annotate typenames and C++ scope specifiers.  If we get one, just
1145    // recurse to handle whatever we get.
1146    if (TryAnnotateTypeOrScopeToken())
1147      return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, TemplateInfo);
1148    // Otherwise, not a type specifier.
1149    return false;
1150  case tok::coloncolon:   // ::foo::bar
1151    if (NextToken().is(tok::kw_new) ||    // ::new
1152        NextToken().is(tok::kw_delete))   // ::delete
1153      return false;
1154
1155    // Annotate typenames and C++ scope specifiers.  If we get one, just
1156    // recurse to handle whatever we get.
1157    if (TryAnnotateTypeOrScopeToken())
1158      return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, TemplateInfo);
1159    // Otherwise, not a type specifier.
1160    return false;
1161
1162  // simple-type-specifier:
1163  case tok::annot_typename: {
1164    if (Tok.getAnnotationValue())
1165      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1166                                     Tok.getAnnotationValue());
1167    else
1168      DS.SetTypeSpecError();
1169    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1170    ConsumeToken(); // The typename
1171
1172    // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1173    // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1174    // Objective-C interface.  If we don't have Objective-C or a '<', this is
1175    // just a normal reference to a typedef name.
1176    if (!Tok.is(tok::less) || !getLang().ObjC1)
1177      return true;
1178
1179    SourceLocation EndProtoLoc;
1180    llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1181    ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
1182    DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size());
1183
1184    DS.SetRangeEnd(EndProtoLoc);
1185    return true;
1186  }
1187
1188  case tok::kw_short:
1189    isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec);
1190    break;
1191  case tok::kw_long:
1192    if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1193      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec);
1194    else
1195      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec);
1196    break;
1197  case tok::kw_signed:
1198    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec);
1199    break;
1200  case tok::kw_unsigned:
1201    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec);
1202    break;
1203  case tok::kw__Complex:
1204    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec);
1205    break;
1206  case tok::kw__Imaginary:
1207    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec);
1208    break;
1209  case tok::kw_void:
1210    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec);
1211    break;
1212  case tok::kw_char:
1213    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec);
1214    break;
1215  case tok::kw_int:
1216    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec);
1217    break;
1218  case tok::kw_float:
1219    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec);
1220    break;
1221  case tok::kw_double:
1222    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec);
1223    break;
1224  case tok::kw_wchar_t:
1225    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec);
1226    break;
1227  case tok::kw_bool:
1228  case tok::kw__Bool:
1229    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec);
1230    break;
1231  case tok::kw__Decimal32:
1232    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec);
1233    break;
1234  case tok::kw__Decimal64:
1235    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec);
1236    break;
1237  case tok::kw__Decimal128:
1238    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec);
1239    break;
1240
1241  // class-specifier:
1242  case tok::kw_class:
1243  case tok::kw_struct:
1244  case tok::kw_union: {
1245    tok::TokenKind Kind = Tok.getKind();
1246    ConsumeToken();
1247    ParseClassSpecifier(Kind, Loc, DS, TemplateInfo);
1248    return true;
1249  }
1250
1251  // enum-specifier:
1252  case tok::kw_enum:
1253    ConsumeToken();
1254    ParseEnumSpecifier(Loc, DS);
1255    return true;
1256
1257  // cv-qualifier:
1258  case tok::kw_const:
1259    isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
1260                               getLang())*2;
1261    break;
1262  case tok::kw_volatile:
1263    isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
1264                               getLang())*2;
1265    break;
1266  case tok::kw_restrict:
1267    isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1268                               getLang())*2;
1269    break;
1270
1271  // GNU typeof support.
1272  case tok::kw_typeof:
1273    ParseTypeofSpecifier(DS);
1274    return true;
1275
1276  // C++0x decltype support.
1277  case tok::kw_decltype:
1278    ParseDecltypeSpecifier(DS);
1279    return true;
1280
1281  // C++0x auto support.
1282  case tok::kw_auto:
1283    if (!getLang().CPlusPlus0x)
1284      return false;
1285
1286    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec);
1287    break;
1288  case tok::kw___ptr64:
1289  case tok::kw___w64:
1290  case tok::kw___cdecl:
1291  case tok::kw___stdcall:
1292  case tok::kw___fastcall:
1293    DS.AddAttributes(ParseMicrosoftTypeAttributes());
1294    return true;
1295
1296  default:
1297    // Not a type-specifier; do nothing.
1298    return false;
1299  }
1300
1301  // If the specifier combination wasn't legal, issue a diagnostic.
1302  if (isInvalid) {
1303    assert(PrevSpec && "Method did not return previous specifier!");
1304    // Pick between error or extwarn.
1305    unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination
1306                                     : diag::ext_duplicate_declspec;
1307    Diag(Tok, DiagID) << PrevSpec;
1308  }
1309  DS.SetRangeEnd(Tok.getLocation());
1310  ConsumeToken(); // whatever we parsed above.
1311  return true;
1312}
1313
1314/// ParseStructDeclaration - Parse a struct declaration without the terminating
1315/// semicolon.
1316///
1317///       struct-declaration:
1318///         specifier-qualifier-list struct-declarator-list
1319/// [GNU]   __extension__ struct-declaration
1320/// [GNU]   specifier-qualifier-list
1321///       struct-declarator-list:
1322///         struct-declarator
1323///         struct-declarator-list ',' struct-declarator
1324/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
1325///       struct-declarator:
1326///         declarator
1327/// [GNU]   declarator attributes[opt]
1328///         declarator[opt] ':' constant-expression
1329/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
1330///
1331void Parser::
1332ParseStructDeclaration(DeclSpec &DS,
1333                       llvm::SmallVectorImpl<FieldDeclarator> &Fields) {
1334  if (Tok.is(tok::kw___extension__)) {
1335    // __extension__ silences extension warnings in the subexpression.
1336    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1337    ConsumeToken();
1338    return ParseStructDeclaration(DS, Fields);
1339  }
1340
1341  // Parse the common specifier-qualifiers-list piece.
1342  SourceLocation DSStart = Tok.getLocation();
1343  ParseSpecifierQualifierList(DS);
1344
1345  // If there are no declarators, this is a free-standing declaration
1346  // specifier. Let the actions module cope with it.
1347  if (Tok.is(tok::semi)) {
1348    Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
1349    return;
1350  }
1351
1352  // Read struct-declarators until we find the semicolon.
1353  Fields.push_back(FieldDeclarator(DS));
1354  while (1) {
1355    FieldDeclarator &DeclaratorInfo = Fields.back();
1356
1357    /// struct-declarator: declarator
1358    /// struct-declarator: declarator[opt] ':' constant-expression
1359    if (Tok.isNot(tok::colon))
1360      ParseDeclarator(DeclaratorInfo.D);
1361
1362    if (Tok.is(tok::colon)) {
1363      ConsumeToken();
1364      OwningExprResult Res(ParseConstantExpression());
1365      if (Res.isInvalid())
1366        SkipUntil(tok::semi, true, true);
1367      else
1368        DeclaratorInfo.BitfieldSize = Res.release();
1369    }
1370
1371    // If attributes exist after the declarator, parse them.
1372    if (Tok.is(tok::kw___attribute)) {
1373      SourceLocation Loc;
1374      AttributeList *AttrList = ParseAttributes(&Loc);
1375      DeclaratorInfo.D.AddAttributes(AttrList, Loc);
1376    }
1377
1378    // If we don't have a comma, it is either the end of the list (a ';')
1379    // or an error, bail out.
1380    if (Tok.isNot(tok::comma))
1381      return;
1382
1383    // Consume the comma.
1384    ConsumeToken();
1385
1386    // Parse the next declarator.
1387    Fields.push_back(FieldDeclarator(DS));
1388
1389    // Attributes are only allowed on the second declarator.
1390    if (Tok.is(tok::kw___attribute)) {
1391      SourceLocation Loc;
1392      AttributeList *AttrList = ParseAttributes(&Loc);
1393      Fields.back().D.AddAttributes(AttrList, Loc);
1394    }
1395  }
1396}
1397
1398/// ParseStructUnionBody
1399///       struct-contents:
1400///         struct-declaration-list
1401/// [EXT]   empty
1402/// [GNU]   "struct-declaration-list" without terminatoring ';'
1403///       struct-declaration-list:
1404///         struct-declaration
1405///         struct-declaration-list struct-declaration
1406/// [OBC]   '@' 'defs' '(' class-name ')'
1407///
1408void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
1409                                  unsigned TagType, DeclPtrTy TagDecl) {
1410  PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions,
1411                                        PP.getSourceManager(),
1412                                        "parsing struct/union body");
1413
1414  SourceLocation LBraceLoc = ConsumeBrace();
1415
1416  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
1417  Actions.ActOnTagStartDefinition(CurScope, TagDecl);
1418
1419  // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
1420  // C++.
1421  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1422    Diag(Tok, diag::ext_empty_struct_union_enum)
1423      << DeclSpec::getSpecifierName((DeclSpec::TST)TagType);
1424
1425  llvm::SmallVector<DeclPtrTy, 32> FieldDecls;
1426  llvm::SmallVector<FieldDeclarator, 8> FieldDeclarators;
1427
1428  // While we still have something to read, read the declarations in the struct.
1429  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1430    // Each iteration of this loop reads one struct-declaration.
1431
1432    // Check for extraneous top-level semicolon.
1433    if (Tok.is(tok::semi)) {
1434      Diag(Tok, diag::ext_extra_struct_semi)
1435        << CodeModificationHint::CreateRemoval(SourceRange(Tok.getLocation()));
1436      ConsumeToken();
1437      continue;
1438    }
1439
1440    // Parse all the comma separated declarators.
1441    DeclSpec DS;
1442    FieldDeclarators.clear();
1443    if (!Tok.is(tok::at)) {
1444      ParseStructDeclaration(DS, FieldDeclarators);
1445
1446      // Convert them all to fields.
1447      for (unsigned i = 0, e = FieldDeclarators.size(); i != e; ++i) {
1448        FieldDeclarator &FD = FieldDeclarators[i];
1449        // Install the declarator into the current TagDecl.
1450        DeclPtrTy Field = Actions.ActOnField(CurScope, TagDecl,
1451                                             DS.getSourceRange().getBegin(),
1452                                             FD.D, FD.BitfieldSize);
1453        FieldDecls.push_back(Field);
1454      }
1455    } else { // Handle @defs
1456      ConsumeToken();
1457      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
1458        Diag(Tok, diag::err_unexpected_at);
1459        SkipUntil(tok::semi, true, true);
1460        continue;
1461      }
1462      ConsumeToken();
1463      ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
1464      if (!Tok.is(tok::identifier)) {
1465        Diag(Tok, diag::err_expected_ident);
1466        SkipUntil(tok::semi, true, true);
1467        continue;
1468      }
1469      llvm::SmallVector<DeclPtrTy, 16> Fields;
1470      Actions.ActOnDefs(CurScope, TagDecl, Tok.getLocation(),
1471                        Tok.getIdentifierInfo(), Fields);
1472      FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
1473      ConsumeToken();
1474      ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
1475    }
1476
1477    if (Tok.is(tok::semi)) {
1478      ConsumeToken();
1479    } else if (Tok.is(tok::r_brace)) {
1480      Diag(Tok, diag::ext_expected_semi_decl_list);
1481      break;
1482    } else {
1483      Diag(Tok, diag::err_expected_semi_decl_list);
1484      // Skip to end of block or statement
1485      SkipUntil(tok::r_brace, true, true);
1486    }
1487  }
1488
1489  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1490
1491  AttributeList *AttrList = 0;
1492  // If attributes exist after struct contents, parse them.
1493  if (Tok.is(tok::kw___attribute))
1494    AttrList = ParseAttributes();
1495
1496  Actions.ActOnFields(CurScope,
1497                      RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(),
1498                      LBraceLoc, RBraceLoc,
1499                      AttrList);
1500  StructScope.Exit();
1501  Actions.ActOnTagFinishDefinition(CurScope, TagDecl);
1502}
1503
1504
1505/// ParseEnumSpecifier
1506///       enum-specifier: [C99 6.7.2.2]
1507///         'enum' identifier[opt] '{' enumerator-list '}'
1508///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
1509/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
1510///                                                 '}' attributes[opt]
1511///         'enum' identifier
1512/// [GNU]   'enum' attributes[opt] identifier
1513///
1514/// [C++] elaborated-type-specifier:
1515/// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
1516///
1517void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
1518                                AccessSpecifier AS) {
1519  // Parse the tag portion of this.
1520
1521  AttributeList *Attr = 0;
1522  // If attributes exist after tag, parse them.
1523  if (Tok.is(tok::kw___attribute))
1524    Attr = ParseAttributes();
1525
1526  CXXScopeSpec SS;
1527  if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS)) {
1528    if (Tok.isNot(tok::identifier)) {
1529      Diag(Tok, diag::err_expected_ident);
1530      if (Tok.isNot(tok::l_brace)) {
1531        // Has no name and is not a definition.
1532        // Skip the rest of this declarator, up until the comma or semicolon.
1533        SkipUntil(tok::comma, true);
1534        return;
1535      }
1536    }
1537  }
1538
1539  // Must have either 'enum name' or 'enum {...}'.
1540  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) {
1541    Diag(Tok, diag::err_expected_ident_lbrace);
1542
1543    // Skip the rest of this declarator, up until the comma or semicolon.
1544    SkipUntil(tok::comma, true);
1545    return;
1546  }
1547
1548  // If an identifier is present, consume and remember it.
1549  IdentifierInfo *Name = 0;
1550  SourceLocation NameLoc;
1551  if (Tok.is(tok::identifier)) {
1552    Name = Tok.getIdentifierInfo();
1553    NameLoc = ConsumeToken();
1554  }
1555
1556  // There are three options here.  If we have 'enum foo;', then this is a
1557  // forward declaration.  If we have 'enum foo {...' then this is a
1558  // definition. Otherwise we have something like 'enum foo xyz', a reference.
1559  //
1560  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
1561  // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
1562  // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
1563  //
1564  Action::TagKind TK;
1565  if (Tok.is(tok::l_brace))
1566    TK = Action::TK_Definition;
1567  else if (Tok.is(tok::semi))
1568    TK = Action::TK_Declaration;
1569  else
1570    TK = Action::TK_Reference;
1571  bool Owned = false;
1572  DeclPtrTy TagDecl = Actions.ActOnTag(CurScope, DeclSpec::TST_enum, TK,
1573                                       StartLoc, SS, Name, NameLoc, Attr, AS,
1574                                       Owned);
1575
1576  if (Tok.is(tok::l_brace))
1577    ParseEnumBody(StartLoc, TagDecl);
1578
1579  // TODO: semantic analysis on the declspec for enums.
1580  const char *PrevSpec = 0;
1581  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, PrevSpec,
1582                         TagDecl.getAs<void>(), Owned))
1583    Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
1584}
1585
1586/// ParseEnumBody - Parse a {} enclosed enumerator-list.
1587///       enumerator-list:
1588///         enumerator
1589///         enumerator-list ',' enumerator
1590///       enumerator:
1591///         enumeration-constant
1592///         enumeration-constant '=' constant-expression
1593///       enumeration-constant:
1594///         identifier
1595///
1596void Parser::ParseEnumBody(SourceLocation StartLoc, DeclPtrTy EnumDecl) {
1597  // Enter the scope of the enum body and start the definition.
1598  ParseScope EnumScope(this, Scope::DeclScope);
1599  Actions.ActOnTagStartDefinition(CurScope, EnumDecl);
1600
1601  SourceLocation LBraceLoc = ConsumeBrace();
1602
1603  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
1604  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1605    Diag(Tok, diag::ext_empty_struct_union_enum) << "enum";
1606
1607  llvm::SmallVector<DeclPtrTy, 32> EnumConstantDecls;
1608
1609  DeclPtrTy LastEnumConstDecl;
1610
1611  // Parse the enumerator-list.
1612  while (Tok.is(tok::identifier)) {
1613    IdentifierInfo *Ident = Tok.getIdentifierInfo();
1614    SourceLocation IdentLoc = ConsumeToken();
1615
1616    SourceLocation EqualLoc;
1617    OwningExprResult AssignedVal(Actions);
1618    if (Tok.is(tok::equal)) {
1619      EqualLoc = ConsumeToken();
1620      AssignedVal = ParseConstantExpression();
1621      if (AssignedVal.isInvalid())
1622        SkipUntil(tok::comma, tok::r_brace, true, true);
1623    }
1624
1625    // Install the enumerator constant into EnumDecl.
1626    DeclPtrTy EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl,
1627                                                        LastEnumConstDecl,
1628                                                        IdentLoc, Ident,
1629                                                        EqualLoc,
1630                                                        AssignedVal.release());
1631    EnumConstantDecls.push_back(EnumConstDecl);
1632    LastEnumConstDecl = EnumConstDecl;
1633
1634    if (Tok.isNot(tok::comma))
1635      break;
1636    SourceLocation CommaLoc = ConsumeToken();
1637
1638    if (Tok.isNot(tok::identifier) &&
1639        !(getLang().C99 || getLang().CPlusPlus0x))
1640      Diag(CommaLoc, diag::ext_enumerator_list_comma)
1641        << getLang().CPlusPlus
1642        << CodeModificationHint::CreateRemoval((SourceRange(CommaLoc)));
1643  }
1644
1645  // Eat the }.
1646  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1647
1648  Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl,
1649                        EnumConstantDecls.data(), EnumConstantDecls.size());
1650
1651  Action::AttrTy *AttrList = 0;
1652  // If attributes exist after the identifier list, parse them.
1653  if (Tok.is(tok::kw___attribute))
1654    AttrList = ParseAttributes(); // FIXME: where do they do?
1655
1656  EnumScope.Exit();
1657  Actions.ActOnTagFinishDefinition(CurScope, EnumDecl);
1658}
1659
1660/// isTypeSpecifierQualifier - Return true if the current token could be the
1661/// start of a type-qualifier-list.
1662bool Parser::isTypeQualifier() const {
1663  switch (Tok.getKind()) {
1664  default: return false;
1665    // type-qualifier
1666  case tok::kw_const:
1667  case tok::kw_volatile:
1668  case tok::kw_restrict:
1669    return true;
1670  }
1671}
1672
1673/// isTypeSpecifierQualifier - Return true if the current token could be the
1674/// start of a specifier-qualifier-list.
1675bool Parser::isTypeSpecifierQualifier() {
1676  switch (Tok.getKind()) {
1677  default: return false;
1678
1679  case tok::identifier:   // foo::bar
1680  case tok::kw_typename:  // typename T::type
1681    // Annotate typenames and C++ scope specifiers.  If we get one, just
1682    // recurse to handle whatever we get.
1683    if (TryAnnotateTypeOrScopeToken())
1684      return isTypeSpecifierQualifier();
1685    // Otherwise, not a type specifier.
1686    return false;
1687
1688  case tok::coloncolon:   // ::foo::bar
1689    if (NextToken().is(tok::kw_new) ||    // ::new
1690        NextToken().is(tok::kw_delete))   // ::delete
1691      return false;
1692
1693    // Annotate typenames and C++ scope specifiers.  If we get one, just
1694    // recurse to handle whatever we get.
1695    if (TryAnnotateTypeOrScopeToken())
1696      return isTypeSpecifierQualifier();
1697    // Otherwise, not a type specifier.
1698    return false;
1699
1700    // GNU attributes support.
1701  case tok::kw___attribute:
1702    // GNU typeof support.
1703  case tok::kw_typeof:
1704
1705    // type-specifiers
1706  case tok::kw_short:
1707  case tok::kw_long:
1708  case tok::kw_signed:
1709  case tok::kw_unsigned:
1710  case tok::kw__Complex:
1711  case tok::kw__Imaginary:
1712  case tok::kw_void:
1713  case tok::kw_char:
1714  case tok::kw_wchar_t:
1715  case tok::kw_int:
1716  case tok::kw_float:
1717  case tok::kw_double:
1718  case tok::kw_bool:
1719  case tok::kw__Bool:
1720  case tok::kw__Decimal32:
1721  case tok::kw__Decimal64:
1722  case tok::kw__Decimal128:
1723
1724    // struct-or-union-specifier (C99) or class-specifier (C++)
1725  case tok::kw_class:
1726  case tok::kw_struct:
1727  case tok::kw_union:
1728    // enum-specifier
1729  case tok::kw_enum:
1730
1731    // type-qualifier
1732  case tok::kw_const:
1733  case tok::kw_volatile:
1734  case tok::kw_restrict:
1735
1736    // typedef-name
1737  case tok::annot_typename:
1738    return true;
1739
1740    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
1741  case tok::less:
1742    return getLang().ObjC1;
1743
1744  case tok::kw___cdecl:
1745  case tok::kw___stdcall:
1746  case tok::kw___fastcall:
1747  case tok::kw___w64:
1748  case tok::kw___ptr64:
1749    return true;
1750  }
1751}
1752
1753/// isDeclarationSpecifier() - Return true if the current token is part of a
1754/// declaration specifier.
1755bool Parser::isDeclarationSpecifier() {
1756  switch (Tok.getKind()) {
1757  default: return false;
1758
1759  case tok::identifier:   // foo::bar
1760    // Unfortunate hack to support "Class.factoryMethod" notation.
1761    if (getLang().ObjC1 && NextToken().is(tok::period))
1762      return false;
1763    // Fall through
1764
1765  case tok::kw_typename: // typename T::type
1766    // Annotate typenames and C++ scope specifiers.  If we get one, just
1767    // recurse to handle whatever we get.
1768    if (TryAnnotateTypeOrScopeToken())
1769      return isDeclarationSpecifier();
1770    // Otherwise, not a declaration specifier.
1771    return false;
1772  case tok::coloncolon:   // ::foo::bar
1773    if (NextToken().is(tok::kw_new) ||    // ::new
1774        NextToken().is(tok::kw_delete))   // ::delete
1775      return false;
1776
1777    // Annotate typenames and C++ scope specifiers.  If we get one, just
1778    // recurse to handle whatever we get.
1779    if (TryAnnotateTypeOrScopeToken())
1780      return isDeclarationSpecifier();
1781    // Otherwise, not a declaration specifier.
1782    return false;
1783
1784    // storage-class-specifier
1785  case tok::kw_typedef:
1786  case tok::kw_extern:
1787  case tok::kw___private_extern__:
1788  case tok::kw_static:
1789  case tok::kw_auto:
1790  case tok::kw_register:
1791  case tok::kw___thread:
1792
1793    // type-specifiers
1794  case tok::kw_short:
1795  case tok::kw_long:
1796  case tok::kw_signed:
1797  case tok::kw_unsigned:
1798  case tok::kw__Complex:
1799  case tok::kw__Imaginary:
1800  case tok::kw_void:
1801  case tok::kw_char:
1802  case tok::kw_wchar_t:
1803  case tok::kw_int:
1804  case tok::kw_float:
1805  case tok::kw_double:
1806  case tok::kw_bool:
1807  case tok::kw__Bool:
1808  case tok::kw__Decimal32:
1809  case tok::kw__Decimal64:
1810  case tok::kw__Decimal128:
1811
1812    // struct-or-union-specifier (C99) or class-specifier (C++)
1813  case tok::kw_class:
1814  case tok::kw_struct:
1815  case tok::kw_union:
1816    // enum-specifier
1817  case tok::kw_enum:
1818
1819    // type-qualifier
1820  case tok::kw_const:
1821  case tok::kw_volatile:
1822  case tok::kw_restrict:
1823
1824    // function-specifier
1825  case tok::kw_inline:
1826  case tok::kw_virtual:
1827  case tok::kw_explicit:
1828
1829    // typedef-name
1830  case tok::annot_typename:
1831
1832    // GNU typeof support.
1833  case tok::kw_typeof:
1834
1835    // GNU attributes.
1836  case tok::kw___attribute:
1837    return true;
1838
1839    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
1840  case tok::less:
1841    return getLang().ObjC1;
1842
1843  case tok::kw___declspec:
1844  case tok::kw___cdecl:
1845  case tok::kw___stdcall:
1846  case tok::kw___fastcall:
1847  case tok::kw___w64:
1848  case tok::kw___ptr64:
1849  case tok::kw___forceinline:
1850    return true;
1851  }
1852}
1853
1854
1855/// ParseTypeQualifierListOpt
1856///       type-qualifier-list: [C99 6.7.5]
1857///         type-qualifier
1858/// [GNU]   attributes                        [ only if AttributesAllowed=true ]
1859///         type-qualifier-list type-qualifier
1860/// [GNU]   type-qualifier-list attributes    [ only if AttributesAllowed=true ]
1861///
1862void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, bool AttributesAllowed) {
1863  while (1) {
1864    int isInvalid = false;
1865    const char *PrevSpec = 0;
1866    SourceLocation Loc = Tok.getLocation();
1867
1868    switch (Tok.getKind()) {
1869    case tok::kw_const:
1870      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
1871                                 getLang())*2;
1872      break;
1873    case tok::kw_volatile:
1874      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
1875                                 getLang())*2;
1876      break;
1877    case tok::kw_restrict:
1878      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1879                                 getLang())*2;
1880      break;
1881    case tok::kw___w64:
1882    case tok::kw___ptr64:
1883    case tok::kw___cdecl:
1884    case tok::kw___stdcall:
1885    case tok::kw___fastcall:
1886      if (AttributesAllowed) {
1887        DS.AddAttributes(ParseMicrosoftTypeAttributes());
1888        continue;
1889      }
1890      goto DoneWithTypeQuals;
1891    case tok::kw___attribute:
1892      if (AttributesAllowed) {
1893        DS.AddAttributes(ParseAttributes());
1894        continue; // do *not* consume the next token!
1895      }
1896      // otherwise, FALL THROUGH!
1897    default:
1898      DoneWithTypeQuals:
1899      // If this is not a type-qualifier token, we're done reading type
1900      // qualifiers.  First verify that DeclSpec's are consistent.
1901      DS.Finish(Diags, PP);
1902      return;
1903    }
1904
1905    // If the specifier combination wasn't legal, issue a diagnostic.
1906    if (isInvalid) {
1907      assert(PrevSpec && "Method did not return previous specifier!");
1908      // Pick between error or extwarn.
1909      unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination
1910                                      : diag::ext_duplicate_declspec;
1911      Diag(Tok, DiagID) << PrevSpec;
1912    }
1913    ConsumeToken();
1914  }
1915}
1916
1917
1918/// ParseDeclarator - Parse and verify a newly-initialized declarator.
1919///
1920void Parser::ParseDeclarator(Declarator &D) {
1921  /// This implements the 'declarator' production in the C grammar, then checks
1922  /// for well-formedness and issues diagnostics.
1923  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
1924}
1925
1926/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
1927/// is parsed by the function passed to it. Pass null, and the direct-declarator
1928/// isn't parsed at all, making this function effectively parse the C++
1929/// ptr-operator production.
1930///
1931///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
1932/// [C]     pointer[opt] direct-declarator
1933/// [C++]   direct-declarator
1934/// [C++]   ptr-operator declarator
1935///
1936///       pointer: [C99 6.7.5]
1937///         '*' type-qualifier-list[opt]
1938///         '*' type-qualifier-list[opt] pointer
1939///
1940///       ptr-operator:
1941///         '*' cv-qualifier-seq[opt]
1942///         '&'
1943/// [C++0x] '&&'
1944/// [GNU]   '&' restrict[opt] attributes[opt]
1945/// [GNU?]  '&&' restrict[opt] attributes[opt]
1946///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
1947void Parser::ParseDeclaratorInternal(Declarator &D,
1948                                     DirectDeclParseFunction DirectDeclParser) {
1949
1950  // C++ member pointers start with a '::' or a nested-name.
1951  // Member pointers get special handling, since there's no place for the
1952  // scope spec in the generic path below.
1953  if (getLang().CPlusPlus &&
1954      (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
1955       Tok.is(tok::annot_cxxscope))) {
1956    CXXScopeSpec SS;
1957    if (ParseOptionalCXXScopeSpecifier(SS)) {
1958      if(Tok.isNot(tok::star)) {
1959        // The scope spec really belongs to the direct-declarator.
1960        D.getCXXScopeSpec() = SS;
1961        if (DirectDeclParser)
1962          (this->*DirectDeclParser)(D);
1963        return;
1964      }
1965
1966      SourceLocation Loc = ConsumeToken();
1967      D.SetRangeEnd(Loc);
1968      DeclSpec DS;
1969      ParseTypeQualifierListOpt(DS);
1970      D.ExtendWithDeclSpec(DS);
1971
1972      // Recurse to parse whatever is left.
1973      ParseDeclaratorInternal(D, DirectDeclParser);
1974
1975      // Sema will have to catch (syntactically invalid) pointers into global
1976      // scope. It has to catch pointers into namespace scope anyway.
1977      D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
1978                                                      Loc, DS.TakeAttributes()),
1979                    /* Don't replace range end. */SourceLocation());
1980      return;
1981    }
1982  }
1983
1984  tok::TokenKind Kind = Tok.getKind();
1985  // Not a pointer, C++ reference, or block.
1986  if (Kind != tok::star && Kind != tok::caret &&
1987      (Kind != tok::amp || !getLang().CPlusPlus) &&
1988      // We parse rvalue refs in C++03, because otherwise the errors are scary.
1989      (Kind != tok::ampamp || !getLang().CPlusPlus)) {
1990    if (DirectDeclParser)
1991      (this->*DirectDeclParser)(D);
1992    return;
1993  }
1994
1995  // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
1996  // '&&' -> rvalue reference
1997  SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
1998  D.SetRangeEnd(Loc);
1999
2000  if (Kind == tok::star || Kind == tok::caret) {
2001    // Is a pointer.
2002    DeclSpec DS;
2003
2004    ParseTypeQualifierListOpt(DS);
2005    D.ExtendWithDeclSpec(DS);
2006
2007    // Recursively parse the declarator.
2008    ParseDeclaratorInternal(D, DirectDeclParser);
2009    if (Kind == tok::star)
2010      // Remember that we parsed a pointer type, and remember the type-quals.
2011      D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
2012                                                DS.TakeAttributes()),
2013                    SourceLocation());
2014    else
2015      // Remember that we parsed a Block type, and remember the type-quals.
2016      D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
2017                                                     Loc, DS.TakeAttributes()),
2018                    SourceLocation());
2019  } else {
2020    // Is a reference
2021    DeclSpec DS;
2022
2023    // Complain about rvalue references in C++03, but then go on and build
2024    // the declarator.
2025    if (Kind == tok::ampamp && !getLang().CPlusPlus0x)
2026      Diag(Loc, diag::err_rvalue_reference);
2027
2028    // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
2029    // cv-qualifiers are introduced through the use of a typedef or of a
2030    // template type argument, in which case the cv-qualifiers are ignored.
2031    //
2032    // [GNU] Retricted references are allowed.
2033    // [GNU] Attributes on references are allowed.
2034    ParseTypeQualifierListOpt(DS);
2035    D.ExtendWithDeclSpec(DS);
2036
2037    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2038      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2039        Diag(DS.getConstSpecLoc(),
2040             diag::err_invalid_reference_qualifier_application) << "const";
2041      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2042        Diag(DS.getVolatileSpecLoc(),
2043             diag::err_invalid_reference_qualifier_application) << "volatile";
2044    }
2045
2046    // Recursively parse the declarator.
2047    ParseDeclaratorInternal(D, DirectDeclParser);
2048
2049    if (D.getNumTypeObjects() > 0) {
2050      // C++ [dcl.ref]p4: There shall be no references to references.
2051      DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
2052      if (InnerChunk.Kind == DeclaratorChunk::Reference) {
2053        if (const IdentifierInfo *II = D.getIdentifier())
2054          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
2055           << II;
2056        else
2057          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
2058            << "type name";
2059
2060        // Once we've complained about the reference-to-reference, we
2061        // can go ahead and build the (technically ill-formed)
2062        // declarator: reference collapsing will take care of it.
2063      }
2064    }
2065
2066    // Remember that we parsed a reference type. It doesn't have type-quals.
2067    D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
2068                                                DS.TakeAttributes(),
2069                                                Kind == tok::amp),
2070                  SourceLocation());
2071  }
2072}
2073
2074/// ParseDirectDeclarator
2075///       direct-declarator: [C99 6.7.5]
2076/// [C99]   identifier
2077///         '(' declarator ')'
2078/// [GNU]   '(' attributes declarator ')'
2079/// [C90]   direct-declarator '[' constant-expression[opt] ']'
2080/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2081/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2082/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2083/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
2084///         direct-declarator '(' parameter-type-list ')'
2085///         direct-declarator '(' identifier-list[opt] ')'
2086/// [GNU]   direct-declarator '(' parameter-forward-declarations
2087///                    parameter-type-list[opt] ')'
2088/// [C++]   direct-declarator '(' parameter-declaration-clause ')'
2089///                    cv-qualifier-seq[opt] exception-specification[opt]
2090/// [C++]   declarator-id
2091///
2092///       declarator-id: [C++ 8]
2093///         id-expression
2094///         '::'[opt] nested-name-specifier[opt] type-name
2095///
2096///       id-expression: [C++ 5.1]
2097///         unqualified-id
2098///         qualified-id            [TODO]
2099///
2100///       unqualified-id: [C++ 5.1]
2101///         identifier
2102///         operator-function-id
2103///         conversion-function-id  [TODO]
2104///          '~' class-name
2105///         template-id
2106///
2107void Parser::ParseDirectDeclarator(Declarator &D) {
2108  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
2109
2110  if (getLang().CPlusPlus) {
2111    if (D.mayHaveIdentifier()) {
2112      // ParseDeclaratorInternal might already have parsed the scope.
2113      bool afterCXXScope = D.getCXXScopeSpec().isSet() ||
2114        ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec());
2115      if (afterCXXScope) {
2116        // Change the declaration context for name lookup, until this function
2117        // is exited (and the declarator has been parsed).
2118        DeclScopeObj.EnterDeclaratorScope();
2119      }
2120
2121      if (Tok.is(tok::identifier)) {
2122        assert(Tok.getIdentifierInfo() && "Not an identifier?");
2123
2124        // If this identifier is the name of the current class, it's a
2125        // constructor name.
2126        if (!D.getDeclSpec().hasTypeSpecifier() &&
2127            Actions.isCurrentClassName(*Tok.getIdentifierInfo(),CurScope)) {
2128          CXXScopeSpec *SS = afterCXXScope? &D.getCXXScopeSpec() : 0;
2129          D.setConstructor(Actions.getTypeName(*Tok.getIdentifierInfo(),
2130                                               Tok.getLocation(), CurScope, SS),
2131                           Tok.getLocation());
2132        // This is a normal identifier.
2133        } else
2134          D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2135        ConsumeToken();
2136        goto PastIdentifier;
2137      } else if (Tok.is(tok::annot_template_id)) {
2138        TemplateIdAnnotation *TemplateId
2139          = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
2140
2141        // FIXME: Could this template-id name a constructor?
2142
2143        // FIXME: This is an egregious hack, where we silently ignore
2144        // the specialization (which should be a function template
2145        // specialization name) and use the name instead. This hack
2146        // will go away when we have support for function
2147        // specializations.
2148        D.SetIdentifier(TemplateId->Name, Tok.getLocation());
2149        TemplateId->Destroy();
2150        ConsumeToken();
2151        goto PastIdentifier;
2152      } else if (Tok.is(tok::kw_operator)) {
2153        SourceLocation OperatorLoc = Tok.getLocation();
2154        SourceLocation EndLoc;
2155
2156        // First try the name of an overloaded operator
2157        if (OverloadedOperatorKind Op = TryParseOperatorFunctionId(&EndLoc)) {
2158          D.setOverloadedOperator(Op, OperatorLoc, EndLoc);
2159        } else {
2160          // This must be a conversion function (C++ [class.conv.fct]).
2161          if (TypeTy *ConvType = ParseConversionFunctionId(&EndLoc))
2162            D.setConversionFunction(ConvType, OperatorLoc, EndLoc);
2163          else {
2164            D.SetIdentifier(0, Tok.getLocation());
2165          }
2166        }
2167        goto PastIdentifier;
2168      } else if (Tok.is(tok::tilde)) {
2169        // This should be a C++ destructor.
2170        SourceLocation TildeLoc = ConsumeToken();
2171        if (Tok.is(tok::identifier)) {
2172          // FIXME: Inaccurate.
2173          SourceLocation NameLoc = Tok.getLocation();
2174          SourceLocation EndLoc;
2175          CXXScopeSpec *SS = afterCXXScope? &D.getCXXScopeSpec() : 0;
2176          TypeResult Type = ParseClassName(EndLoc, SS);
2177          if (Type.isInvalid())
2178            D.SetIdentifier(0, TildeLoc);
2179          else
2180            D.setDestructor(Type.get(), TildeLoc, NameLoc);
2181        } else {
2182          Diag(Tok, diag::err_expected_class_name);
2183          D.SetIdentifier(0, TildeLoc);
2184        }
2185        goto PastIdentifier;
2186      }
2187
2188      // If we reached this point, token is not identifier and not '~'.
2189
2190      if (afterCXXScope) {
2191        Diag(Tok, diag::err_expected_unqualified_id);
2192        D.SetIdentifier(0, Tok.getLocation());
2193        D.setInvalidType(true);
2194        goto PastIdentifier;
2195      }
2196    }
2197  }
2198
2199  // If we reached this point, we are either in C/ObjC or the token didn't
2200  // satisfy any of the C++-specific checks.
2201  if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
2202    assert(!getLang().CPlusPlus &&
2203           "There's a C++-specific check for tok::identifier above");
2204    assert(Tok.getIdentifierInfo() && "Not an identifier?");
2205    D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2206    ConsumeToken();
2207  } else if (Tok.is(tok::l_paren)) {
2208    // direct-declarator: '(' declarator ')'
2209    // direct-declarator: '(' attributes declarator ')'
2210    // Example: 'char (*X)'   or 'int (*XX)(void)'
2211    ParseParenDeclarator(D);
2212  } else if (D.mayOmitIdentifier()) {
2213    // This could be something simple like "int" (in which case the declarator
2214    // portion is empty), if an abstract-declarator is allowed.
2215    D.SetIdentifier(0, Tok.getLocation());
2216  } else {
2217    if (D.getContext() == Declarator::MemberContext)
2218      Diag(Tok, diag::err_expected_member_name_or_semi)
2219        << D.getDeclSpec().getSourceRange();
2220    else if (getLang().CPlusPlus)
2221      Diag(Tok, diag::err_expected_unqualified_id);
2222    else
2223      Diag(Tok, diag::err_expected_ident_lparen);
2224    D.SetIdentifier(0, Tok.getLocation());
2225    D.setInvalidType(true);
2226  }
2227
2228 PastIdentifier:
2229  assert(D.isPastIdentifier() &&
2230         "Haven't past the location of the identifier yet?");
2231
2232  while (1) {
2233    if (Tok.is(tok::l_paren)) {
2234      // The paren may be part of a C++ direct initializer, eg. "int x(1);".
2235      // In such a case, check if we actually have a function declarator; if it
2236      // is not, the declarator has been fully parsed.
2237      if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
2238        // When not in file scope, warn for ambiguous function declarators, just
2239        // in case the author intended it as a variable definition.
2240        bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
2241        if (!isCXXFunctionDeclarator(warnIfAmbiguous))
2242          break;
2243      }
2244      ParseFunctionDeclarator(ConsumeParen(), D);
2245    } else if (Tok.is(tok::l_square)) {
2246      ParseBracketDeclarator(D);
2247    } else {
2248      break;
2249    }
2250  }
2251}
2252
2253/// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
2254/// only called before the identifier, so these are most likely just grouping
2255/// parens for precedence.  If we find that these are actually function
2256/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
2257///
2258///       direct-declarator:
2259///         '(' declarator ')'
2260/// [GNU]   '(' attributes declarator ')'
2261///         direct-declarator '(' parameter-type-list ')'
2262///         direct-declarator '(' identifier-list[opt] ')'
2263/// [GNU]   direct-declarator '(' parameter-forward-declarations
2264///                    parameter-type-list[opt] ')'
2265///
2266void Parser::ParseParenDeclarator(Declarator &D) {
2267  SourceLocation StartLoc = ConsumeParen();
2268  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
2269
2270  // Eat any attributes before we look at whether this is a grouping or function
2271  // declarator paren.  If this is a grouping paren, the attribute applies to
2272  // the type being built up, for example:
2273  //     int (__attribute__(()) *x)(long y)
2274  // If this ends up not being a grouping paren, the attribute applies to the
2275  // first argument, for example:
2276  //     int (__attribute__(()) int x)
2277  // In either case, we need to eat any attributes to be able to determine what
2278  // sort of paren this is.
2279  //
2280  AttributeList *AttrList = 0;
2281  bool RequiresArg = false;
2282  if (Tok.is(tok::kw___attribute)) {
2283    AttrList = ParseAttributes();
2284
2285    // We require that the argument list (if this is a non-grouping paren) be
2286    // present even if the attribute list was empty.
2287    RequiresArg = true;
2288  }
2289  // Eat any Microsoft extensions.
2290  if  (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
2291       Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___w64) ||
2292       Tok.is(tok::kw___ptr64)) {
2293    AttrList = ParseMicrosoftTypeAttributes(AttrList);
2294  }
2295
2296  // If we haven't past the identifier yet (or where the identifier would be
2297  // stored, if this is an abstract declarator), then this is probably just
2298  // grouping parens. However, if this could be an abstract-declarator, then
2299  // this could also be the start of function arguments (consider 'void()').
2300  bool isGrouping;
2301
2302  if (!D.mayOmitIdentifier()) {
2303    // If this can't be an abstract-declarator, this *must* be a grouping
2304    // paren, because we haven't seen the identifier yet.
2305    isGrouping = true;
2306  } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
2307             (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
2308             isDeclarationSpecifier()) {       // 'int(int)' is a function.
2309    // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
2310    // considered to be a type, not a K&R identifier-list.
2311    isGrouping = false;
2312  } else {
2313    // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
2314    isGrouping = true;
2315  }
2316
2317  // If this is a grouping paren, handle:
2318  // direct-declarator: '(' declarator ')'
2319  // direct-declarator: '(' attributes declarator ')'
2320  if (isGrouping) {
2321    bool hadGroupingParens = D.hasGroupingParens();
2322    D.setGroupingParens(true);
2323    if (AttrList)
2324      D.AddAttributes(AttrList, SourceLocation());
2325
2326    ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
2327    // Match the ')'.
2328    SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, StartLoc);
2329
2330    D.setGroupingParens(hadGroupingParens);
2331    D.SetRangeEnd(Loc);
2332    return;
2333  }
2334
2335  // Okay, if this wasn't a grouping paren, it must be the start of a function
2336  // argument list.  Recognize that this declarator will never have an
2337  // identifier (and remember where it would have been), then call into
2338  // ParseFunctionDeclarator to handle of argument list.
2339  D.SetIdentifier(0, Tok.getLocation());
2340
2341  ParseFunctionDeclarator(StartLoc, D, AttrList, RequiresArg);
2342}
2343
2344/// ParseFunctionDeclarator - We are after the identifier and have parsed the
2345/// declarator D up to a paren, which indicates that we are parsing function
2346/// arguments.
2347///
2348/// If AttrList is non-null, then the caller parsed those arguments immediately
2349/// after the open paren - they should be considered to be the first argument of
2350/// a parameter.  If RequiresArg is true, then the first argument of the
2351/// function is required to be present and required to not be an identifier
2352/// list.
2353///
2354/// This method also handles this portion of the grammar:
2355///       parameter-type-list: [C99 6.7.5]
2356///         parameter-list
2357///         parameter-list ',' '...'
2358///
2359///       parameter-list: [C99 6.7.5]
2360///         parameter-declaration
2361///         parameter-list ',' parameter-declaration
2362///
2363///       parameter-declaration: [C99 6.7.5]
2364///         declaration-specifiers declarator
2365/// [C++]   declaration-specifiers declarator '=' assignment-expression
2366/// [GNU]   declaration-specifiers declarator attributes
2367///         declaration-specifiers abstract-declarator[opt]
2368/// [C++]   declaration-specifiers abstract-declarator[opt]
2369///           '=' assignment-expression
2370/// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
2371///
2372/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]"
2373/// and "exception-specification[opt]".
2374///
2375void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
2376                                     AttributeList *AttrList,
2377                                     bool RequiresArg) {
2378  // lparen is already consumed!
2379  assert(D.isPastIdentifier() && "Should not call before identifier!");
2380
2381  // This parameter list may be empty.
2382  if (Tok.is(tok::r_paren)) {
2383    if (RequiresArg) {
2384      Diag(Tok, diag::err_argument_required_after_attribute);
2385      delete AttrList;
2386    }
2387
2388    SourceLocation Loc = ConsumeParen();  // Eat the closing ')'.
2389
2390    // cv-qualifier-seq[opt].
2391    DeclSpec DS;
2392    bool hasExceptionSpec = false;
2393    SourceLocation ThrowLoc;
2394    bool hasAnyExceptionSpec = false;
2395    llvm::SmallVector<TypeTy*, 2> Exceptions;
2396    llvm::SmallVector<SourceRange, 2> ExceptionRanges;
2397    if (getLang().CPlusPlus) {
2398      ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2399      if (!DS.getSourceRange().getEnd().isInvalid())
2400        Loc = DS.getSourceRange().getEnd();
2401
2402      // Parse exception-specification[opt].
2403      if (Tok.is(tok::kw_throw)) {
2404        hasExceptionSpec = true;
2405        ThrowLoc = Tok.getLocation();
2406        ParseExceptionSpecification(Loc, Exceptions, ExceptionRanges,
2407                                    hasAnyExceptionSpec);
2408        assert(Exceptions.size() == ExceptionRanges.size() &&
2409               "Produced different number of exception types and ranges.");
2410      }
2411    }
2412
2413    // Remember that we parsed a function type, and remember the attributes.
2414    // int() -> no prototype, no '...'.
2415    D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus,
2416                                               /*variadic*/ false,
2417                                               SourceLocation(),
2418                                               /*arglist*/ 0, 0,
2419                                               DS.getTypeQualifiers(),
2420                                               hasExceptionSpec, ThrowLoc,
2421                                               hasAnyExceptionSpec,
2422                                               Exceptions.data(),
2423                                               ExceptionRanges.data(),
2424                                               Exceptions.size(),
2425                                               LParenLoc, D),
2426                  Loc);
2427    return;
2428  }
2429
2430  // Alternatively, this parameter list may be an identifier list form for a
2431  // K&R-style function:  void foo(a,b,c)
2432  if (!getLang().CPlusPlus && Tok.is(tok::identifier)) {
2433    if (!TryAnnotateTypeOrScopeToken()) {
2434      // K&R identifier lists can't have typedefs as identifiers, per
2435      // C99 6.7.5.3p11.
2436      if (RequiresArg) {
2437        Diag(Tok, diag::err_argument_required_after_attribute);
2438        delete AttrList;
2439      }
2440      // Identifier list.  Note that '(' identifier-list ')' is only allowed for
2441      // normal declarators, not for abstract-declarators.
2442      return ParseFunctionDeclaratorIdentifierList(LParenLoc, D);
2443    }
2444  }
2445
2446  // Finally, a normal, non-empty parameter type list.
2447
2448  // Build up an array of information about the parsed arguments.
2449  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
2450
2451  // Enter function-declaration scope, limiting any declarators to the
2452  // function prototype scope, including parameter declarators.
2453  ParseScope PrototypeScope(this,
2454                            Scope::FunctionPrototypeScope|Scope::DeclScope);
2455
2456  bool IsVariadic = false;
2457  SourceLocation EllipsisLoc;
2458  while (1) {
2459    if (Tok.is(tok::ellipsis)) {
2460      IsVariadic = true;
2461      EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
2462      break;
2463    }
2464
2465    SourceLocation DSStart = Tok.getLocation();
2466
2467    // Parse the declaration-specifiers.
2468    DeclSpec DS;
2469
2470    // If the caller parsed attributes for the first argument, add them now.
2471    if (AttrList) {
2472      DS.AddAttributes(AttrList);
2473      AttrList = 0;  // Only apply the attributes to the first parameter.
2474    }
2475    ParseDeclarationSpecifiers(DS);
2476
2477    // Parse the declarator.  This is "PrototypeContext", because we must
2478    // accept either 'declarator' or 'abstract-declarator' here.
2479    Declarator ParmDecl(DS, Declarator::PrototypeContext);
2480    ParseDeclarator(ParmDecl);
2481
2482    // Parse GNU attributes, if present.
2483    if (Tok.is(tok::kw___attribute)) {
2484      SourceLocation Loc;
2485      AttributeList *AttrList = ParseAttributes(&Loc);
2486      ParmDecl.AddAttributes(AttrList, Loc);
2487    }
2488
2489    // Remember this parsed parameter in ParamInfo.
2490    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
2491
2492    // DefArgToks is used when the parsing of default arguments needs
2493    // to be delayed.
2494    CachedTokens *DefArgToks = 0;
2495
2496    // If no parameter was specified, verify that *something* was specified,
2497    // otherwise we have a missing type and identifier.
2498    if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
2499        ParmDecl.getNumTypeObjects() == 0) {
2500      // Completely missing, emit error.
2501      Diag(DSStart, diag::err_missing_param);
2502    } else {
2503      // Otherwise, we have something.  Add it and let semantic analysis try
2504      // to grok it and add the result to the ParamInfo we are building.
2505
2506      // Inform the actions module about the parameter declarator, so it gets
2507      // added to the current scope.
2508      DeclPtrTy Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl);
2509
2510      // Parse the default argument, if any. We parse the default
2511      // arguments in all dialects; the semantic analysis in
2512      // ActOnParamDefaultArgument will reject the default argument in
2513      // C.
2514      if (Tok.is(tok::equal)) {
2515        SourceLocation EqualLoc = Tok.getLocation();
2516
2517        // Parse the default argument
2518        if (D.getContext() == Declarator::MemberContext) {
2519          // If we're inside a class definition, cache the tokens
2520          // corresponding to the default argument. We'll actually parse
2521          // them when we see the end of the class definition.
2522          // FIXME: Templates will require something similar.
2523          // FIXME: Can we use a smart pointer for Toks?
2524          DefArgToks = new CachedTokens;
2525
2526          if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
2527                                    tok::semi, false)) {
2528            delete DefArgToks;
2529            DefArgToks = 0;
2530            Actions.ActOnParamDefaultArgumentError(Param);
2531          } else
2532            Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
2533                                                (*DefArgToks)[1].getLocation());
2534        } else {
2535          // Consume the '='.
2536          ConsumeToken();
2537
2538          OwningExprResult DefArgResult(ParseAssignmentExpression());
2539          if (DefArgResult.isInvalid()) {
2540            Actions.ActOnParamDefaultArgumentError(Param);
2541            SkipUntil(tok::comma, tok::r_paren, true, true);
2542          } else {
2543            // Inform the actions module about the default argument
2544            Actions.ActOnParamDefaultArgument(Param, EqualLoc,
2545                                              move(DefArgResult));
2546          }
2547        }
2548      }
2549
2550      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
2551                                          ParmDecl.getIdentifierLoc(), Param,
2552                                          DefArgToks));
2553    }
2554
2555    // If the next token is a comma, consume it and keep reading arguments.
2556    if (Tok.isNot(tok::comma)) break;
2557
2558    // Consume the comma.
2559    ConsumeToken();
2560  }
2561
2562  // Leave prototype scope.
2563  PrototypeScope.Exit();
2564
2565  // If we have the closing ')', eat it.
2566  SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2567
2568  DeclSpec DS;
2569  bool hasExceptionSpec = false;
2570  SourceLocation ThrowLoc;
2571  bool hasAnyExceptionSpec = false;
2572  llvm::SmallVector<TypeTy*, 2> Exceptions;
2573  llvm::SmallVector<SourceRange, 2> ExceptionRanges;
2574  if (getLang().CPlusPlus) {
2575    // Parse cv-qualifier-seq[opt].
2576    ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2577      if (!DS.getSourceRange().getEnd().isInvalid())
2578        Loc = DS.getSourceRange().getEnd();
2579
2580    // Parse exception-specification[opt].
2581    if (Tok.is(tok::kw_throw)) {
2582      hasExceptionSpec = true;
2583      ThrowLoc = Tok.getLocation();
2584      ParseExceptionSpecification(Loc, Exceptions, ExceptionRanges,
2585                                  hasAnyExceptionSpec);
2586      assert(Exceptions.size() == ExceptionRanges.size() &&
2587             "Produced different number of exception types and ranges.");
2588    }
2589  }
2590
2591  // Remember that we parsed a function type, and remember the attributes.
2592  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
2593                                             EllipsisLoc,
2594                                             ParamInfo.data(), ParamInfo.size(),
2595                                             DS.getTypeQualifiers(),
2596                                             hasExceptionSpec, ThrowLoc,
2597                                             hasAnyExceptionSpec,
2598                                             Exceptions.data(),
2599                                             ExceptionRanges.data(),
2600                                             Exceptions.size(), LParenLoc, D),
2601                Loc);
2602}
2603
2604/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
2605/// we found a K&R-style identifier list instead of a type argument list.  The
2606/// current token is known to be the first identifier in the list.
2607///
2608///       identifier-list: [C99 6.7.5]
2609///         identifier
2610///         identifier-list ',' identifier
2611///
2612void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
2613                                                   Declarator &D) {
2614  // Build up an array of information about the parsed arguments.
2615  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
2616  llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
2617
2618  // If there was no identifier specified for the declarator, either we are in
2619  // an abstract-declarator, or we are in a parameter declarator which was found
2620  // to be abstract.  In abstract-declarators, identifier lists are not valid:
2621  // diagnose this.
2622  if (!D.getIdentifier())
2623    Diag(Tok, diag::ext_ident_list_in_param);
2624
2625  // Tok is known to be the first identifier in the list.  Remember this
2626  // identifier in ParamInfo.
2627  ParamsSoFar.insert(Tok.getIdentifierInfo());
2628  ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
2629                                                 Tok.getLocation(),
2630                                                 DeclPtrTy()));
2631
2632  ConsumeToken();  // eat the first identifier.
2633
2634  while (Tok.is(tok::comma)) {
2635    // Eat the comma.
2636    ConsumeToken();
2637
2638    // If this isn't an identifier, report the error and skip until ')'.
2639    if (Tok.isNot(tok::identifier)) {
2640      Diag(Tok, diag::err_expected_ident);
2641      SkipUntil(tok::r_paren);
2642      return;
2643    }
2644
2645    IdentifierInfo *ParmII = Tok.getIdentifierInfo();
2646
2647    // Reject 'typedef int y; int test(x, y)', but continue parsing.
2648    if (Actions.getTypeName(*ParmII, Tok.getLocation(), CurScope))
2649      Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
2650
2651    // Verify that the argument identifier has not already been mentioned.
2652    if (!ParamsSoFar.insert(ParmII)) {
2653      Diag(Tok, diag::err_param_redefinition) << ParmII;
2654    } else {
2655      // Remember this identifier in ParamInfo.
2656      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
2657                                                     Tok.getLocation(),
2658                                                     DeclPtrTy()));
2659    }
2660
2661    // Eat the identifier.
2662    ConsumeToken();
2663  }
2664
2665  // If we have the closing ')', eat it and we're done.
2666  SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2667
2668  // Remember that we parsed a function type, and remember the attributes.  This
2669  // function type is always a K&R style function type, which is not varargs and
2670  // has no prototype.
2671  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
2672                                             SourceLocation(),
2673                                             &ParamInfo[0], ParamInfo.size(),
2674                                             /*TypeQuals*/0,
2675                                             /*exception*/false,
2676                                             SourceLocation(), false, 0, 0, 0,
2677                                             LParenLoc, D),
2678                RLoc);
2679}
2680
2681/// [C90]   direct-declarator '[' constant-expression[opt] ']'
2682/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2683/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2684/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2685/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
2686void Parser::ParseBracketDeclarator(Declarator &D) {
2687  SourceLocation StartLoc = ConsumeBracket();
2688
2689  // C array syntax has many features, but by-far the most common is [] and [4].
2690  // This code does a fast path to handle some of the most obvious cases.
2691  if (Tok.getKind() == tok::r_square) {
2692    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
2693    // Remember that we parsed the empty array type.
2694    OwningExprResult NumElements(Actions);
2695    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
2696                                            StartLoc, EndLoc),
2697                  EndLoc);
2698    return;
2699  } else if (Tok.getKind() == tok::numeric_constant &&
2700             GetLookAheadToken(1).is(tok::r_square)) {
2701    // [4] is very common.  Parse the numeric constant expression.
2702    OwningExprResult ExprRes(Actions.ActOnNumericConstant(Tok));
2703    ConsumeToken();
2704
2705    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
2706
2707    // If there was an error parsing the assignment-expression, recover.
2708    if (ExprRes.isInvalid())
2709      ExprRes.release();  // Deallocate expr, just use [].
2710
2711    // Remember that we parsed a array type, and remember its features.
2712    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, ExprRes.release(),
2713                                            StartLoc, EndLoc),
2714                  EndLoc);
2715    return;
2716  }
2717
2718  // If valid, this location is the position where we read the 'static' keyword.
2719  SourceLocation StaticLoc;
2720  if (Tok.is(tok::kw_static))
2721    StaticLoc = ConsumeToken();
2722
2723  // If there is a type-qualifier-list, read it now.
2724  // Type qualifiers in an array subscript are a C99 feature.
2725  DeclSpec DS;
2726  ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2727
2728  // If we haven't already read 'static', check to see if there is one after the
2729  // type-qualifier-list.
2730  if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
2731    StaticLoc = ConsumeToken();
2732
2733  // Handle "direct-declarator [ type-qual-list[opt] * ]".
2734  bool isStar = false;
2735  OwningExprResult NumElements(Actions);
2736
2737  // Handle the case where we have '[*]' as the array size.  However, a leading
2738  // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
2739  // the the token after the star is a ']'.  Since stars in arrays are
2740  // infrequent, use of lookahead is not costly here.
2741  if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
2742    ConsumeToken();  // Eat the '*'.
2743
2744    if (StaticLoc.isValid()) {
2745      Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
2746      StaticLoc = SourceLocation();  // Drop the static.
2747    }
2748    isStar = true;
2749  } else if (Tok.isNot(tok::r_square)) {
2750    // Note, in C89, this production uses the constant-expr production instead
2751    // of assignment-expr.  The only difference is that assignment-expr allows
2752    // things like '=' and '*='.  Sema rejects these in C89 mode because they
2753    // are not i-c-e's, so we don't need to distinguish between the two here.
2754
2755    // Parse the constant-expression or assignment-expression now (depending
2756    // on dialect).
2757    if (getLang().CPlusPlus)
2758      NumElements = ParseConstantExpression();
2759    else
2760      NumElements = ParseAssignmentExpression();
2761  }
2762
2763  // If there was an error parsing the assignment-expression, recover.
2764  if (NumElements.isInvalid()) {
2765    D.setInvalidType(true);
2766    // If the expression was invalid, skip it.
2767    SkipUntil(tok::r_square);
2768    return;
2769  }
2770
2771  SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
2772
2773  // Remember that we parsed a array type, and remember its features.
2774  D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
2775                                          StaticLoc.isValid(), isStar,
2776                                          NumElements.release(),
2777                                          StartLoc, EndLoc),
2778                EndLoc);
2779}
2780
2781/// [GNU]   typeof-specifier:
2782///           typeof ( expressions )
2783///           typeof ( type-name )
2784/// [GNU/C++] typeof unary-expression
2785///
2786void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
2787  assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
2788  Token OpTok = Tok;
2789  SourceLocation StartLoc = ConsumeToken();
2790
2791  bool isCastExpr;
2792  TypeTy *CastTy;
2793  SourceRange CastRange;
2794  OwningExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok,
2795                                                               isCastExpr,
2796                                                               CastTy,
2797                                                               CastRange);
2798
2799  if (CastRange.getEnd().isInvalid())
2800    // FIXME: Not accurate, the range gets one token more than it should.
2801    DS.SetRangeEnd(Tok.getLocation());
2802  else
2803    DS.SetRangeEnd(CastRange.getEnd());
2804
2805  if (isCastExpr) {
2806    if (!CastTy) {
2807      DS.SetTypeSpecError();
2808      return;
2809    }
2810
2811    const char *PrevSpec = 0;
2812    // Check for duplicate type specifiers (e.g. "int typeof(int)").
2813    if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
2814                           CastTy))
2815      Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
2816    return;
2817  }
2818
2819  // If we get here, the operand to the typeof was an expresion.
2820  if (Operand.isInvalid()) {
2821    DS.SetTypeSpecError();
2822    return;
2823  }
2824
2825  const char *PrevSpec = 0;
2826  // Check for duplicate type specifiers (e.g. "int typeof(int)").
2827  if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
2828                         Operand.release()))
2829    Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
2830}
2831