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