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