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