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