]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/Parse/ParseDecl.cpp
MFC r244628:
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / 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/Basic/OpenCL.h"
17 #include "clang/Sema/Lookup.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/ParsedTemplate.h"
20 #include "clang/Sema/PrettyDeclStackTrace.h"
21 #include "RAIIObjectsForParser.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringSwitch.h"
25 using namespace clang;
26
27 //===----------------------------------------------------------------------===//
28 // C99 6.7: Declarations.
29 //===----------------------------------------------------------------------===//
30
31 /// ParseTypeName
32 ///       type-name: [C99 6.7.6]
33 ///         specifier-qualifier-list abstract-declarator[opt]
34 ///
35 /// Called type-id in C++.
36 TypeResult Parser::ParseTypeName(SourceRange *Range,
37                                  Declarator::TheContext Context,
38                                  AccessSpecifier AS,
39                                  Decl **OwnedType) {
40   DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
41   if (DSC == DSC_normal)
42     DSC = DSC_type_specifier;
43
44   // Parse the common declaration-specifiers piece.
45   DeclSpec DS(AttrFactory);
46   ParseSpecifierQualifierList(DS, AS, DSC);
47   if (OwnedType)
48     *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : 0;
49
50   // Parse the abstract-declarator, if present.
51   Declarator DeclaratorInfo(DS, Context);
52   ParseDeclarator(DeclaratorInfo);
53   if (Range)
54     *Range = DeclaratorInfo.getSourceRange();
55
56   if (DeclaratorInfo.isInvalidType())
57     return true;
58
59   return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
60 }
61
62
63 /// isAttributeLateParsed - Return true if the attribute has arguments that
64 /// require late parsing.
65 static bool isAttributeLateParsed(const IdentifierInfo &II) {
66     return llvm::StringSwitch<bool>(II.getName())
67 #include "clang/Parse/AttrLateParsed.inc"
68         .Default(false);
69 }
70
71 /// ParseGNUAttributes - Parse a non-empty attributes list.
72 ///
73 /// [GNU] attributes:
74 ///         attribute
75 ///         attributes attribute
76 ///
77 /// [GNU]  attribute:
78 ///          '__attribute__' '(' '(' attribute-list ')' ')'
79 ///
80 /// [GNU]  attribute-list:
81 ///          attrib
82 ///          attribute_list ',' attrib
83 ///
84 /// [GNU]  attrib:
85 ///          empty
86 ///          attrib-name
87 ///          attrib-name '(' identifier ')'
88 ///          attrib-name '(' identifier ',' nonempty-expr-list ')'
89 ///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
90 ///
91 /// [GNU]  attrib-name:
92 ///          identifier
93 ///          typespec
94 ///          typequal
95 ///          storageclass
96 ///
97 /// FIXME: The GCC grammar/code for this construct implies we need two
98 /// token lookahead. Comment from gcc: "If they start with an identifier
99 /// which is followed by a comma or close parenthesis, then the arguments
100 /// start with that identifier; otherwise they are an expression list."
101 ///
102 /// GCC does not require the ',' between attribs in an attribute-list.
103 ///
104 /// At the moment, I am not doing 2 token lookahead. I am also unaware of
105 /// any attributes that don't work (based on my limited testing). Most
106 /// attributes are very simple in practice. Until we find a bug, I don't see
107 /// a pressing need to implement the 2 token lookahead.
108
109 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
110                                 SourceLocation *endLoc,
111                                 LateParsedAttrList *LateAttrs) {
112   assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
113
114   while (Tok.is(tok::kw___attribute)) {
115     ConsumeToken();
116     if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
117                          "attribute")) {
118       SkipUntil(tok::r_paren, true); // skip until ) or ;
119       return;
120     }
121     if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
122       SkipUntil(tok::r_paren, true); // skip until ) or ;
123       return;
124     }
125     // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
126     while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
127            Tok.is(tok::comma)) {
128       if (Tok.is(tok::comma)) {
129         // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
130         ConsumeToken();
131         continue;
132       }
133       // we have an identifier or declaration specifier (const, int, etc.)
134       IdentifierInfo *AttrName = Tok.getIdentifierInfo();
135       SourceLocation AttrNameLoc = ConsumeToken();
136
137       if (Tok.is(tok::l_paren)) {
138         // handle "parameterized" attributes
139         if (LateAttrs && isAttributeLateParsed(*AttrName)) {
140           LateParsedAttribute *LA =
141             new LateParsedAttribute(this, *AttrName, AttrNameLoc);
142           LateAttrs->push_back(LA);
143
144           // Attributes in a class are parsed at the end of the class, along
145           // with other late-parsed declarations.
146           if (!ClassStack.empty() && !LateAttrs->parseSoon())
147             getCurrentClass().LateParsedDeclarations.push_back(LA);
148
149           // consume everything up to and including the matching right parens
150           ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false);
151
152           Token Eof;
153           Eof.startToken();
154           Eof.setLocation(Tok.getLocation());
155           LA->Toks.push_back(Eof);
156         } else {
157           ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc,
158                                 0, SourceLocation(), AttributeList::AS_GNU);
159         }
160       } else {
161         attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
162                      0, SourceLocation(), 0, 0, AttributeList::AS_GNU);
163       }
164     }
165     if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
166       SkipUntil(tok::r_paren, false);
167     SourceLocation Loc = Tok.getLocation();
168     if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
169       SkipUntil(tok::r_paren, false);
170     }
171     if (endLoc)
172       *endLoc = Loc;
173   }
174 }
175
176
177 /// Parse the arguments to a parameterized GNU attribute or
178 /// a C++11 attribute in "gnu" namespace.
179 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
180                                    SourceLocation AttrNameLoc,
181                                    ParsedAttributes &Attrs,
182                                    SourceLocation *EndLoc,
183                                    IdentifierInfo *ScopeName,
184                                    SourceLocation ScopeLoc,
185                                    AttributeList::Syntax Syntax) {
186
187   assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
188
189   // Availability attributes have their own grammar.
190   if (AttrName->isStr("availability")) {
191     ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
192     return;
193   }
194   // Thread safety attributes fit into the FIXME case above, so we
195   // just parse the arguments as a list of expressions
196   if (IsThreadSafetyAttribute(AttrName->getName())) {
197     ParseThreadSafetyAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
198     return;
199   }
200   // Type safety attributes have their own grammar.
201   if (AttrName->isStr("type_tag_for_datatype")) {
202     ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
203     return;
204   }
205
206   ConsumeParen(); // ignore the left paren loc for now
207
208   IdentifierInfo *ParmName = 0;
209   SourceLocation ParmLoc;
210   bool BuiltinType = false;
211
212   switch (Tok.getKind()) {
213   case tok::kw_char:
214   case tok::kw_wchar_t:
215   case tok::kw_char16_t:
216   case tok::kw_char32_t:
217   case tok::kw_bool:
218   case tok::kw_short:
219   case tok::kw_int:
220   case tok::kw_long:
221   case tok::kw___int64:
222   case tok::kw___int128:
223   case tok::kw_signed:
224   case tok::kw_unsigned:
225   case tok::kw_float:
226   case tok::kw_double:
227   case tok::kw_void:
228   case tok::kw_typeof:
229     // __attribute__(( vec_type_hint(char) ))
230     // FIXME: Don't just discard the builtin type token.
231     ConsumeToken();
232     BuiltinType = true;
233     break;
234
235   case tok::identifier:
236     ParmName = Tok.getIdentifierInfo();
237     ParmLoc = ConsumeToken();
238     break;
239
240   default:
241     break;
242   }
243
244   ExprVector ArgExprs;
245
246   if (!BuiltinType &&
247       (ParmLoc.isValid() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren))) {
248     // Eat the comma.
249     if (ParmLoc.isValid())
250       ConsumeToken();
251
252     // Parse the non-empty comma-separated list of expressions.
253     while (1) {
254       ExprResult ArgExpr(ParseAssignmentExpression());
255       if (ArgExpr.isInvalid()) {
256         SkipUntil(tok::r_paren);
257         return;
258       }
259       ArgExprs.push_back(ArgExpr.release());
260       if (Tok.isNot(tok::comma))
261         break;
262       ConsumeToken(); // Eat the comma, move to the next argument
263     }
264   }
265   else if (Tok.is(tok::less) && AttrName->isStr("iboutletcollection")) {
266     if (!ExpectAndConsume(tok::less, diag::err_expected_less_after, "<",
267                           tok::greater)) {
268       while (Tok.is(tok::identifier)) {
269         ConsumeToken();
270         if (Tok.is(tok::greater))
271           break;
272         if (Tok.is(tok::comma)) {
273           ConsumeToken();
274           continue;
275         }
276       }
277       if (Tok.isNot(tok::greater))
278         Diag(Tok, diag::err_iboutletcollection_with_protocol);
279       SkipUntil(tok::r_paren, false, true); // skip until ')'
280     }
281   }
282
283   SourceLocation RParen = Tok.getLocation();
284   if (!ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
285     SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
286     AttributeList *attr =
287       Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen),
288                    ScopeName, ScopeLoc, ParmName, ParmLoc,
289                    ArgExprs.data(), ArgExprs.size(), Syntax);
290     if (BuiltinType && attr->getKind() == AttributeList::AT_IBOutletCollection)
291       Diag(Tok, diag::err_iboutletcollection_builtintype);
292   }
293 }
294
295 /// \brief Parses a single argument for a declspec, including the
296 /// surrounding parens.
297 void Parser::ParseMicrosoftDeclSpecWithSingleArg(IdentifierInfo *AttrName,
298                                                  SourceLocation AttrNameLoc,
299                                                  ParsedAttributes &Attrs)
300 {
301   BalancedDelimiterTracker T(*this, tok::l_paren);
302   if (T.expectAndConsume(diag::err_expected_lparen_after,
303                          AttrName->getNameStart(), tok::r_paren))
304     return;
305
306   ExprResult ArgExpr(ParseConstantExpression());
307   if (ArgExpr.isInvalid()) {
308     T.skipToEnd();
309     return;
310   }
311   Expr *ExprList = ArgExpr.take();
312   Attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
313                &ExprList, 1, AttributeList::AS_Declspec);
314
315   T.consumeClose();
316 }
317
318 /// \brief Determines whether a declspec is a "simple" one requiring no
319 /// arguments.
320 bool Parser::IsSimpleMicrosoftDeclSpec(IdentifierInfo *Ident) {
321   return llvm::StringSwitch<bool>(Ident->getName())
322     .Case("dllimport", true)
323     .Case("dllexport", true)
324     .Case("noreturn", true)
325     .Case("nothrow", true)
326     .Case("noinline", true)
327     .Case("naked", true)
328     .Case("appdomain", true)
329     .Case("process", true)
330     .Case("jitintrinsic", true)
331     .Case("noalias", true)
332     .Case("restrict", true)
333     .Case("novtable", true)
334     .Case("selectany", true)
335     .Case("thread", true)
336     .Default(false);
337 }
338
339 /// \brief Attempts to parse a declspec which is not simple (one that takes
340 /// parameters).  Will return false if we properly handled the declspec, or
341 /// true if it is an unknown declspec.
342 void Parser::ParseComplexMicrosoftDeclSpec(IdentifierInfo *Ident,
343                                            SourceLocation Loc,
344                                            ParsedAttributes &Attrs) {
345   // Try to handle the easy case first -- these declspecs all take a single
346   // parameter as their argument.
347   if (llvm::StringSwitch<bool>(Ident->getName())
348       .Case("uuid", true)
349       .Case("align", true)
350       .Case("allocate", true)
351       .Default(false)) {
352     ParseMicrosoftDeclSpecWithSingleArg(Ident, Loc, Attrs);
353   } else if (Ident->getName() == "deprecated") {
354     // The deprecated declspec has an optional single argument, so we will
355     // check for a l-paren to decide whether we should parse an argument or
356     // not.
357     if (Tok.getKind() == tok::l_paren)
358       ParseMicrosoftDeclSpecWithSingleArg(Ident, Loc, Attrs);
359     else
360       Attrs.addNew(Ident, Loc, 0, Loc, 0, SourceLocation(), 0, 0,
361                    AttributeList::AS_Declspec);
362   } else if (Ident->getName() == "property") {
363     // The property declspec is more complex in that it can take one or two
364     // assignment expressions as a parameter, but the lhs of the assignment
365     // must be named get or put.
366     //
367     // For right now, we will just skip to the closing right paren of the
368     // property expression.
369     //
370     // FIXME: we should deal with __declspec(property) at some point because it
371     // is used in the platform SDK headers for the Parallel Patterns Library
372     // and ATL.
373     BalancedDelimiterTracker T(*this, tok::l_paren);
374     if (T.expectAndConsume(diag::err_expected_lparen_after,
375                            Ident->getNameStart(), tok::r_paren))
376       return;
377     T.skipToEnd();
378   } else {
379     // We don't recognize this as a valid declspec, but instead of creating the
380     // attribute and allowing sema to warn about it, we will warn here instead.
381     // This is because some attributes have multiple spellings, but we need to
382     // disallow that for declspecs (such as align vs aligned).  If we made the
383     // attribute, we'd have to split the valid declspec spelling logic into
384     // both locations.
385     Diag(Loc, diag::warn_ms_declspec_unknown) << Ident;
386
387     // If there's an open paren, we should eat the open and close parens under
388     // the assumption that this unknown declspec has parameters.
389     BalancedDelimiterTracker T(*this, tok::l_paren);
390     if (!T.consumeOpen())
391       T.skipToEnd();
392   }
393 }
394
395 /// [MS] decl-specifier:
396 ///             __declspec ( extended-decl-modifier-seq )
397 ///
398 /// [MS] extended-decl-modifier-seq:
399 ///             extended-decl-modifier[opt]
400 ///             extended-decl-modifier extended-decl-modifier-seq
401 void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &Attrs) {
402   assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
403
404   ConsumeToken();
405   BalancedDelimiterTracker T(*this, tok::l_paren);
406   if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
407                          tok::r_paren))
408     return;
409
410   // An empty declspec is perfectly legal and should not warn.  Additionally,
411   // you can specify multiple attributes per declspec.
412   while (Tok.getKind() != tok::r_paren) {
413     // We expect either a well-known identifier or a generic string.  Anything
414     // else is a malformed declspec.
415     bool IsString = Tok.getKind() == tok::string_literal ? true : false;
416     if (!IsString && Tok.getKind() != tok::identifier &&
417         Tok.getKind() != tok::kw_restrict) {
418       Diag(Tok, diag::err_ms_declspec_type);
419       T.skipToEnd();
420       return;
421     }
422
423     IdentifierInfo *AttrName;
424     SourceLocation AttrNameLoc;
425     if (IsString) {
426       SmallString<8> StrBuffer;
427       bool Invalid = false;
428       StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
429       if (Invalid) {
430         T.skipToEnd();
431         return;
432       }
433       AttrName = PP.getIdentifierInfo(Str);
434       AttrNameLoc = ConsumeStringToken();
435     } else {
436       AttrName = Tok.getIdentifierInfo();
437       AttrNameLoc = ConsumeToken();
438     }
439
440     if (IsString || IsSimpleMicrosoftDeclSpec(AttrName))
441       // If we have a generic string, we will allow it because there is no
442       // documented list of allowable string declspecs, but we know they exist
443       // (for instance, SAL declspecs in older versions of MSVC).
444       //
445       // Alternatively, if the identifier is a simple one, then it requires no
446       // arguments and can be turned into an attribute directly.
447       Attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
448                    0, 0, AttributeList::AS_Declspec);
449     else
450       ParseComplexMicrosoftDeclSpec(AttrName, AttrNameLoc, Attrs);
451   }
452   T.consumeClose();
453 }
454
455 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
456   // Treat these like attributes
457   while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
458          Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl)   ||
459          Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) ||
460          Tok.is(tok::kw___ptr32) ||
461          Tok.is(tok::kw___unaligned)) {
462     IdentifierInfo *AttrName = Tok.getIdentifierInfo();
463     SourceLocation AttrNameLoc = ConsumeToken();
464     attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
465                  SourceLocation(), 0, 0, AttributeList::AS_MSTypespec);
466   }
467 }
468
469 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
470   // Treat these like attributes
471   while (Tok.is(tok::kw___pascal)) {
472     IdentifierInfo *AttrName = Tok.getIdentifierInfo();
473     SourceLocation AttrNameLoc = ConsumeToken();
474     attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
475                  SourceLocation(), 0, 0, AttributeList::AS_MSTypespec);
476   }
477 }
478
479 void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
480   // Treat these like attributes
481   while (Tok.is(tok::kw___kernel)) {
482     SourceLocation AttrNameLoc = ConsumeToken();
483     attrs.addNew(PP.getIdentifierInfo("opencl_kernel_function"),
484                  AttrNameLoc, 0, AttrNameLoc, 0,
485                  SourceLocation(), 0, 0, AttributeList::AS_GNU);
486   }
487 }
488
489 void Parser::ParseOpenCLQualifiers(DeclSpec &DS) {
490   SourceLocation Loc = Tok.getLocation();
491   switch(Tok.getKind()) {
492     // OpenCL qualifiers:
493     case tok::kw___private:
494     case tok::kw_private:
495       DS.getAttributes().addNewInteger(
496           Actions.getASTContext(),
497           PP.getIdentifierInfo("address_space"), Loc, 0);
498       break;
499
500     case tok::kw___global:
501       DS.getAttributes().addNewInteger(
502           Actions.getASTContext(),
503           PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global);
504       break;
505
506     case tok::kw___local:
507       DS.getAttributes().addNewInteger(
508           Actions.getASTContext(),
509           PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local);
510       break;
511
512     case tok::kw___constant:
513       DS.getAttributes().addNewInteger(
514           Actions.getASTContext(),
515           PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant);
516       break;
517
518     case tok::kw___read_only:
519       DS.getAttributes().addNewInteger(
520           Actions.getASTContext(),
521           PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only);
522       break;
523
524     case tok::kw___write_only:
525       DS.getAttributes().addNewInteger(
526           Actions.getASTContext(),
527           PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only);
528       break;
529
530     case tok::kw___read_write:
531       DS.getAttributes().addNewInteger(
532           Actions.getASTContext(),
533           PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write);
534       break;
535     default: break;
536   }
537 }
538
539 /// \brief Parse a version number.
540 ///
541 /// version:
542 ///   simple-integer
543 ///   simple-integer ',' simple-integer
544 ///   simple-integer ',' simple-integer ',' simple-integer
545 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
546   Range = Tok.getLocation();
547
548   if (!Tok.is(tok::numeric_constant)) {
549     Diag(Tok, diag::err_expected_version);
550     SkipUntil(tok::comma, tok::r_paren, true, true, true);
551     return VersionTuple();
552   }
553
554   // Parse the major (and possibly minor and subminor) versions, which
555   // are stored in the numeric constant. We utilize a quirk of the
556   // lexer, which is that it handles something like 1.2.3 as a single
557   // numeric constant, rather than two separate tokens.
558   SmallString<512> Buffer;
559   Buffer.resize(Tok.getLength()+1);
560   const char *ThisTokBegin = &Buffer[0];
561
562   // Get the spelling of the token, which eliminates trigraphs, etc.
563   bool Invalid = false;
564   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
565   if (Invalid)
566     return VersionTuple();
567
568   // Parse the major version.
569   unsigned AfterMajor = 0;
570   unsigned Major = 0;
571   while (AfterMajor < ActualLength && isdigit(ThisTokBegin[AfterMajor])) {
572     Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
573     ++AfterMajor;
574   }
575
576   if (AfterMajor == 0) {
577     Diag(Tok, diag::err_expected_version);
578     SkipUntil(tok::comma, tok::r_paren, true, true, true);
579     return VersionTuple();
580   }
581
582   if (AfterMajor == ActualLength) {
583     ConsumeToken();
584
585     // We only had a single version component.
586     if (Major == 0) {
587       Diag(Tok, diag::err_zero_version);
588       return VersionTuple();
589     }
590
591     return VersionTuple(Major);
592   }
593
594   if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) {
595     Diag(Tok, diag::err_expected_version);
596     SkipUntil(tok::comma, tok::r_paren, true, true, true);
597     return VersionTuple();
598   }
599
600   // Parse the minor version.
601   unsigned AfterMinor = AfterMajor + 1;
602   unsigned Minor = 0;
603   while (AfterMinor < ActualLength && isdigit(ThisTokBegin[AfterMinor])) {
604     Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
605     ++AfterMinor;
606   }
607
608   if (AfterMinor == ActualLength) {
609     ConsumeToken();
610
611     // We had major.minor.
612     if (Major == 0 && Minor == 0) {
613       Diag(Tok, diag::err_zero_version);
614       return VersionTuple();
615     }
616
617     return VersionTuple(Major, Minor);
618   }
619
620   // If what follows is not a '.', we have a problem.
621   if (ThisTokBegin[AfterMinor] != '.') {
622     Diag(Tok, diag::err_expected_version);
623     SkipUntil(tok::comma, tok::r_paren, true, true, true);
624     return VersionTuple();
625   }
626
627   // Parse the subminor version.
628   unsigned AfterSubminor = AfterMinor + 1;
629   unsigned Subminor = 0;
630   while (AfterSubminor < ActualLength && isdigit(ThisTokBegin[AfterSubminor])) {
631     Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
632     ++AfterSubminor;
633   }
634
635   if (AfterSubminor != ActualLength) {
636     Diag(Tok, diag::err_expected_version);
637     SkipUntil(tok::comma, tok::r_paren, true, true, true);
638     return VersionTuple();
639   }
640   ConsumeToken();
641   return VersionTuple(Major, Minor, Subminor);
642 }
643
644 /// \brief Parse the contents of the "availability" attribute.
645 ///
646 /// availability-attribute:
647 ///   'availability' '(' platform ',' version-arg-list, opt-message')'
648 ///
649 /// platform:
650 ///   identifier
651 ///
652 /// version-arg-list:
653 ///   version-arg
654 ///   version-arg ',' version-arg-list
655 ///
656 /// version-arg:
657 ///   'introduced' '=' version
658 ///   'deprecated' '=' version
659 ///   'obsoleted' = version
660 ///   'unavailable'
661 /// opt-message:
662 ///   'message' '=' <string>
663 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
664                                         SourceLocation AvailabilityLoc,
665                                         ParsedAttributes &attrs,
666                                         SourceLocation *endLoc) {
667   SourceLocation PlatformLoc;
668   IdentifierInfo *Platform = 0;
669
670   enum { Introduced, Deprecated, Obsoleted, Unknown };
671   AvailabilityChange Changes[Unknown];
672   ExprResult MessageExpr;
673
674   // Opening '('.
675   BalancedDelimiterTracker T(*this, tok::l_paren);
676   if (T.consumeOpen()) {
677     Diag(Tok, diag::err_expected_lparen);
678     return;
679   }
680
681   // Parse the platform name,
682   if (Tok.isNot(tok::identifier)) {
683     Diag(Tok, diag::err_availability_expected_platform);
684     SkipUntil(tok::r_paren);
685     return;
686   }
687   Platform = Tok.getIdentifierInfo();
688   PlatformLoc = ConsumeToken();
689
690   // Parse the ',' following the platform name.
691   if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren))
692     return;
693
694   // If we haven't grabbed the pointers for the identifiers
695   // "introduced", "deprecated", and "obsoleted", do so now.
696   if (!Ident_introduced) {
697     Ident_introduced = PP.getIdentifierInfo("introduced");
698     Ident_deprecated = PP.getIdentifierInfo("deprecated");
699     Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
700     Ident_unavailable = PP.getIdentifierInfo("unavailable");
701     Ident_message = PP.getIdentifierInfo("message");
702   }
703
704   // Parse the set of introductions/deprecations/removals.
705   SourceLocation UnavailableLoc;
706   do {
707     if (Tok.isNot(tok::identifier)) {
708       Diag(Tok, diag::err_availability_expected_change);
709       SkipUntil(tok::r_paren);
710       return;
711     }
712     IdentifierInfo *Keyword = Tok.getIdentifierInfo();
713     SourceLocation KeywordLoc = ConsumeToken();
714
715     if (Keyword == Ident_unavailable) {
716       if (UnavailableLoc.isValid()) {
717         Diag(KeywordLoc, diag::err_availability_redundant)
718           << Keyword << SourceRange(UnavailableLoc);
719       }
720       UnavailableLoc = KeywordLoc;
721
722       if (Tok.isNot(tok::comma))
723         break;
724
725       ConsumeToken();
726       continue;
727     }
728
729     if (Tok.isNot(tok::equal)) {
730       Diag(Tok, diag::err_expected_equal_after)
731         << Keyword;
732       SkipUntil(tok::r_paren);
733       return;
734     }
735     ConsumeToken();
736     if (Keyword == Ident_message) {
737       if (!isTokenStringLiteral()) {
738         Diag(Tok, diag::err_expected_string_literal);
739         SkipUntil(tok::r_paren);
740         return;
741       }
742       MessageExpr = ParseStringLiteralExpression();
743       break;
744     }
745
746     SourceRange VersionRange;
747     VersionTuple Version = ParseVersionTuple(VersionRange);
748
749     if (Version.empty()) {
750       SkipUntil(tok::r_paren);
751       return;
752     }
753
754     unsigned Index;
755     if (Keyword == Ident_introduced)
756       Index = Introduced;
757     else if (Keyword == Ident_deprecated)
758       Index = Deprecated;
759     else if (Keyword == Ident_obsoleted)
760       Index = Obsoleted;
761     else
762       Index = Unknown;
763
764     if (Index < Unknown) {
765       if (!Changes[Index].KeywordLoc.isInvalid()) {
766         Diag(KeywordLoc, diag::err_availability_redundant)
767           << Keyword
768           << SourceRange(Changes[Index].KeywordLoc,
769                          Changes[Index].VersionRange.getEnd());
770       }
771
772       Changes[Index].KeywordLoc = KeywordLoc;
773       Changes[Index].Version = Version;
774       Changes[Index].VersionRange = VersionRange;
775     } else {
776       Diag(KeywordLoc, diag::err_availability_unknown_change)
777         << Keyword << VersionRange;
778     }
779
780     if (Tok.isNot(tok::comma))
781       break;
782
783     ConsumeToken();
784   } while (true);
785
786   // Closing ')'.
787   if (T.consumeClose())
788     return;
789
790   if (endLoc)
791     *endLoc = T.getCloseLocation();
792
793   // The 'unavailable' availability cannot be combined with any other
794   // availability changes. Make sure that hasn't happened.
795   if (UnavailableLoc.isValid()) {
796     bool Complained = false;
797     for (unsigned Index = Introduced; Index != Unknown; ++Index) {
798       if (Changes[Index].KeywordLoc.isValid()) {
799         if (!Complained) {
800           Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
801             << SourceRange(Changes[Index].KeywordLoc,
802                            Changes[Index].VersionRange.getEnd());
803           Complained = true;
804         }
805
806         // Clear out the availability.
807         Changes[Index] = AvailabilityChange();
808       }
809     }
810   }
811
812   // Record this attribute
813   attrs.addNew(&Availability,
814                SourceRange(AvailabilityLoc, T.getCloseLocation()),
815                0, AvailabilityLoc,
816                Platform, PlatformLoc,
817                Changes[Introduced],
818                Changes[Deprecated],
819                Changes[Obsoleted],
820                UnavailableLoc, MessageExpr.take(),
821                AttributeList::AS_GNU);
822 }
823
824
825 // Late Parsed Attributes:
826 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
827
828 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
829
830 void Parser::LateParsedClass::ParseLexedAttributes() {
831   Self->ParseLexedAttributes(*Class);
832 }
833
834 void Parser::LateParsedAttribute::ParseLexedAttributes() {
835   Self->ParseLexedAttribute(*this, true, false);
836 }
837
838 /// Wrapper class which calls ParseLexedAttribute, after setting up the
839 /// scope appropriately.
840 void Parser::ParseLexedAttributes(ParsingClass &Class) {
841   // Deal with templates
842   // FIXME: Test cases to make sure this does the right thing for templates.
843   bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
844   ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
845                                 HasTemplateScope);
846   if (HasTemplateScope)
847     Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
848
849   // Set or update the scope flags.
850   bool AlreadyHasClassScope = Class.TopLevelClass;
851   unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
852   ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
853   ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
854
855   // Enter the scope of nested classes
856   if (!AlreadyHasClassScope)
857     Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
858                                                 Class.TagOrTemplate);
859   if (!Class.LateParsedDeclarations.empty()) {
860     for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
861       Class.LateParsedDeclarations[i]->ParseLexedAttributes();
862     }
863   }
864
865   if (!AlreadyHasClassScope)
866     Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
867                                                  Class.TagOrTemplate);
868 }
869
870
871 /// \brief Parse all attributes in LAs, and attach them to Decl D.
872 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
873                                      bool EnterScope, bool OnDefinition) {
874   assert(LAs.parseSoon() &&
875          "Attribute list should be marked for immediate parsing.");
876   for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
877     if (D)
878       LAs[i]->addDecl(D);
879     ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
880     delete LAs[i];
881   }
882   LAs.clear();
883 }
884
885
886 /// \brief Finish parsing an attribute for which parsing was delayed.
887 /// This will be called at the end of parsing a class declaration
888 /// for each LateParsedAttribute. We consume the saved tokens and
889 /// create an attribute with the arguments filled in. We add this
890 /// to the Attribute list for the decl.
891 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
892                                  bool EnterScope, bool OnDefinition) {
893   // Save the current token position.
894   SourceLocation OrigLoc = Tok.getLocation();
895
896   // Append the current token at the end of the new token stream so that it
897   // doesn't get lost.
898   LA.Toks.push_back(Tok);
899   PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false);
900   // Consume the previously pushed token.
901   ConsumeAnyToken();
902
903   if (OnDefinition && !IsThreadSafetyAttribute(LA.AttrName.getName())) {
904     Diag(Tok, diag::warn_attribute_on_function_definition)
905       << LA.AttrName.getName();
906   }
907
908   ParsedAttributes Attrs(AttrFactory);
909   SourceLocation endLoc;
910
911   if (LA.Decls.size() > 0) {
912     Decl *D = LA.Decls[0];
913     NamedDecl *ND  = dyn_cast<NamedDecl>(D);
914     RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
915
916     // Allow 'this' within late-parsed attributes.
917     Sema::CXXThisScopeRAII ThisScope(Actions, RD,
918                                      /*TypeQuals=*/0,
919                                      ND && RD && ND->isCXXInstanceMember());
920
921     if (LA.Decls.size() == 1) {
922       // If the Decl is templatized, add template parameters to scope.
923       bool HasTemplateScope = EnterScope && D->isTemplateDecl();
924       ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
925       if (HasTemplateScope)
926         Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
927
928       // If the Decl is on a function, add function parameters to the scope.
929       bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
930       ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunScope);
931       if (HasFunScope)
932         Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
933
934       ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
935                             0, SourceLocation(), AttributeList::AS_GNU);
936
937       if (HasFunScope) {
938         Actions.ActOnExitFunctionContext();
939         FnScope.Exit();  // Pop scope, and remove Decls from IdResolver
940       }
941       if (HasTemplateScope) {
942         TempScope.Exit();
943       }
944     } else {
945       // If there are multiple decls, then the decl cannot be within the
946       // function scope.
947       ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
948                             0, SourceLocation(), AttributeList::AS_GNU);
949     }
950   } else {
951     Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
952   }
953
954   for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i) {
955     Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
956   }
957
958   if (Tok.getLocation() != OrigLoc) {
959     // Due to a parsing error, we either went over the cached tokens or
960     // there are still cached tokens left, so we skip the leftover tokens.
961     // Since this is an uncommon situation that should be avoided, use the
962     // expensive isBeforeInTranslationUnit call.
963     if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
964                                                         OrigLoc))
965     while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
966       ConsumeAnyToken();
967   }
968 }
969
970 /// \brief Wrapper around a case statement checking if AttrName is
971 /// one of the thread safety attributes
972 bool Parser::IsThreadSafetyAttribute(llvm::StringRef AttrName){
973   return llvm::StringSwitch<bool>(AttrName)
974       .Case("guarded_by", true)
975       .Case("guarded_var", true)
976       .Case("pt_guarded_by", true)
977       .Case("pt_guarded_var", true)
978       .Case("lockable", true)
979       .Case("scoped_lockable", true)
980       .Case("no_thread_safety_analysis", true)
981       .Case("acquired_after", true)
982       .Case("acquired_before", true)
983       .Case("exclusive_lock_function", true)
984       .Case("shared_lock_function", true)
985       .Case("exclusive_trylock_function", true)
986       .Case("shared_trylock_function", true)
987       .Case("unlock_function", true)
988       .Case("lock_returned", true)
989       .Case("locks_excluded", true)
990       .Case("exclusive_locks_required", true)
991       .Case("shared_locks_required", true)
992       .Default(false);
993 }
994
995 /// \brief Parse the contents of thread safety attributes. These
996 /// should always be parsed as an expression list.
997 ///
998 /// We need to special case the parsing due to the fact that if the first token
999 /// of the first argument is an identifier, the main parse loop will store
1000 /// that token as a "parameter" and the rest of
1001 /// the arguments will be added to a list of "arguments". However,
1002 /// subsequent tokens in the first argument are lost. We instead parse each
1003 /// argument as an expression and add all arguments to the list of "arguments".
1004 /// In future, we will take advantage of this special case to also
1005 /// deal with some argument scoping issues here (for example, referring to a
1006 /// function parameter in the attribute on that function).
1007 void Parser::ParseThreadSafetyAttribute(IdentifierInfo &AttrName,
1008                                         SourceLocation AttrNameLoc,
1009                                         ParsedAttributes &Attrs,
1010                                         SourceLocation *EndLoc) {
1011   assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1012
1013   BalancedDelimiterTracker T(*this, tok::l_paren);
1014   T.consumeOpen();
1015
1016   ExprVector ArgExprs;
1017   bool ArgExprsOk = true;
1018
1019   // now parse the list of expressions
1020   while (Tok.isNot(tok::r_paren)) {
1021     ExprResult ArgExpr(ParseAssignmentExpression());
1022     if (ArgExpr.isInvalid()) {
1023       ArgExprsOk = false;
1024       T.consumeClose();
1025       break;
1026     } else {
1027       ArgExprs.push_back(ArgExpr.release());
1028     }
1029     if (Tok.isNot(tok::comma))
1030       break;
1031     ConsumeToken(); // Eat the comma, move to the next argument
1032   }
1033   // Match the ')'.
1034   if (ArgExprsOk && !T.consumeClose()) {
1035     Attrs.addNew(&AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
1036                  ArgExprs.data(), ArgExprs.size(), AttributeList::AS_GNU);
1037   }
1038   if (EndLoc)
1039     *EndLoc = T.getCloseLocation();
1040 }
1041
1042 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1043                                               SourceLocation AttrNameLoc,
1044                                               ParsedAttributes &Attrs,
1045                                               SourceLocation *EndLoc) {
1046   assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1047
1048   BalancedDelimiterTracker T(*this, tok::l_paren);
1049   T.consumeOpen();
1050
1051   if (Tok.isNot(tok::identifier)) {
1052     Diag(Tok, diag::err_expected_ident);
1053     T.skipToEnd();
1054     return;
1055   }
1056   IdentifierInfo *ArgumentKind = Tok.getIdentifierInfo();
1057   SourceLocation ArgumentKindLoc = ConsumeToken();
1058
1059   if (Tok.isNot(tok::comma)) {
1060     Diag(Tok, diag::err_expected_comma);
1061     T.skipToEnd();
1062     return;
1063   }
1064   ConsumeToken();
1065
1066   SourceRange MatchingCTypeRange;
1067   TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1068   if (MatchingCType.isInvalid()) {
1069     T.skipToEnd();
1070     return;
1071   }
1072
1073   bool LayoutCompatible = false;
1074   bool MustBeNull = false;
1075   while (Tok.is(tok::comma)) {
1076     ConsumeToken();
1077     if (Tok.isNot(tok::identifier)) {
1078       Diag(Tok, diag::err_expected_ident);
1079       T.skipToEnd();
1080       return;
1081     }
1082     IdentifierInfo *Flag = Tok.getIdentifierInfo();
1083     if (Flag->isStr("layout_compatible"))
1084       LayoutCompatible = true;
1085     else if (Flag->isStr("must_be_null"))
1086       MustBeNull = true;
1087     else {
1088       Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1089       T.skipToEnd();
1090       return;
1091     }
1092     ConsumeToken(); // consume flag
1093   }
1094
1095   if (!T.consumeClose()) {
1096     Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, 0, AttrNameLoc,
1097                                    ArgumentKind, ArgumentKindLoc,
1098                                    MatchingCType.release(), LayoutCompatible,
1099                                    MustBeNull, AttributeList::AS_GNU);
1100   }
1101
1102   if (EndLoc)
1103     *EndLoc = T.getCloseLocation();
1104 }
1105
1106 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1107 /// of a C++11 attribute-specifier in a location where an attribute is not
1108 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1109 /// situation.
1110 ///
1111 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1112 /// this doesn't appear to actually be an attribute-specifier, and the caller
1113 /// should try to parse it.
1114 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1115   assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1116
1117   switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1118   case CAK_NotAttributeSpecifier:
1119     // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1120     return false;
1121
1122   case CAK_InvalidAttributeSpecifier:
1123     Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1124     return false;
1125
1126   case CAK_AttributeSpecifier:
1127     // Parse and discard the attributes.
1128     SourceLocation BeginLoc = ConsumeBracket();
1129     ConsumeBracket();
1130     SkipUntil(tok::r_square, /*StopAtSemi*/ false);
1131     assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1132     SourceLocation EndLoc = ConsumeBracket();
1133     Diag(BeginLoc, diag::err_attributes_not_allowed)
1134       << SourceRange(BeginLoc, EndLoc);
1135     return true;
1136   }
1137   llvm_unreachable("All cases handled above.");
1138 }
1139
1140 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
1141   Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
1142     << attrs.Range;
1143 }
1144
1145 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs) {
1146   AttributeList *AttrList = attrs.getList();
1147   while (AttrList) {
1148     if (AttrList->isCXX0XAttribute()) {
1149       Diag(AttrList->getLoc(), diag::warn_attribute_no_decl) 
1150         << AttrList->getName();
1151       AttrList->setInvalid();
1152     }
1153     AttrList = AttrList->getNext();
1154   }
1155 }
1156
1157 /// ParseDeclaration - Parse a full 'declaration', which consists of
1158 /// declaration-specifiers, some number of declarators, and a semicolon.
1159 /// 'Context' should be a Declarator::TheContext value.  This returns the
1160 /// location of the semicolon in DeclEnd.
1161 ///
1162 ///       declaration: [C99 6.7]
1163 ///         block-declaration ->
1164 ///           simple-declaration
1165 ///           others                   [FIXME]
1166 /// [C++]   template-declaration
1167 /// [C++]   namespace-definition
1168 /// [C++]   using-directive
1169 /// [C++]   using-declaration
1170 /// [C++11/C11] static_assert-declaration
1171 ///         others... [FIXME]
1172 ///
1173 Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts,
1174                                                 unsigned Context,
1175                                                 SourceLocation &DeclEnd,
1176                                           ParsedAttributesWithRange &attrs) {
1177   ParenBraceBracketBalancer BalancerRAIIObj(*this);
1178   // Must temporarily exit the objective-c container scope for
1179   // parsing c none objective-c decls.
1180   ObjCDeclContextSwitch ObjCDC(*this);
1181
1182   Decl *SingleDecl = 0;
1183   Decl *OwnedType = 0;
1184   switch (Tok.getKind()) {
1185   case tok::kw_template:
1186   case tok::kw_export:
1187     ProhibitAttributes(attrs);
1188     SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
1189     break;
1190   case tok::kw_inline:
1191     // Could be the start of an inline namespace. Allowed as an ext in C++03.
1192     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1193       ProhibitAttributes(attrs);
1194       SourceLocation InlineLoc = ConsumeToken();
1195       SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc);
1196       break;
1197     }
1198     return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs,
1199                                   true);
1200   case tok::kw_namespace:
1201     ProhibitAttributes(attrs);
1202     SingleDecl = ParseNamespace(Context, DeclEnd);
1203     break;
1204   case tok::kw_using:
1205     SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1206                                                   DeclEnd, attrs, &OwnedType);
1207     break;
1208   case tok::kw_static_assert:
1209   case tok::kw__Static_assert:
1210     ProhibitAttributes(attrs);
1211     SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1212     break;
1213   default:
1214     return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true);
1215   }
1216
1217   // This routine returns a DeclGroup, if the thing we parsed only contains a
1218   // single decl, convert it now. Alias declarations can also declare a type;
1219   // include that too if it is present.
1220   return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType);
1221 }
1222
1223 ///       simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1224 ///         declaration-specifiers init-declarator-list[opt] ';'
1225 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1226 ///             init-declarator-list ';'
1227 ///[C90/C++]init-declarator-list ';'                             [TODO]
1228 /// [OMP]   threadprivate-directive                              [TODO]
1229 ///
1230 ///       for-range-declaration: [C++11 6.5p1: stmt.ranged]
1231 ///         attribute-specifier-seq[opt] type-specifier-seq declarator
1232 ///
1233 /// If RequireSemi is false, this does not check for a ';' at the end of the
1234 /// declaration.  If it is true, it checks for and eats it.
1235 ///
1236 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1237 /// of a simple-declaration. If we find that we are, we also parse the
1238 /// for-range-initializer, and place it here.
1239 Parser::DeclGroupPtrTy
1240 Parser::ParseSimpleDeclaration(StmtVector &Stmts, unsigned Context,
1241                                SourceLocation &DeclEnd,
1242                                ParsedAttributesWithRange &attrs,
1243                                bool RequireSemi, ForRangeInit *FRI) {
1244   // Parse the common declaration-specifiers piece.
1245   ParsingDeclSpec DS(*this);
1246   DS.takeAttributesFrom(attrs);
1247
1248   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
1249                              getDeclSpecContextFromDeclaratorContext(Context));
1250
1251   // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1252   // declaration-specifiers init-declarator-list[opt] ';'
1253   if (Tok.is(tok::semi)) {
1254     DeclEnd = Tok.getLocation();
1255     if (RequireSemi) ConsumeToken();
1256     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1257                                                        DS);
1258     DS.complete(TheDecl);
1259     return Actions.ConvertDeclToDeclGroup(TheDecl);
1260   }
1261
1262   return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI);
1263 }
1264
1265 /// Returns true if this might be the start of a declarator, or a common typo
1266 /// for a declarator.
1267 bool Parser::MightBeDeclarator(unsigned Context) {
1268   switch (Tok.getKind()) {
1269   case tok::annot_cxxscope:
1270   case tok::annot_template_id:
1271   case tok::caret:
1272   case tok::code_completion:
1273   case tok::coloncolon:
1274   case tok::ellipsis:
1275   case tok::kw___attribute:
1276   case tok::kw_operator:
1277   case tok::l_paren:
1278   case tok::star:
1279     return true;
1280
1281   case tok::amp:
1282   case tok::ampamp:
1283     return getLangOpts().CPlusPlus;
1284
1285   case tok::l_square: // Might be an attribute on an unnamed bit-field.
1286     return Context == Declarator::MemberContext && getLangOpts().CPlusPlus0x &&
1287            NextToken().is(tok::l_square);
1288
1289   case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1290     return Context == Declarator::MemberContext || getLangOpts().CPlusPlus;
1291
1292   case tok::identifier:
1293     switch (NextToken().getKind()) {
1294     case tok::code_completion:
1295     case tok::coloncolon:
1296     case tok::comma:
1297     case tok::equal:
1298     case tok::equalequal: // Might be a typo for '='.
1299     case tok::kw_alignas:
1300     case tok::kw_asm:
1301     case tok::kw___attribute:
1302     case tok::l_brace:
1303     case tok::l_paren:
1304     case tok::l_square:
1305     case tok::less:
1306     case tok::r_brace:
1307     case tok::r_paren:
1308     case tok::r_square:
1309     case tok::semi:
1310       return true;
1311
1312     case tok::colon:
1313       // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1314       // and in block scope it's probably a label. Inside a class definition,
1315       // this is a bit-field.
1316       return Context == Declarator::MemberContext ||
1317              (getLangOpts().CPlusPlus && Context == Declarator::FileContext);
1318
1319     case tok::identifier: // Possible virt-specifier.
1320       return getLangOpts().CPlusPlus0x && isCXX0XVirtSpecifier(NextToken());
1321
1322     default:
1323       return false;
1324     }
1325
1326   default:
1327     return false;
1328   }
1329 }
1330
1331 /// Skip until we reach something which seems like a sensible place to pick
1332 /// up parsing after a malformed declaration. This will sometimes stop sooner
1333 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1334 void Parser::SkipMalformedDecl() {
1335   while (true) {
1336     switch (Tok.getKind()) {
1337     case tok::l_brace:
1338       // Skip until matching }, then stop. We've probably skipped over
1339       // a malformed class or function definition or similar.
1340       ConsumeBrace();
1341       SkipUntil(tok::r_brace, /*StopAtSemi*/false);
1342       if (Tok.is(tok::comma) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try)) {
1343         // This declaration isn't over yet. Keep skipping.
1344         continue;
1345       }
1346       if (Tok.is(tok::semi))
1347         ConsumeToken();
1348       return;
1349
1350     case tok::l_square:
1351       ConsumeBracket();
1352       SkipUntil(tok::r_square, /*StopAtSemi*/false);
1353       continue;
1354
1355     case tok::l_paren:
1356       ConsumeParen();
1357       SkipUntil(tok::r_paren, /*StopAtSemi*/false);
1358       continue;
1359
1360     case tok::r_brace:
1361       return;
1362
1363     case tok::semi:
1364       ConsumeToken();
1365       return;
1366
1367     case tok::kw_inline:
1368       // 'inline namespace' at the start of a line is almost certainly
1369       // a good place to pick back up parsing, except in an Objective-C
1370       // @interface context.
1371       if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1372           (!ParsingInObjCContainer || CurParsedObjCImpl))
1373         return;
1374       break;
1375
1376     case tok::kw_namespace:
1377       // 'namespace' at the start of a line is almost certainly a good
1378       // place to pick back up parsing, except in an Objective-C
1379       // @interface context.
1380       if (Tok.isAtStartOfLine() &&
1381           (!ParsingInObjCContainer || CurParsedObjCImpl))
1382         return;
1383       break;
1384
1385     case tok::at:
1386       // @end is very much like } in Objective-C contexts.
1387       if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1388           ParsingInObjCContainer)
1389         return;
1390       break;
1391
1392     case tok::minus:
1393     case tok::plus:
1394       // - and + probably start new method declarations in Objective-C contexts.
1395       if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1396         return;
1397       break;
1398
1399     case tok::eof:
1400       return;
1401
1402     default:
1403       break;
1404     }
1405
1406     ConsumeAnyToken();
1407   }
1408 }
1409
1410 /// ParseDeclGroup - Having concluded that this is either a function
1411 /// definition or a group of object declarations, actually parse the
1412 /// result.
1413 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1414                                               unsigned Context,
1415                                               bool AllowFunctionDefinitions,
1416                                               SourceLocation *DeclEnd,
1417                                               ForRangeInit *FRI) {
1418   // Parse the first declarator.
1419   ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
1420   ParseDeclarator(D);
1421
1422   // Bail out if the first declarator didn't seem well-formed.
1423   if (!D.hasName() && !D.mayOmitIdentifier()) {
1424     SkipMalformedDecl();
1425     return DeclGroupPtrTy();
1426   }
1427
1428   // Save late-parsed attributes for now; they need to be parsed in the
1429   // appropriate function scope after the function Decl has been constructed.
1430   // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1431   LateParsedAttrList LateParsedAttrs(true);
1432   if (D.isFunctionDeclarator())
1433     MaybeParseGNUAttributes(D, &LateParsedAttrs);
1434
1435   // Check to see if we have a function *definition* which must have a body.
1436   if (AllowFunctionDefinitions && D.isFunctionDeclarator() &&
1437       // Look at the next token to make sure that this isn't a function
1438       // declaration.  We have to check this because __attribute__ might be the
1439       // start of a function definition in GCC-extended K&R C.
1440       !isDeclarationAfterDeclarator()) {
1441
1442     if (isStartOfFunctionDefinition(D)) {
1443       if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1444         Diag(Tok, diag::err_function_declared_typedef);
1445
1446         // Recover by treating the 'typedef' as spurious.
1447         DS.ClearStorageClassSpecs();
1448       }
1449
1450       Decl *TheDecl =
1451         ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1452       return Actions.ConvertDeclToDeclGroup(TheDecl);
1453     }
1454
1455     if (isDeclarationSpecifier()) {
1456       // If there is an invalid declaration specifier right after the function
1457       // prototype, then we must be in a missing semicolon case where this isn't
1458       // actually a body.  Just fall through into the code that handles it as a
1459       // prototype, and let the top-level code handle the erroneous declspec
1460       // where it would otherwise expect a comma or semicolon.
1461     } else {
1462       Diag(Tok, diag::err_expected_fn_body);
1463       SkipUntil(tok::semi);
1464       return DeclGroupPtrTy();
1465     }
1466   }
1467
1468   if (ParseAsmAttributesAfterDeclarator(D))
1469     return DeclGroupPtrTy();
1470
1471   // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1472   // must parse and analyze the for-range-initializer before the declaration is
1473   // analyzed.
1474   if (FRI && Tok.is(tok::colon)) {
1475     FRI->ColonLoc = ConsumeToken();
1476     if (Tok.is(tok::l_brace))
1477       FRI->RangeExpr = ParseBraceInitializer();
1478     else
1479       FRI->RangeExpr = ParseExpression();
1480     Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1481     Actions.ActOnCXXForRangeDecl(ThisDecl);
1482     Actions.FinalizeDeclaration(ThisDecl);
1483     D.complete(ThisDecl);
1484     return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, &ThisDecl, 1);
1485   }
1486
1487   SmallVector<Decl *, 8> DeclsInGroup;
1488   Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(D);
1489   if (LateParsedAttrs.size() > 0)
1490     ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
1491   D.complete(FirstDecl);
1492   if (FirstDecl)
1493     DeclsInGroup.push_back(FirstDecl);
1494
1495   bool ExpectSemi = Context != Declarator::ForContext;
1496   
1497   // If we don't have a comma, it is either the end of the list (a ';') or an
1498   // error, bail out.
1499   while (Tok.is(tok::comma)) {
1500     SourceLocation CommaLoc = ConsumeToken();
1501
1502     if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
1503       // This comma was followed by a line-break and something which can't be
1504       // the start of a declarator. The comma was probably a typo for a
1505       // semicolon.
1506       Diag(CommaLoc, diag::err_expected_semi_declaration)
1507         << FixItHint::CreateReplacement(CommaLoc, ";");
1508       ExpectSemi = false;
1509       break;
1510     }
1511
1512     // Parse the next declarator.
1513     D.clear();
1514     D.setCommaLoc(CommaLoc);
1515
1516     // Accept attributes in an init-declarator.  In the first declarator in a
1517     // declaration, these would be part of the declspec.  In subsequent
1518     // declarators, they become part of the declarator itself, so that they
1519     // don't apply to declarators after *this* one.  Examples:
1520     //    short __attribute__((common)) var;    -> declspec
1521     //    short var __attribute__((common));    -> declarator
1522     //    short x, __attribute__((common)) var;    -> declarator
1523     MaybeParseGNUAttributes(D);
1524
1525     ParseDeclarator(D);
1526     if (!D.isInvalidType()) {
1527       Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
1528       D.complete(ThisDecl);
1529       if (ThisDecl)
1530         DeclsInGroup.push_back(ThisDecl);
1531     }
1532   }
1533
1534   if (DeclEnd)
1535     *DeclEnd = Tok.getLocation();
1536
1537   if (ExpectSemi &&
1538       ExpectAndConsumeSemi(Context == Declarator::FileContext
1539                            ? diag::err_invalid_token_after_toplevel_declarator
1540                            : diag::err_expected_semi_declaration)) {
1541     // Okay, there was no semicolon and one was expected.  If we see a
1542     // declaration specifier, just assume it was missing and continue parsing.
1543     // Otherwise things are very confused and we skip to recover.
1544     if (!isDeclarationSpecifier()) {
1545       SkipUntil(tok::r_brace, true, true);
1546       if (Tok.is(tok::semi))
1547         ConsumeToken();
1548     }
1549   }
1550
1551   return Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
1552                                          DeclsInGroup.data(),
1553                                          DeclsInGroup.size());
1554 }
1555
1556 /// Parse an optional simple-asm-expr and attributes, and attach them to a
1557 /// declarator. Returns true on an error.
1558 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
1559   // If a simple-asm-expr is present, parse it.
1560   if (Tok.is(tok::kw_asm)) {
1561     SourceLocation Loc;
1562     ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1563     if (AsmLabel.isInvalid()) {
1564       SkipUntil(tok::semi, true, true);
1565       return true;
1566     }
1567
1568     D.setAsmLabel(AsmLabel.release());
1569     D.SetRangeEnd(Loc);
1570   }
1571
1572   MaybeParseGNUAttributes(D);
1573   return false;
1574 }
1575
1576 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
1577 /// declarator'. This method parses the remainder of the declaration
1578 /// (including any attributes or initializer, among other things) and
1579 /// finalizes the declaration.
1580 ///
1581 ///       init-declarator: [C99 6.7]
1582 ///         declarator
1583 ///         declarator '=' initializer
1584 /// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
1585 /// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
1586 /// [C++]   declarator initializer[opt]
1587 ///
1588 /// [C++] initializer:
1589 /// [C++]   '=' initializer-clause
1590 /// [C++]   '(' expression-list ')'
1591 /// [C++0x] '=' 'default'                                                [TODO]
1592 /// [C++0x] '=' 'delete'
1593 /// [C++0x] braced-init-list
1594 ///
1595 /// According to the standard grammar, =default and =delete are function
1596 /// definitions, but that definitely doesn't fit with the parser here.
1597 ///
1598 Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D,
1599                                      const ParsedTemplateInfo &TemplateInfo) {
1600   if (ParseAsmAttributesAfterDeclarator(D))
1601     return 0;
1602
1603   return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
1604 }
1605
1606 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
1607                                      const ParsedTemplateInfo &TemplateInfo) {
1608   // Inform the current actions module that we just parsed this declarator.
1609   Decl *ThisDecl = 0;
1610   switch (TemplateInfo.Kind) {
1611   case ParsedTemplateInfo::NonTemplate:
1612     ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1613     break;
1614
1615   case ParsedTemplateInfo::Template:
1616   case ParsedTemplateInfo::ExplicitSpecialization:
1617     ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
1618                                                *TemplateInfo.TemplateParams,
1619                                                D);
1620     break;
1621
1622   case ParsedTemplateInfo::ExplicitInstantiation: {
1623     DeclResult ThisRes
1624       = Actions.ActOnExplicitInstantiation(getCurScope(),
1625                                            TemplateInfo.ExternLoc,
1626                                            TemplateInfo.TemplateLoc,
1627                                            D);
1628     if (ThisRes.isInvalid()) {
1629       SkipUntil(tok::semi, true, true);
1630       return 0;
1631     }
1632
1633     ThisDecl = ThisRes.get();
1634     break;
1635     }
1636   }
1637
1638   bool TypeContainsAuto =
1639     D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
1640
1641   // Parse declarator '=' initializer.
1642   // If a '==' or '+=' is found, suggest a fixit to '='.
1643   if (isTokenEqualOrEqualTypo()) {
1644     ConsumeToken();
1645     if (Tok.is(tok::kw_delete)) {
1646       if (D.isFunctionDeclarator())
1647         Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1648           << 1 /* delete */;
1649       else
1650         Diag(ConsumeToken(), diag::err_deleted_non_function);
1651     } else if (Tok.is(tok::kw_default)) {
1652       if (D.isFunctionDeclarator())
1653         Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1654           << 0 /* default */;
1655       else
1656         Diag(ConsumeToken(), diag::err_default_special_members);
1657     } else {
1658       if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1659         EnterScope(0);
1660         Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1661       }
1662
1663       if (Tok.is(tok::code_completion)) {
1664         Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
1665         Actions.FinalizeDeclaration(ThisDecl);
1666         cutOffParsing();
1667         return 0;
1668       }
1669
1670       ExprResult Init(ParseInitializer());
1671
1672       if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1673         Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1674         ExitScope();
1675       }
1676
1677       if (Init.isInvalid()) {
1678         SkipUntil(tok::comma, true, true);
1679         Actions.ActOnInitializerError(ThisDecl);
1680       } else
1681         Actions.AddInitializerToDecl(ThisDecl, Init.take(),
1682                                      /*DirectInit=*/false, TypeContainsAuto);
1683     }
1684   } else if (Tok.is(tok::l_paren)) {
1685     // Parse C++ direct initializer: '(' expression-list ')'
1686     BalancedDelimiterTracker T(*this, tok::l_paren);
1687     T.consumeOpen();
1688
1689     ExprVector Exprs;
1690     CommaLocsTy CommaLocs;
1691
1692     if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1693       EnterScope(0);
1694       Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1695     }
1696
1697     if (ParseExpressionList(Exprs, CommaLocs)) {
1698       Actions.ActOnInitializerError(ThisDecl);
1699       SkipUntil(tok::r_paren);
1700
1701       if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1702         Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1703         ExitScope();
1704       }
1705     } else {
1706       // Match the ')'.
1707       T.consumeClose();
1708
1709       assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
1710              "Unexpected number of commas!");
1711
1712       if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1713         Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1714         ExitScope();
1715       }
1716
1717       ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
1718                                                           T.getCloseLocation(),
1719                                                           Exprs);
1720       Actions.AddInitializerToDecl(ThisDecl, Initializer.take(),
1721                                    /*DirectInit=*/true, TypeContainsAuto);
1722     }
1723   } else if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace) &&
1724              (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
1725     // Parse C++0x braced-init-list.
1726     Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1727
1728     if (D.getCXXScopeSpec().isSet()) {
1729       EnterScope(0);
1730       Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1731     }
1732
1733     ExprResult Init(ParseBraceInitializer());
1734
1735     if (D.getCXXScopeSpec().isSet()) {
1736       Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1737       ExitScope();
1738     }
1739
1740     if (Init.isInvalid()) {
1741       Actions.ActOnInitializerError(ThisDecl);
1742     } else
1743       Actions.AddInitializerToDecl(ThisDecl, Init.take(),
1744                                    /*DirectInit=*/true, TypeContainsAuto);
1745
1746   } else {
1747     Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
1748   }
1749
1750   Actions.FinalizeDeclaration(ThisDecl);
1751
1752   return ThisDecl;
1753 }
1754
1755 /// ParseSpecifierQualifierList
1756 ///        specifier-qualifier-list:
1757 ///          type-specifier specifier-qualifier-list[opt]
1758 ///          type-qualifier specifier-qualifier-list[opt]
1759 /// [GNU]    attributes     specifier-qualifier-list[opt]
1760 ///
1761 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
1762                                          DeclSpecContext DSC) {
1763   /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
1764   /// parse declaration-specifiers and complain about extra stuff.
1765   /// TODO: diagnose attribute-specifiers and alignment-specifiers.
1766   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
1767
1768   // Validate declspec for type-name.
1769   unsigned Specs = DS.getParsedSpecifiers();
1770   if ((DSC == DSC_type_specifier || DSC == DSC_trailing) &&
1771       !DS.hasTypeSpecifier()) {
1772     Diag(Tok, diag::err_expected_type);
1773     DS.SetTypeSpecError();
1774   } else if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
1775              !DS.hasAttributes()) {
1776     Diag(Tok, diag::err_typename_requires_specqual);
1777     if (!DS.hasTypeSpecifier())
1778       DS.SetTypeSpecError();
1779   }
1780
1781   // Issue diagnostic and remove storage class if present.
1782   if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
1783     if (DS.getStorageClassSpecLoc().isValid())
1784       Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
1785     else
1786       Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
1787     DS.ClearStorageClassSpecs();
1788   }
1789
1790   // Issue diagnostic and remove function specfier if present.
1791   if (Specs & DeclSpec::PQ_FunctionSpecifier) {
1792     if (DS.isInlineSpecified())
1793       Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
1794     if (DS.isVirtualSpecified())
1795       Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
1796     if (DS.isExplicitSpecified())
1797       Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
1798     DS.ClearFunctionSpecs();
1799   }
1800
1801   // Issue diagnostic and remove constexpr specfier if present.
1802   if (DS.isConstexprSpecified()) {
1803     Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
1804     DS.ClearConstexprSpec();
1805   }
1806 }
1807
1808 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
1809 /// specified token is valid after the identifier in a declarator which
1810 /// immediately follows the declspec.  For example, these things are valid:
1811 ///
1812 ///      int x   [             4];         // direct-declarator
1813 ///      int x   (             int y);     // direct-declarator
1814 ///  int(int x   )                         // direct-declarator
1815 ///      int x   ;                         // simple-declaration
1816 ///      int x   =             17;         // init-declarator-list
1817 ///      int x   ,             y;          // init-declarator-list
1818 ///      int x   __asm__       ("foo");    // init-declarator-list
1819 ///      int x   :             4;          // struct-declarator
1820 ///      int x   {             5};         // C++'0x unified initializers
1821 ///
1822 /// This is not, because 'x' does not immediately follow the declspec (though
1823 /// ')' happens to be valid anyway).
1824 ///    int (x)
1825 ///
1826 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
1827   return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
1828          T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
1829          T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
1830 }
1831
1832
1833 /// ParseImplicitInt - This method is called when we have an non-typename
1834 /// identifier in a declspec (which normally terminates the decl spec) when
1835 /// the declspec has no type specifier.  In this case, the declspec is either
1836 /// malformed or is "implicit int" (in K&R and C89).
1837 ///
1838 /// This method handles diagnosing this prettily and returns false if the
1839 /// declspec is done being processed.  If it recovers and thinks there may be
1840 /// other pieces of declspec after it, it returns true.
1841 ///
1842 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1843                               const ParsedTemplateInfo &TemplateInfo,
1844                               AccessSpecifier AS, DeclSpecContext DSC) {
1845   assert(Tok.is(tok::identifier) && "should have identifier");
1846
1847   SourceLocation Loc = Tok.getLocation();
1848   // If we see an identifier that is not a type name, we normally would
1849   // parse it as the identifer being declared.  However, when a typename
1850   // is typo'd or the definition is not included, this will incorrectly
1851   // parse the typename as the identifier name and fall over misparsing
1852   // later parts of the diagnostic.
1853   //
1854   // As such, we try to do some look-ahead in cases where this would
1855   // otherwise be an "implicit-int" case to see if this is invalid.  For
1856   // example: "static foo_t x = 4;"  In this case, if we parsed foo_t as
1857   // an identifier with implicit int, we'd get a parse error because the
1858   // next token is obviously invalid for a type.  Parse these as a case
1859   // with an invalid type specifier.
1860   assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
1861
1862   // Since we know that this either implicit int (which is rare) or an
1863   // error, do lookahead to try to do better recovery. This never applies
1864   // within a type specifier. Outside of C++, we allow this even if the
1865   // language doesn't "officially" support implicit int -- we support
1866   // implicit int as an extension in C99 and C11. Allegedly, MS also
1867   // supports implicit int in C++ mode.
1868   if (DSC != DSC_type_specifier && DSC != DSC_trailing &&
1869       (!getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt) &&
1870       isValidAfterIdentifierInDeclarator(NextToken())) {
1871     // If this token is valid for implicit int, e.g. "static x = 4", then
1872     // we just avoid eating the identifier, so it will be parsed as the
1873     // identifier in the declarator.
1874     return false;
1875   }
1876
1877   if (getLangOpts().CPlusPlus &&
1878       DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
1879     // Don't require a type specifier if we have the 'auto' storage class
1880     // specifier in C++98 -- we'll promote it to a type specifier.
1881     return false;
1882   }
1883
1884   // Otherwise, if we don't consume this token, we are going to emit an
1885   // error anyway.  Try to recover from various common problems.  Check
1886   // to see if this was a reference to a tag name without a tag specified.
1887   // This is a common problem in C (saying 'foo' instead of 'struct foo').
1888   //
1889   // C++ doesn't need this, and isTagName doesn't take SS.
1890   if (SS == 0) {
1891     const char *TagName = 0, *FixitTagName = 0;
1892     tok::TokenKind TagKind = tok::unknown;
1893
1894     switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
1895       default: break;
1896       case DeclSpec::TST_enum:
1897         TagName="enum"  ; FixitTagName = "enum "  ; TagKind=tok::kw_enum ;break;
1898       case DeclSpec::TST_union:
1899         TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
1900       case DeclSpec::TST_struct:
1901         TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
1902       case DeclSpec::TST_interface:
1903         TagName="__interface"; FixitTagName = "__interface ";
1904         TagKind=tok::kw___interface;break;
1905       case DeclSpec::TST_class:
1906         TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
1907     }
1908
1909     if (TagName) {
1910       IdentifierInfo *TokenName = Tok.getIdentifierInfo();
1911       LookupResult R(Actions, TokenName, SourceLocation(),
1912                      Sema::LookupOrdinaryName);
1913
1914       Diag(Loc, diag::err_use_of_tag_name_without_tag)
1915         << TokenName << TagName << getLangOpts().CPlusPlus
1916         << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
1917
1918       if (Actions.LookupParsedName(R, getCurScope(), SS)) {
1919         for (LookupResult::iterator I = R.begin(), IEnd = R.end();
1920              I != IEnd; ++I)
1921           Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
1922             << TokenName << TagName;
1923       }
1924
1925       // Parse this as a tag as if the missing tag were present.
1926       if (TagKind == tok::kw_enum)
1927         ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
1928       else
1929         ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
1930                             /*EnteringContext*/ false, DSC_normal);
1931       return true;
1932     }
1933   }
1934
1935   // Determine whether this identifier could plausibly be the name of something
1936   // being declared (with a missing type).
1937   if (DSC != DSC_type_specifier && DSC != DSC_trailing &&
1938       (!SS || DSC == DSC_top_level || DSC == DSC_class)) {
1939     // Look ahead to the next token to try to figure out what this declaration
1940     // was supposed to be.
1941     switch (NextToken().getKind()) {
1942     case tok::comma:
1943     case tok::equal:
1944     case tok::kw_asm:
1945     case tok::l_brace:
1946     case tok::l_square:
1947     case tok::semi:
1948       // This looks like a variable declaration. The type is probably missing.
1949       // We're done parsing decl-specifiers.
1950       return false;
1951
1952     case tok::l_paren: {
1953       // static x(4); // 'x' is not a type
1954       // x(int n);    // 'x' is not a type
1955       // x (*p)[];    // 'x' is a type
1956       //
1957       // Since we're in an error case (or the rare 'implicit int in C++' MS
1958       // extension), we can afford to perform a tentative parse to determine
1959       // which case we're in.
1960       TentativeParsingAction PA(*this);
1961       ConsumeToken();
1962       TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
1963       PA.Revert();
1964       if (TPR == TPResult::False())
1965         return false;
1966       // The identifier is followed by a parenthesized declarator.
1967       // It's supposed to be a type.
1968       break;
1969     }
1970
1971     default:
1972       // This is probably supposed to be a type. This includes cases like:
1973       //   int f(itn);
1974       //   struct S { unsinged : 4; };
1975       break;
1976     }
1977   }
1978
1979   // This is almost certainly an invalid type name. Let the action emit a
1980   // diagnostic and attempt to recover.
1981   ParsedType T;
1982   IdentifierInfo *II = Tok.getIdentifierInfo();
1983   if (Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T)) {
1984     // The action emitted a diagnostic, so we don't have to.
1985     if (T) {
1986       // The action has suggested that the type T could be used. Set that as
1987       // the type in the declaration specifiers, consume the would-be type
1988       // name token, and we're done.
1989       const char *PrevSpec;
1990       unsigned DiagID;
1991       DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T);
1992       DS.SetRangeEnd(Tok.getLocation());
1993       ConsumeToken();
1994       // There may be other declaration specifiers after this.
1995       return true;
1996     } else if (II != Tok.getIdentifierInfo()) {
1997       // If no type was suggested, the correction is to a keyword
1998       Tok.setKind(II->getTokenID());
1999       // There may be other declaration specifiers after this.
2000       return true;
2001     }
2002
2003     // Fall through; the action had no suggestion for us.
2004   } else {
2005     // The action did not emit a diagnostic, so emit one now.
2006     SourceRange R;
2007     if (SS) R = SS->getRange();
2008     Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
2009   }
2010
2011   // Mark this as an error.
2012   DS.SetTypeSpecError();
2013   DS.SetRangeEnd(Tok.getLocation());
2014   ConsumeToken();
2015
2016   // TODO: Could inject an invalid typedef decl in an enclosing scope to
2017   // avoid rippling error messages on subsequent uses of the same type,
2018   // could be useful if #include was forgotten.
2019   return false;
2020 }
2021
2022 /// \brief Determine the declaration specifier context from the declarator
2023 /// context.
2024 ///
2025 /// \param Context the declarator context, which is one of the
2026 /// Declarator::TheContext enumerator values.
2027 Parser::DeclSpecContext
2028 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
2029   if (Context == Declarator::MemberContext)
2030     return DSC_class;
2031   if (Context == Declarator::FileContext)
2032     return DSC_top_level;
2033   if (Context == Declarator::TrailingReturnContext)
2034     return DSC_trailing;
2035   return DSC_normal;
2036 }
2037
2038 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2039 ///
2040 /// FIXME: Simply returns an alignof() expression if the argument is a
2041 /// type. Ideally, the type should be propagated directly into Sema.
2042 ///
2043 /// [C11]   type-id
2044 /// [C11]   constant-expression
2045 /// [C++0x] type-id ...[opt]
2046 /// [C++0x] assignment-expression ...[opt]
2047 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2048                                       SourceLocation &EllipsisLoc) {
2049   ExprResult ER;
2050   if (isTypeIdInParens()) {
2051     SourceLocation TypeLoc = Tok.getLocation();
2052     ParsedType Ty = ParseTypeName().get();
2053     SourceRange TypeRange(Start, Tok.getLocation());
2054     ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2055                                                Ty.getAsOpaquePtr(), TypeRange);
2056   } else
2057     ER = ParseConstantExpression();
2058
2059   if (getLangOpts().CPlusPlus0x && Tok.is(tok::ellipsis))
2060     EllipsisLoc = ConsumeToken();
2061
2062   return ER;
2063 }
2064
2065 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2066 /// attribute to Attrs.
2067 ///
2068 /// alignment-specifier:
2069 /// [C11]   '_Alignas' '(' type-id ')'
2070 /// [C11]   '_Alignas' '(' constant-expression ')'
2071 /// [C++0x] 'alignas' '(' type-id ...[opt] ')'
2072 /// [C++0x] 'alignas' '(' assignment-expression ...[opt] ')'
2073 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2074                                      SourceLocation *endLoc) {
2075   assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) &&
2076          "Not an alignment-specifier!");
2077
2078   SourceLocation KWLoc = Tok.getLocation();
2079   ConsumeToken();
2080
2081   BalancedDelimiterTracker T(*this, tok::l_paren);
2082   if (T.expectAndConsume(diag::err_expected_lparen))
2083     return;
2084
2085   SourceLocation EllipsisLoc;
2086   ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2087   if (ArgExpr.isInvalid()) {
2088     SkipUntil(tok::r_paren);
2089     return;
2090   }
2091
2092   T.consumeClose();
2093   if (endLoc)
2094     *endLoc = T.getCloseLocation();
2095
2096   // FIXME: Handle pack-expansions here.
2097   if (EllipsisLoc.isValid()) {
2098     Diag(EllipsisLoc, diag::err_alignas_pack_exp_unsupported);
2099     return;
2100   }
2101
2102   ExprVector ArgExprs;
2103   ArgExprs.push_back(ArgExpr.release());
2104   // FIXME: This should not be GNU, but we since the attribute used is
2105   //        based on the spelling, and there is no true spelling for
2106   //        C++11 attributes, this isn't accepted.
2107   Attrs.addNew(PP.getIdentifierInfo("aligned"), KWLoc, 0, KWLoc,
2108                0, T.getOpenLocation(), ArgExprs.data(), 1,
2109                AttributeList::AS_GNU);
2110 }
2111
2112 /// ParseDeclarationSpecifiers
2113 ///       declaration-specifiers: [C99 6.7]
2114 ///         storage-class-specifier declaration-specifiers[opt]
2115 ///         type-specifier declaration-specifiers[opt]
2116 /// [C99]   function-specifier declaration-specifiers[opt]
2117 /// [C11]   alignment-specifier declaration-specifiers[opt]
2118 /// [GNU]   attributes declaration-specifiers[opt]
2119 /// [Clang] '__module_private__' declaration-specifiers[opt]
2120 ///
2121 ///       storage-class-specifier: [C99 6.7.1]
2122 ///         'typedef'
2123 ///         'extern'
2124 ///         'static'
2125 ///         'auto'
2126 ///         'register'
2127 /// [C++]   'mutable'
2128 /// [GNU]   '__thread'
2129 ///       function-specifier: [C99 6.7.4]
2130 /// [C99]   'inline'
2131 /// [C++]   'virtual'
2132 /// [C++]   'explicit'
2133 /// [OpenCL] '__kernel'
2134 ///       'friend': [C++ dcl.friend]
2135 ///       'constexpr': [C++0x dcl.constexpr]
2136
2137 ///
2138 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2139                                         const ParsedTemplateInfo &TemplateInfo,
2140                                         AccessSpecifier AS,
2141                                         DeclSpecContext DSContext,
2142                                         LateParsedAttrList *LateAttrs) {
2143   if (DS.getSourceRange().isInvalid()) {
2144     DS.SetRangeStart(Tok.getLocation());
2145     DS.SetRangeEnd(Tok.getLocation());
2146   }
2147
2148   bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2149   bool AttrsLastTime = false;
2150   ParsedAttributesWithRange attrs(AttrFactory);
2151   while (1) {
2152     bool isInvalid = false;
2153     const char *PrevSpec = 0;
2154     unsigned DiagID = 0;
2155
2156     SourceLocation Loc = Tok.getLocation();
2157
2158     switch (Tok.getKind()) {
2159     default:
2160     DoneWithDeclSpec:
2161       if (!AttrsLastTime)
2162         ProhibitAttributes(attrs);
2163       else {
2164         // Reject C++11 attributes that appertain to decl specifiers as
2165         // we don't support any C++11 attributes that appertain to decl
2166         // specifiers. This also conforms to what g++ 4.8 is doing.
2167         ProhibitCXX11Attributes(attrs);
2168
2169         DS.takeAttributesFrom(attrs);
2170       }
2171
2172       // If this is not a declaration specifier token, we're done reading decl
2173       // specifiers.  First verify that DeclSpec's are consistent.
2174       DS.Finish(Diags, PP);
2175       return;
2176
2177     case tok::l_square:
2178     case tok::kw_alignas:
2179       if (!isCXX11AttributeSpecifier())
2180         goto DoneWithDeclSpec;
2181
2182       ProhibitAttributes(attrs);
2183       // FIXME: It would be good to recover by accepting the attributes,
2184       //        but attempting to do that now would cause serious
2185       //        madness in terms of diagnostics.
2186       attrs.clear();
2187       attrs.Range = SourceRange();
2188
2189       ParseCXX11Attributes(attrs);
2190       AttrsLastTime = true;
2191       continue;
2192
2193     case tok::code_completion: {
2194       Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2195       if (DS.hasTypeSpecifier()) {
2196         bool AllowNonIdentifiers
2197           = (getCurScope()->getFlags() & (Scope::ControlScope |
2198                                           Scope::BlockScope |
2199                                           Scope::TemplateParamScope |
2200                                           Scope::FunctionPrototypeScope |
2201                                           Scope::AtCatchScope)) == 0;
2202         bool AllowNestedNameSpecifiers
2203           = DSContext == DSC_top_level ||
2204             (DSContext == DSC_class && DS.isFriendSpecified());
2205
2206         Actions.CodeCompleteDeclSpec(getCurScope(), DS,
2207                                      AllowNonIdentifiers,
2208                                      AllowNestedNameSpecifiers);
2209         return cutOffParsing();
2210       }
2211
2212       if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
2213         CCC = Sema::PCC_LocalDeclarationSpecifiers;
2214       else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
2215         CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
2216                                     : Sema::PCC_Template;
2217       else if (DSContext == DSC_class)
2218         CCC = Sema::PCC_Class;
2219       else if (CurParsedObjCImpl)
2220         CCC = Sema::PCC_ObjCImplementation;
2221
2222       Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
2223       return cutOffParsing();
2224     }
2225
2226     case tok::coloncolon: // ::foo::bar
2227       // C++ scope specifier.  Annotate and loop, or bail out on error.
2228       if (TryAnnotateCXXScopeToken(true)) {
2229         if (!DS.hasTypeSpecifier())
2230           DS.SetTypeSpecError();
2231         goto DoneWithDeclSpec;
2232       }
2233       if (Tok.is(tok::coloncolon)) // ::new or ::delete
2234         goto DoneWithDeclSpec;
2235       continue;
2236
2237     case tok::annot_cxxscope: {
2238       if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
2239         goto DoneWithDeclSpec;
2240
2241       CXXScopeSpec SS;
2242       Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2243                                                    Tok.getAnnotationRange(),
2244                                                    SS);
2245
2246       // We are looking for a qualified typename.
2247       Token Next = NextToken();
2248       if (Next.is(tok::annot_template_id) &&
2249           static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
2250             ->Kind == TNK_Type_template) {
2251         // We have a qualified template-id, e.g., N::A<int>
2252
2253         // C++ [class.qual]p2:
2254         //   In a lookup in which the constructor is an acceptable lookup
2255         //   result and the nested-name-specifier nominates a class C:
2256         //
2257         //     - if the name specified after the
2258         //       nested-name-specifier, when looked up in C, is the
2259         //       injected-class-name of C (Clause 9), or
2260         //
2261         //     - if the name specified after the nested-name-specifier
2262         //       is the same as the identifier or the
2263         //       simple-template-id's template-name in the last
2264         //       component of the nested-name-specifier,
2265         //
2266         //   the name is instead considered to name the constructor of
2267         //   class C.
2268         //
2269         // Thus, if the template-name is actually the constructor
2270         // name, then the code is ill-formed; this interpretation is
2271         // reinforced by the NAD status of core issue 635.
2272         TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
2273         if ((DSContext == DSC_top_level ||
2274              (DSContext == DSC_class && DS.isFriendSpecified())) &&
2275             TemplateId->Name &&
2276             Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2277           if (isConstructorDeclarator()) {
2278             // The user meant this to be an out-of-line constructor
2279             // definition, but template arguments are not allowed
2280             // there.  Just allow this as a constructor; we'll
2281             // complain about it later.
2282             goto DoneWithDeclSpec;
2283           }
2284
2285           // The user meant this to name a type, but it actually names
2286           // a constructor with some extraneous template
2287           // arguments. Complain, then parse it as a type as the user
2288           // intended.
2289           Diag(TemplateId->TemplateNameLoc,
2290                diag::err_out_of_line_template_id_names_constructor)
2291             << TemplateId->Name;
2292         }
2293
2294         DS.getTypeSpecScope() = SS;
2295         ConsumeToken(); // The C++ scope.
2296         assert(Tok.is(tok::annot_template_id) &&
2297                "ParseOptionalCXXScopeSpecifier not working");
2298         AnnotateTemplateIdTokenAsType();
2299         continue;
2300       }
2301
2302       if (Next.is(tok::annot_typename)) {
2303         DS.getTypeSpecScope() = SS;
2304         ConsumeToken(); // The C++ scope.
2305         if (Tok.getAnnotationValue()) {
2306           ParsedType T = getTypeAnnotation(Tok);
2307           isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
2308                                          Tok.getAnnotationEndLoc(),
2309                                          PrevSpec, DiagID, T);
2310           if (isInvalid)
2311             break;
2312         }
2313         else
2314           DS.SetTypeSpecError();
2315         DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2316         ConsumeToken(); // The typename
2317       }
2318
2319       if (Next.isNot(tok::identifier))
2320         goto DoneWithDeclSpec;
2321
2322       // If we're in a context where the identifier could be a class name,
2323       // check whether this is a constructor declaration.
2324       if ((DSContext == DSC_top_level ||
2325            (DSContext == DSC_class && DS.isFriendSpecified())) &&
2326           Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
2327                                      &SS)) {
2328         if (isConstructorDeclarator())
2329           goto DoneWithDeclSpec;
2330
2331         // As noted in C++ [class.qual]p2 (cited above), when the name
2332         // of the class is qualified in a context where it could name
2333         // a constructor, its a constructor name. However, we've
2334         // looked at the declarator, and the user probably meant this
2335         // to be a type. Complain that it isn't supposed to be treated
2336         // as a type, then proceed to parse it as a type.
2337         Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
2338           << Next.getIdentifierInfo();
2339       }
2340
2341       ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
2342                                                Next.getLocation(),
2343                                                getCurScope(), &SS,
2344                                                false, false, ParsedType(),
2345                                                /*IsCtorOrDtorName=*/false,
2346                                                /*NonTrivialSourceInfo=*/true);
2347
2348       // If the referenced identifier is not a type, then this declspec is
2349       // erroneous: We already checked about that it has no type specifier, and
2350       // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
2351       // typename.
2352       if (TypeRep == 0) {
2353         ConsumeToken();   // Eat the scope spec so the identifier is current.
2354         if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext)) continue;
2355         goto DoneWithDeclSpec;
2356       }
2357
2358       DS.getTypeSpecScope() = SS;
2359       ConsumeToken(); // The C++ scope.
2360
2361       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2362                                      DiagID, TypeRep);
2363       if (isInvalid)
2364         break;
2365
2366       DS.SetRangeEnd(Tok.getLocation());
2367       ConsumeToken(); // The typename.
2368
2369       continue;
2370     }
2371
2372     case tok::annot_typename: {
2373       if (Tok.getAnnotationValue()) {
2374         ParsedType T = getTypeAnnotation(Tok);
2375         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2376                                        DiagID, T);
2377       } else
2378         DS.SetTypeSpecError();
2379
2380       if (isInvalid)
2381         break;
2382
2383       DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2384       ConsumeToken(); // The typename
2385
2386       // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2387       // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2388       // Objective-C interface.
2389       if (Tok.is(tok::less) && getLangOpts().ObjC1)
2390         ParseObjCProtocolQualifiers(DS);
2391
2392       continue;
2393     }
2394
2395     case tok::kw___is_signed:
2396       // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
2397       // typically treats it as a trait. If we see __is_signed as it appears
2398       // in libstdc++, e.g.,
2399       //
2400       //   static const bool __is_signed;
2401       //
2402       // then treat __is_signed as an identifier rather than as a keyword.
2403       if (DS.getTypeSpecType() == TST_bool &&
2404           DS.getTypeQualifiers() == DeclSpec::TQ_const &&
2405           DS.getStorageClassSpec() == DeclSpec::SCS_static) {
2406         Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
2407         Tok.setKind(tok::identifier);
2408       }
2409
2410       // We're done with the declaration-specifiers.
2411       goto DoneWithDeclSpec;
2412
2413       // typedef-name
2414     case tok::kw_decltype:
2415     case tok::identifier: {
2416       // In C++, check to see if this is a scope specifier like foo::bar::, if
2417       // so handle it as such.  This is important for ctor parsing.
2418       if (getLangOpts().CPlusPlus) {
2419         if (TryAnnotateCXXScopeToken(true)) {
2420           if (!DS.hasTypeSpecifier())
2421             DS.SetTypeSpecError();
2422           goto DoneWithDeclSpec;
2423         }
2424         if (!Tok.is(tok::identifier))
2425           continue;
2426       }
2427
2428       // This identifier can only be a typedef name if we haven't already seen
2429       // a type-specifier.  Without this check we misparse:
2430       //  typedef int X; struct Y { short X; };  as 'short int'.
2431       if (DS.hasTypeSpecifier())
2432         goto DoneWithDeclSpec;
2433
2434       // Check for need to substitute AltiVec keyword tokens.
2435       if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
2436         break;
2437
2438       // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
2439       //                allow the use of a typedef name as a type specifier.
2440       if (DS.isTypeAltiVecVector())
2441         goto DoneWithDeclSpec;
2442
2443       ParsedType TypeRep =
2444         Actions.getTypeName(*Tok.getIdentifierInfo(),
2445                             Tok.getLocation(), getCurScope());
2446
2447       // If this is not a typedef name, don't parse it as part of the declspec,
2448       // it must be an implicit int or an error.
2449       if (!TypeRep) {
2450         if (ParseImplicitInt(DS, 0, TemplateInfo, AS, DSContext)) continue;
2451         goto DoneWithDeclSpec;
2452       }
2453
2454       // If we're in a context where the identifier could be a class name,
2455       // check whether this is a constructor declaration.
2456       if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2457           Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
2458           isConstructorDeclarator())
2459         goto DoneWithDeclSpec;
2460
2461       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2462                                      DiagID, TypeRep);
2463       if (isInvalid)
2464         break;
2465
2466       DS.SetRangeEnd(Tok.getLocation());
2467       ConsumeToken(); // The identifier
2468
2469       // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2470       // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2471       // Objective-C interface.
2472       if (Tok.is(tok::less) && getLangOpts().ObjC1)
2473         ParseObjCProtocolQualifiers(DS);
2474
2475       // Need to support trailing type qualifiers (e.g. "id<p> const").
2476       // If a type specifier follows, it will be diagnosed elsewhere.
2477       continue;
2478     }
2479
2480       // type-name
2481     case tok::annot_template_id: {
2482       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2483       if (TemplateId->Kind != TNK_Type_template) {
2484         // This template-id does not refer to a type name, so we're
2485         // done with the type-specifiers.
2486         goto DoneWithDeclSpec;
2487       }
2488
2489       // If we're in a context where the template-id could be a
2490       // constructor name or specialization, check whether this is a
2491       // constructor declaration.
2492       if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2493           Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
2494           isConstructorDeclarator())
2495         goto DoneWithDeclSpec;
2496
2497       // Turn the template-id annotation token into a type annotation
2498       // token, then try again to parse it as a type-specifier.
2499       AnnotateTemplateIdTokenAsType();
2500       continue;
2501     }
2502
2503     // GNU attributes support.
2504     case tok::kw___attribute:
2505       ParseGNUAttributes(DS.getAttributes(), 0, LateAttrs);
2506       continue;
2507
2508     // Microsoft declspec support.
2509     case tok::kw___declspec:
2510       ParseMicrosoftDeclSpec(DS.getAttributes());
2511       continue;
2512
2513     // Microsoft single token adornments.
2514     case tok::kw___forceinline: {
2515       isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
2516       IdentifierInfo *AttrName = Tok.getIdentifierInfo();
2517       SourceLocation AttrNameLoc = Tok.getLocation();
2518       // FIXME: This does not work correctly if it is set to be a declspec
2519       //        attribute, and a GNU attribute is simply incorrect.
2520       DS.getAttributes().addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
2521                                 SourceLocation(), 0, 0, AttributeList::AS_GNU);
2522       break;
2523     }
2524
2525     case tok::kw___ptr64:
2526     case tok::kw___ptr32:
2527     case tok::kw___w64:
2528     case tok::kw___cdecl:
2529     case tok::kw___stdcall:
2530     case tok::kw___fastcall:
2531     case tok::kw___thiscall:
2532     case tok::kw___unaligned:
2533       ParseMicrosoftTypeAttributes(DS.getAttributes());
2534       continue;
2535
2536     // Borland single token adornments.
2537     case tok::kw___pascal:
2538       ParseBorlandTypeAttributes(DS.getAttributes());
2539       continue;
2540
2541     // OpenCL single token adornments.
2542     case tok::kw___kernel:
2543       ParseOpenCLAttributes(DS.getAttributes());
2544       continue;
2545
2546     // storage-class-specifier
2547     case tok::kw_typedef:
2548       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
2549                                          PrevSpec, DiagID);
2550       break;
2551     case tok::kw_extern:
2552       if (DS.isThreadSpecified())
2553         Diag(Tok, diag::ext_thread_before) << "extern";
2554       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
2555                                          PrevSpec, DiagID);
2556       break;
2557     case tok::kw___private_extern__:
2558       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
2559                                          Loc, PrevSpec, DiagID);
2560       break;
2561     case tok::kw_static:
2562       if (DS.isThreadSpecified())
2563         Diag(Tok, diag::ext_thread_before) << "static";
2564       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
2565                                          PrevSpec, DiagID);
2566       break;
2567     case tok::kw_auto:
2568       if (getLangOpts().CPlusPlus0x) {
2569         if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
2570           isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
2571                                              PrevSpec, DiagID);
2572           if (!isInvalid)
2573             Diag(Tok, diag::ext_auto_storage_class)
2574               << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
2575         } else
2576           isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
2577                                          DiagID);
2578       } else
2579         isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
2580                                            PrevSpec, DiagID);
2581       break;
2582     case tok::kw_register:
2583       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
2584                                          PrevSpec, DiagID);
2585       break;
2586     case tok::kw_mutable:
2587       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
2588                                          PrevSpec, DiagID);
2589       break;
2590     case tok::kw___thread:
2591       isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
2592       break;
2593
2594     // function-specifier
2595     case tok::kw_inline:
2596       isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
2597       break;
2598     case tok::kw_virtual:
2599       isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
2600       break;
2601     case tok::kw_explicit:
2602       isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
2603       break;
2604
2605     // alignment-specifier
2606     case tok::kw__Alignas:
2607       if (!getLangOpts().C11)
2608         Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
2609       ParseAlignmentSpecifier(DS.getAttributes());
2610       continue;
2611
2612     // friend
2613     case tok::kw_friend:
2614       if (DSContext == DSC_class)
2615         isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
2616       else {
2617         PrevSpec = ""; // not actually used by the diagnostic
2618         DiagID = diag::err_friend_invalid_in_context;
2619         isInvalid = true;
2620       }
2621       break;
2622
2623     // Modules
2624     case tok::kw___module_private__:
2625       isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
2626       break;
2627
2628     // constexpr
2629     case tok::kw_constexpr:
2630       isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
2631       break;
2632
2633     // type-specifier
2634     case tok::kw_short:
2635       isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
2636                                       DiagID);
2637       break;
2638     case tok::kw_long:
2639       if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
2640         isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
2641                                         DiagID);
2642       else
2643         isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2644                                         DiagID);
2645       break;
2646     case tok::kw___int64:
2647         isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2648                                         DiagID);
2649       break;
2650     case tok::kw_signed:
2651       isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
2652                                      DiagID);
2653       break;
2654     case tok::kw_unsigned:
2655       isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
2656                                      DiagID);
2657       break;
2658     case tok::kw__Complex:
2659       isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
2660                                         DiagID);
2661       break;
2662     case tok::kw__Imaginary:
2663       isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
2664                                         DiagID);
2665       break;
2666     case tok::kw_void:
2667       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
2668                                      DiagID);
2669       break;
2670     case tok::kw_char:
2671       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
2672                                      DiagID);
2673       break;
2674     case tok::kw_int:
2675       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
2676                                      DiagID);
2677       break;
2678     case tok::kw___int128:
2679       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
2680                                      DiagID);
2681       break;
2682     case tok::kw_half:
2683       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
2684                                      DiagID);
2685       break;
2686     case tok::kw_float:
2687       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
2688                                      DiagID);
2689       break;
2690     case tok::kw_double:
2691       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
2692                                      DiagID);
2693       break;
2694     case tok::kw_wchar_t:
2695       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
2696                                      DiagID);
2697       break;
2698     case tok::kw_char16_t:
2699       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
2700                                      DiagID);
2701       break;
2702     case tok::kw_char32_t:
2703       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
2704                                      DiagID);
2705       break;
2706     case tok::kw_bool:
2707     case tok::kw__Bool:
2708       if (Tok.is(tok::kw_bool) &&
2709           DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
2710           DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2711         PrevSpec = ""; // Not used by the diagnostic.
2712         DiagID = diag::err_bool_redeclaration;
2713         // For better error recovery.
2714         Tok.setKind(tok::identifier);
2715         isInvalid = true;
2716       } else {
2717         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
2718                                        DiagID);
2719       }
2720       break;
2721     case tok::kw__Decimal32:
2722       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
2723                                      DiagID);
2724       break;
2725     case tok::kw__Decimal64:
2726       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
2727                                      DiagID);
2728       break;
2729     case tok::kw__Decimal128:
2730       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
2731                                      DiagID);
2732       break;
2733     case tok::kw___vector:
2734       isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
2735       break;
2736     case tok::kw___pixel:
2737       isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
2738       break;
2739     case tok::kw___unknown_anytype:
2740       isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
2741                                      PrevSpec, DiagID);
2742       break;
2743
2744     // class-specifier:
2745     case tok::kw_class:
2746     case tok::kw_struct:
2747     case tok::kw___interface:
2748     case tok::kw_union: {
2749       tok::TokenKind Kind = Tok.getKind();
2750       ConsumeToken();
2751       ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
2752                           EnteringContext, DSContext);
2753       continue;
2754     }
2755
2756     // enum-specifier:
2757     case tok::kw_enum:
2758       ConsumeToken();
2759       ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
2760       continue;
2761
2762     // cv-qualifier:
2763     case tok::kw_const:
2764       isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
2765                                  getLangOpts());
2766       break;
2767     case tok::kw_volatile:
2768       isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
2769                                  getLangOpts());
2770       break;
2771     case tok::kw_restrict:
2772       isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
2773                                  getLangOpts());
2774       break;
2775
2776     // C++ typename-specifier:
2777     case tok::kw_typename:
2778       if (TryAnnotateTypeOrScopeToken()) {
2779         DS.SetTypeSpecError();
2780         goto DoneWithDeclSpec;
2781       }
2782       if (!Tok.is(tok::kw_typename))
2783         continue;
2784       break;
2785
2786     // GNU typeof support.
2787     case tok::kw_typeof:
2788       ParseTypeofSpecifier(DS);
2789       continue;
2790
2791     case tok::annot_decltype:
2792       ParseDecltypeSpecifier(DS);
2793       continue;
2794
2795     case tok::kw___underlying_type:
2796       ParseUnderlyingTypeSpecifier(DS);
2797       continue;
2798
2799     case tok::kw__Atomic:
2800       ParseAtomicSpecifier(DS);
2801       continue;
2802
2803     // OpenCL qualifiers:
2804     case tok::kw_private:
2805       if (!getLangOpts().OpenCL)
2806         goto DoneWithDeclSpec;
2807     case tok::kw___private:
2808     case tok::kw___global:
2809     case tok::kw___local:
2810     case tok::kw___constant:
2811     case tok::kw___read_only:
2812     case tok::kw___write_only:
2813     case tok::kw___read_write:
2814       ParseOpenCLQualifiers(DS);
2815       break;
2816
2817     case tok::less:
2818       // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
2819       // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
2820       // but we support it.
2821       if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
2822         goto DoneWithDeclSpec;
2823
2824       if (!ParseObjCProtocolQualifiers(DS))
2825         Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
2826           << FixItHint::CreateInsertion(Loc, "id")
2827           << SourceRange(Loc, DS.getSourceRange().getEnd());
2828
2829       // Need to support trailing type qualifiers (e.g. "id<p> const").
2830       // If a type specifier follows, it will be diagnosed elsewhere.
2831       continue;
2832     }
2833     // If the specifier wasn't legal, issue a diagnostic.
2834     if (isInvalid) {
2835       assert(PrevSpec && "Method did not return previous specifier!");
2836       assert(DiagID);
2837
2838       if (DiagID == diag::ext_duplicate_declspec)
2839         Diag(Tok, DiagID)
2840           << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
2841       else
2842         Diag(Tok, DiagID) << PrevSpec;
2843     }
2844
2845     DS.SetRangeEnd(Tok.getLocation());
2846     if (DiagID != diag::err_bool_redeclaration)
2847       ConsumeToken();
2848
2849     AttrsLastTime = false;
2850   }
2851 }
2852
2853 /// ParseStructDeclaration - Parse a struct declaration without the terminating
2854 /// semicolon.
2855 ///
2856 ///       struct-declaration:
2857 ///         specifier-qualifier-list struct-declarator-list
2858 /// [GNU]   __extension__ struct-declaration
2859 /// [GNU]   specifier-qualifier-list
2860 ///       struct-declarator-list:
2861 ///         struct-declarator
2862 ///         struct-declarator-list ',' struct-declarator
2863 /// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
2864 ///       struct-declarator:
2865 ///         declarator
2866 /// [GNU]   declarator attributes[opt]
2867 ///         declarator[opt] ':' constant-expression
2868 /// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
2869 ///
2870 void Parser::
2871 ParseStructDeclaration(ParsingDeclSpec &DS, FieldCallback &Fields) {
2872
2873   if (Tok.is(tok::kw___extension__)) {
2874     // __extension__ silences extension warnings in the subexpression.
2875     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
2876     ConsumeToken();
2877     return ParseStructDeclaration(DS, Fields);
2878   }
2879
2880   // Parse the common specifier-qualifiers-list piece.
2881   ParseSpecifierQualifierList(DS);
2882
2883   // If there are no declarators, this is a free-standing declaration
2884   // specifier. Let the actions module cope with it.
2885   if (Tok.is(tok::semi)) {
2886     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
2887                                                        DS);
2888     DS.complete(TheDecl);
2889     return;
2890   }
2891
2892   // Read struct-declarators until we find the semicolon.
2893   bool FirstDeclarator = true;
2894   SourceLocation CommaLoc;
2895   while (1) {
2896     ParsingFieldDeclarator DeclaratorInfo(*this, DS);
2897     DeclaratorInfo.D.setCommaLoc(CommaLoc);
2898
2899     // Attributes are only allowed here on successive declarators.
2900     if (!FirstDeclarator)
2901       MaybeParseGNUAttributes(DeclaratorInfo.D);
2902
2903     /// struct-declarator: declarator
2904     /// struct-declarator: declarator[opt] ':' constant-expression
2905     if (Tok.isNot(tok::colon)) {
2906       // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
2907       ColonProtectionRAIIObject X(*this);
2908       ParseDeclarator(DeclaratorInfo.D);
2909     }
2910
2911     if (Tok.is(tok::colon)) {
2912       ConsumeToken();
2913       ExprResult Res(ParseConstantExpression());
2914       if (Res.isInvalid())
2915         SkipUntil(tok::semi, true, true);
2916       else
2917         DeclaratorInfo.BitfieldSize = Res.release();
2918     }
2919
2920     // If attributes exist after the declarator, parse them.
2921     MaybeParseGNUAttributes(DeclaratorInfo.D);
2922
2923     // We're done with this declarator;  invoke the callback.
2924     Fields.invoke(DeclaratorInfo);
2925
2926     // If we don't have a comma, it is either the end of the list (a ';')
2927     // or an error, bail out.
2928     if (Tok.isNot(tok::comma))
2929       return;
2930
2931     // Consume the comma.
2932     CommaLoc = ConsumeToken();
2933
2934     FirstDeclarator = false;
2935   }
2936 }
2937
2938 /// ParseStructUnionBody
2939 ///       struct-contents:
2940 ///         struct-declaration-list
2941 /// [EXT]   empty
2942 /// [GNU]   "struct-declaration-list" without terminatoring ';'
2943 ///       struct-declaration-list:
2944 ///         struct-declaration
2945 ///         struct-declaration-list struct-declaration
2946 /// [OBC]   '@' 'defs' '(' class-name ')'
2947 ///
2948 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
2949                                   unsigned TagType, Decl *TagDecl) {
2950   PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2951                                       "parsing struct/union body");
2952
2953   BalancedDelimiterTracker T(*this, tok::l_brace);
2954   if (T.consumeOpen())
2955     return;
2956
2957   ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
2958   Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2959
2960   // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
2961   // C++.
2962   if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) {
2963     Diag(Tok, diag::ext_empty_struct_union) << (TagType == TST_union);
2964     Diag(Tok, diag::warn_empty_struct_union_compat) << (TagType == TST_union);
2965   }
2966
2967   SmallVector<Decl *, 32> FieldDecls;
2968
2969   // While we still have something to read, read the declarations in the struct.
2970   while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
2971     // Each iteration of this loop reads one struct-declaration.
2972
2973     // Check for extraneous top-level semicolon.
2974     if (Tok.is(tok::semi)) {
2975       ConsumeExtraSemi(InsideStruct, TagType);
2976       continue;
2977     }
2978
2979     if (!Tok.is(tok::at)) {
2980       struct CFieldCallback : FieldCallback {
2981         Parser &P;
2982         Decl *TagDecl;
2983         SmallVectorImpl<Decl *> &FieldDecls;
2984
2985         CFieldCallback(Parser &P, Decl *TagDecl,
2986                        SmallVectorImpl<Decl *> &FieldDecls) :
2987           P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
2988
2989         void invoke(ParsingFieldDeclarator &FD) {
2990           // Install the declarator into the current TagDecl.
2991           Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl,
2992                               FD.D.getDeclSpec().getSourceRange().getBegin(),
2993                                                  FD.D, FD.BitfieldSize);
2994           FieldDecls.push_back(Field);
2995           FD.complete(Field);
2996         }
2997       } Callback(*this, TagDecl, FieldDecls);
2998
2999       // Parse all the comma separated declarators.
3000       ParsingDeclSpec DS(*this);
3001       ParseStructDeclaration(DS, Callback);
3002     } else { // Handle @defs
3003       ConsumeToken();
3004       if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
3005         Diag(Tok, diag::err_unexpected_at);
3006         SkipUntil(tok::semi, true);
3007         continue;
3008       }
3009       ConsumeToken();
3010       ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
3011       if (!Tok.is(tok::identifier)) {
3012         Diag(Tok, diag::err_expected_ident);
3013         SkipUntil(tok::semi, true);
3014         continue;
3015       }
3016       SmallVector<Decl *, 16> Fields;
3017       Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
3018                         Tok.getIdentifierInfo(), Fields);
3019       FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
3020       ConsumeToken();
3021       ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
3022     }
3023
3024     if (Tok.is(tok::semi)) {
3025       ConsumeToken();
3026     } else if (Tok.is(tok::r_brace)) {
3027       ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
3028       break;
3029     } else {
3030       ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
3031       // Skip to end of block or statement to avoid ext-warning on extra ';'.
3032       SkipUntil(tok::r_brace, true, true);
3033       // If we stopped at a ';', eat it.
3034       if (Tok.is(tok::semi)) ConsumeToken();
3035     }
3036   }
3037
3038   T.consumeClose();
3039
3040   ParsedAttributes attrs(AttrFactory);
3041   // If attributes exist after struct contents, parse them.
3042   MaybeParseGNUAttributes(attrs);
3043
3044   Actions.ActOnFields(getCurScope(),
3045                       RecordLoc, TagDecl, FieldDecls,
3046                       T.getOpenLocation(), T.getCloseLocation(),
3047                       attrs.getList());
3048   StructScope.Exit();
3049   Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
3050                                    T.getCloseLocation());
3051 }
3052
3053 /// ParseEnumSpecifier
3054 ///       enum-specifier: [C99 6.7.2.2]
3055 ///         'enum' identifier[opt] '{' enumerator-list '}'
3056 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
3057 /// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
3058 ///                                                 '}' attributes[opt]
3059 /// [MS]    'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
3060 ///                                                 '}'
3061 ///         'enum' identifier
3062 /// [GNU]   'enum' attributes[opt] identifier
3063 ///
3064 /// [C++11] enum-head '{' enumerator-list[opt] '}'
3065 /// [C++11] enum-head '{' enumerator-list ','  '}'
3066 ///
3067 ///       enum-head: [C++11]
3068 ///         enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
3069 ///         enum-key attribute-specifier-seq[opt] nested-name-specifier
3070 ///             identifier enum-base[opt]
3071 ///
3072 ///       enum-key: [C++11]
3073 ///         'enum'
3074 ///         'enum' 'class'
3075 ///         'enum' 'struct'
3076 ///
3077 ///       enum-base: [C++11]
3078 ///         ':' type-specifier-seq
3079 ///
3080 /// [C++] elaborated-type-specifier:
3081 /// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
3082 ///
3083 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
3084                                 const ParsedTemplateInfo &TemplateInfo,
3085                                 AccessSpecifier AS, DeclSpecContext DSC) {
3086   // Parse the tag portion of this.
3087   if (Tok.is(tok::code_completion)) {
3088     // Code completion for an enum name.
3089     Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
3090     return cutOffParsing();
3091   }
3092
3093   // If attributes exist after tag, parse them.
3094   ParsedAttributesWithRange attrs(AttrFactory);
3095   MaybeParseGNUAttributes(attrs);
3096   MaybeParseCXX0XAttributes(attrs);
3097
3098   // If declspecs exist after tag, parse them.
3099   while (Tok.is(tok::kw___declspec))
3100     ParseMicrosoftDeclSpec(attrs);
3101
3102   SourceLocation ScopedEnumKWLoc;
3103   bool IsScopedUsingClassTag = false;
3104
3105   // In C++11, recognize 'enum class' and 'enum struct'.
3106   if (getLangOpts().CPlusPlus0x &&
3107       (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) {
3108     Diag(Tok, diag::warn_cxx98_compat_scoped_enum);
3109     IsScopedUsingClassTag = Tok.is(tok::kw_class);
3110     ScopedEnumKWLoc = ConsumeToken();
3111
3112     // Attributes are not allowed between these keywords.  Diagnose,
3113     // but then just treat them like they appeared in the right place.
3114     ProhibitAttributes(attrs);
3115
3116     // They are allowed afterwards, though.
3117     MaybeParseGNUAttributes(attrs);
3118     MaybeParseCXX0XAttributes(attrs);
3119     while (Tok.is(tok::kw___declspec))
3120       ParseMicrosoftDeclSpec(attrs);
3121   }
3122
3123   // C++11 [temp.explicit]p12:
3124   //   The usual access controls do not apply to names used to specify
3125   //   explicit instantiations.
3126   // We extend this to also cover explicit specializations.  Note that
3127   // we don't suppress if this turns out to be an elaborated type
3128   // specifier.
3129   bool shouldDelayDiagsInTag =
3130     (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3131      TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3132   SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
3133
3134   // Enum definitions should not be parsed in a trailing-return-type.
3135   bool AllowDeclaration = DSC != DSC_trailing;
3136
3137   bool AllowFixedUnderlyingType = AllowDeclaration &&
3138     (getLangOpts().CPlusPlus0x || getLangOpts().MicrosoftExt ||
3139      getLangOpts().ObjC2);
3140
3141   CXXScopeSpec &SS = DS.getTypeSpecScope();
3142   if (getLangOpts().CPlusPlus) {
3143     // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
3144     // if a fixed underlying type is allowed.
3145     ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
3146
3147     if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
3148                                        /*EnteringContext=*/false))
3149       return;
3150
3151     if (SS.isSet() && Tok.isNot(tok::identifier)) {
3152       Diag(Tok, diag::err_expected_ident);
3153       if (Tok.isNot(tok::l_brace)) {
3154         // Has no name and is not a definition.
3155         // Skip the rest of this declarator, up until the comma or semicolon.
3156         SkipUntil(tok::comma, true);
3157         return;
3158       }
3159     }
3160   }
3161
3162   // Must have either 'enum name' or 'enum {...}'.
3163   if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
3164       !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
3165     Diag(Tok, diag::err_expected_ident_lbrace);
3166
3167     // Skip the rest of this declarator, up until the comma or semicolon.
3168     SkipUntil(tok::comma, true);
3169     return;
3170   }
3171
3172   // If an identifier is present, consume and remember it.
3173   IdentifierInfo *Name = 0;
3174   SourceLocation NameLoc;
3175   if (Tok.is(tok::identifier)) {
3176     Name = Tok.getIdentifierInfo();
3177     NameLoc = ConsumeToken();
3178   }
3179
3180   if (!Name && ScopedEnumKWLoc.isValid()) {
3181     // C++0x 7.2p2: The optional identifier shall not be omitted in the
3182     // declaration of a scoped enumeration.
3183     Diag(Tok, diag::err_scoped_enum_missing_identifier);
3184     ScopedEnumKWLoc = SourceLocation();
3185     IsScopedUsingClassTag = false;
3186   }
3187
3188   // Okay, end the suppression area.  We'll decide whether to emit the
3189   // diagnostics in a second.
3190   if (shouldDelayDiagsInTag)
3191     diagsFromTag.done();
3192
3193   TypeResult BaseType;
3194
3195   // Parse the fixed underlying type.
3196   bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
3197   if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
3198     bool PossibleBitfield = false;
3199     if (CanBeBitfield) {
3200       // If we're in class scope, this can either be an enum declaration with
3201       // an underlying type, or a declaration of a bitfield member. We try to
3202       // use a simple disambiguation scheme first to catch the common cases
3203       // (integer literal, sizeof); if it's still ambiguous, we then consider
3204       // anything that's a simple-type-specifier followed by '(' as an
3205       // expression. This suffices because function types are not valid
3206       // underlying types anyway.
3207       EnterExpressionEvaluationContext Unevaluated(Actions,
3208                                                    Sema::ConstantEvaluated);
3209       TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
3210       // If the next token starts an expression, we know we're parsing a
3211       // bit-field. This is the common case.
3212       if (TPR == TPResult::True())
3213         PossibleBitfield = true;
3214       // If the next token starts a type-specifier-seq, it may be either a
3215       // a fixed underlying type or the start of a function-style cast in C++;
3216       // lookahead one more token to see if it's obvious that we have a
3217       // fixed underlying type.
3218       else if (TPR == TPResult::False() &&
3219                GetLookAheadToken(2).getKind() == tok::semi) {
3220         // Consume the ':'.
3221         ConsumeToken();
3222       } else {
3223         // We have the start of a type-specifier-seq, so we have to perform
3224         // tentative parsing to determine whether we have an expression or a
3225         // type.
3226         TentativeParsingAction TPA(*this);
3227
3228         // Consume the ':'.
3229         ConsumeToken();
3230
3231         // If we see a type specifier followed by an open-brace, we have an
3232         // ambiguity between an underlying type and a C++11 braced
3233         // function-style cast. Resolve this by always treating it as an
3234         // underlying type.
3235         // FIXME: The standard is not entirely clear on how to disambiguate in
3236         // this case.
3237         if ((getLangOpts().CPlusPlus &&
3238              isCXXDeclarationSpecifier(TPResult::True()) != TPResult::True()) ||
3239             (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
3240           // We'll parse this as a bitfield later.
3241           PossibleBitfield = true;
3242           TPA.Revert();
3243         } else {
3244           // We have a type-specifier-seq.
3245           TPA.Commit();
3246         }
3247       }
3248     } else {
3249       // Consume the ':'.
3250       ConsumeToken();
3251     }
3252
3253     if (!PossibleBitfield) {
3254       SourceRange Range;
3255       BaseType = ParseTypeName(&Range);
3256
3257       if (getLangOpts().CPlusPlus0x) {
3258         Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
3259       } else if (!getLangOpts().ObjC2) {
3260         if (getLangOpts().CPlusPlus)
3261           Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
3262         else
3263           Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
3264       }
3265     }
3266   }
3267
3268   // There are four options here.  If we have 'friend enum foo;' then this is a
3269   // friend declaration, and cannot have an accompanying definition. If we have
3270   // 'enum foo;', then this is a forward declaration.  If we have
3271   // 'enum foo {...' then this is a definition. Otherwise we have something
3272   // like 'enum foo xyz', a reference.
3273   //
3274   // This is needed to handle stuff like this right (C99 6.7.2.3p11):
3275   // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
3276   // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
3277   //
3278   Sema::TagUseKind TUK;
3279   if (!AllowDeclaration) {
3280     TUK = Sema::TUK_Reference;
3281   } else if (Tok.is(tok::l_brace)) {
3282     if (DS.isFriendSpecified()) {
3283       Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
3284         << SourceRange(DS.getFriendSpecLoc());
3285       ConsumeBrace();
3286       SkipUntil(tok::r_brace);
3287       TUK = Sema::TUK_Friend;
3288     } else {
3289       TUK = Sema::TUK_Definition;
3290     }
3291   } else if (DSC != DSC_type_specifier &&
3292              (Tok.is(tok::semi) ||
3293               (Tok.isAtStartOfLine() &&
3294                !isValidAfterTypeSpecifier(CanBeBitfield)))) {
3295     TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
3296     if (Tok.isNot(tok::semi)) {
3297       // A semicolon was missing after this declaration. Diagnose and recover.
3298       ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
3299                        "enum");
3300       PP.EnterToken(Tok);
3301       Tok.setKind(tok::semi);
3302     }
3303   } else {
3304     TUK = Sema::TUK_Reference;
3305   }
3306
3307   // If this is an elaborated type specifier, and we delayed
3308   // diagnostics before, just merge them into the current pool.
3309   if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
3310     diagsFromTag.redelay();
3311   }
3312
3313   MultiTemplateParamsArg TParams;
3314   if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
3315       TUK != Sema::TUK_Reference) {
3316     if (!getLangOpts().CPlusPlus0x || !SS.isSet()) {
3317       // Skip the rest of this declarator, up until the comma or semicolon.
3318       Diag(Tok, diag::err_enum_template);
3319       SkipUntil(tok::comma, true);
3320       return;
3321     }
3322
3323     if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
3324       // Enumerations can't be explicitly instantiated.
3325       DS.SetTypeSpecError();
3326       Diag(StartLoc, diag::err_explicit_instantiation_enum);
3327       return;
3328     }
3329
3330     assert(TemplateInfo.TemplateParams && "no template parameters");
3331     TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
3332                                      TemplateInfo.TemplateParams->size());
3333   }
3334
3335   if (TUK == Sema::TUK_Reference)
3336     ProhibitAttributes(attrs);
3337
3338   if (!Name && TUK != Sema::TUK_Definition) {
3339     Diag(Tok, diag::err_enumerator_unnamed_no_def);
3340
3341     // Skip the rest of this declarator, up until the comma or semicolon.
3342     SkipUntil(tok::comma, true);
3343     return;
3344   }
3345
3346   bool Owned = false;
3347   bool IsDependent = false;
3348   const char *PrevSpec = 0;
3349   unsigned DiagID;
3350   Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
3351                                    StartLoc, SS, Name, NameLoc, attrs.getList(),
3352                                    AS, DS.getModulePrivateSpecLoc(), TParams,
3353                                    Owned, IsDependent, ScopedEnumKWLoc,
3354                                    IsScopedUsingClassTag, BaseType);
3355
3356   if (IsDependent) {
3357     // This enum has a dependent nested-name-specifier. Handle it as a
3358     // dependent tag.
3359     if (!Name) {
3360       DS.SetTypeSpecError();
3361       Diag(Tok, diag::err_expected_type_name_after_typename);
3362       return;
3363     }
3364
3365     TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum,
3366                                                 TUK, SS, Name, StartLoc,
3367                                                 NameLoc);
3368     if (Type.isInvalid()) {
3369       DS.SetTypeSpecError();
3370       return;
3371     }
3372
3373     if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
3374                            NameLoc.isValid() ? NameLoc : StartLoc,
3375                            PrevSpec, DiagID, Type.get()))
3376       Diag(StartLoc, DiagID) << PrevSpec;
3377
3378     return;
3379   }
3380
3381   if (!TagDecl) {
3382     // The action failed to produce an enumeration tag. If this is a
3383     // definition, consume the entire definition.
3384     if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
3385       ConsumeBrace();
3386       SkipUntil(tok::r_brace);
3387     }
3388
3389     DS.SetTypeSpecError();
3390     return;
3391   }
3392
3393   if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference)
3394     ParseEnumBody(StartLoc, TagDecl);
3395
3396   if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
3397                          NameLoc.isValid() ? NameLoc : StartLoc,
3398                          PrevSpec, DiagID, TagDecl, Owned))
3399     Diag(StartLoc, DiagID) << PrevSpec;
3400 }
3401
3402 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
3403 ///       enumerator-list:
3404 ///         enumerator
3405 ///         enumerator-list ',' enumerator
3406 ///       enumerator:
3407 ///         enumeration-constant
3408 ///         enumeration-constant '=' constant-expression
3409 ///       enumeration-constant:
3410 ///         identifier
3411 ///
3412 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
3413   // Enter the scope of the enum body and start the definition.
3414   ParseScope EnumScope(this, Scope::DeclScope);
3415   Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
3416
3417   BalancedDelimiterTracker T(*this, tok::l_brace);
3418   T.consumeOpen();
3419
3420   // C does not allow an empty enumerator-list, C++ does [dcl.enum].
3421   if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
3422     Diag(Tok, diag::error_empty_enum);
3423
3424   SmallVector<Decl *, 32> EnumConstantDecls;
3425
3426   Decl *LastEnumConstDecl = 0;
3427
3428   // Parse the enumerator-list.
3429   while (Tok.is(tok::identifier)) {
3430     IdentifierInfo *Ident = Tok.getIdentifierInfo();
3431     SourceLocation IdentLoc = ConsumeToken();
3432
3433     // If attributes exist after the enumerator, parse them.
3434     ParsedAttributesWithRange attrs(AttrFactory);
3435     MaybeParseGNUAttributes(attrs);
3436     MaybeParseCXX0XAttributes(attrs);
3437     ProhibitAttributes(attrs);
3438
3439     SourceLocation EqualLoc;
3440     ExprResult AssignedVal;
3441     ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
3442
3443     if (Tok.is(tok::equal)) {
3444       EqualLoc = ConsumeToken();
3445       AssignedVal = ParseConstantExpression();
3446       if (AssignedVal.isInvalid())
3447         SkipUntil(tok::comma, tok::r_brace, true, true);
3448     }
3449
3450     // Install the enumerator constant into EnumDecl.
3451     Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
3452                                                     LastEnumConstDecl,
3453                                                     IdentLoc, Ident,
3454                                                     attrs.getList(), EqualLoc,
3455                                                     AssignedVal.release());
3456     PD.complete(EnumConstDecl);
3457
3458     EnumConstantDecls.push_back(EnumConstDecl);
3459     LastEnumConstDecl = EnumConstDecl;
3460
3461     if (Tok.is(tok::identifier)) {
3462       // We're missing a comma between enumerators.
3463       SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3464       Diag(Loc, diag::err_enumerator_list_missing_comma)
3465         << FixItHint::CreateInsertion(Loc, ", ");
3466       continue;
3467     }
3468
3469     if (Tok.isNot(tok::comma))
3470       break;
3471     SourceLocation CommaLoc = ConsumeToken();
3472
3473     if (Tok.isNot(tok::identifier)) {
3474       if (!getLangOpts().C99 && !getLangOpts().CPlusPlus0x)
3475         Diag(CommaLoc, getLangOpts().CPlusPlus ?
3476                diag::ext_enumerator_list_comma_cxx :
3477                diag::ext_enumerator_list_comma_c)
3478           << FixItHint::CreateRemoval(CommaLoc);
3479       else if (getLangOpts().CPlusPlus0x)
3480         Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
3481           << FixItHint::CreateRemoval(CommaLoc);
3482     }
3483   }
3484
3485   // Eat the }.
3486   T.consumeClose();
3487
3488   // If attributes exist after the identifier list, parse them.
3489   ParsedAttributes attrs(AttrFactory);
3490   MaybeParseGNUAttributes(attrs);
3491
3492   Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(),
3493                         EnumDecl, EnumConstantDecls.data(),
3494                         EnumConstantDecls.size(), getCurScope(),
3495                         attrs.getList());
3496
3497   EnumScope.Exit();
3498   Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl,
3499                                    T.getCloseLocation());
3500
3501   // The next token must be valid after an enum definition. If not, a ';'
3502   // was probably forgotten.
3503   bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
3504   if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
3505     ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, "enum");
3506     // Push this token back into the preprocessor and change our current token
3507     // to ';' so that the rest of the code recovers as though there were an
3508     // ';' after the definition.
3509     PP.EnterToken(Tok);
3510     Tok.setKind(tok::semi);
3511   }
3512 }
3513
3514 /// isTypeSpecifierQualifier - Return true if the current token could be the
3515 /// start of a type-qualifier-list.
3516 bool Parser::isTypeQualifier() const {
3517   switch (Tok.getKind()) {
3518   default: return false;
3519
3520     // type-qualifier only in OpenCL
3521   case tok::kw_private:
3522     return getLangOpts().OpenCL;
3523
3524     // type-qualifier
3525   case tok::kw_const:
3526   case tok::kw_volatile:
3527   case tok::kw_restrict:
3528   case tok::kw___private:
3529   case tok::kw___local:
3530   case tok::kw___global:
3531   case tok::kw___constant:
3532   case tok::kw___read_only:
3533   case tok::kw___read_write:
3534   case tok::kw___write_only:
3535     return true;
3536   }
3537 }
3538
3539 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
3540 /// is definitely a type-specifier.  Return false if it isn't part of a type
3541 /// specifier or if we're not sure.
3542 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
3543   switch (Tok.getKind()) {
3544   default: return false;
3545     // type-specifiers
3546   case tok::kw_short:
3547   case tok::kw_long:
3548   case tok::kw___int64:
3549   case tok::kw___int128:
3550   case tok::kw_signed:
3551   case tok::kw_unsigned:
3552   case tok::kw__Complex:
3553   case tok::kw__Imaginary:
3554   case tok::kw_void:
3555   case tok::kw_char:
3556   case tok::kw_wchar_t:
3557   case tok::kw_char16_t:
3558   case tok::kw_char32_t:
3559   case tok::kw_int:
3560   case tok::kw_half:
3561   case tok::kw_float:
3562   case tok::kw_double:
3563   case tok::kw_bool:
3564   case tok::kw__Bool:
3565   case tok::kw__Decimal32:
3566   case tok::kw__Decimal64:
3567   case tok::kw__Decimal128:
3568   case tok::kw___vector:
3569
3570     // struct-or-union-specifier (C99) or class-specifier (C++)
3571   case tok::kw_class:
3572   case tok::kw_struct:
3573   case tok::kw___interface:
3574   case tok::kw_union:
3575     // enum-specifier
3576   case tok::kw_enum:
3577
3578     // typedef-name
3579   case tok::annot_typename:
3580     return true;
3581   }
3582 }
3583
3584 /// isTypeSpecifierQualifier - Return true if the current token could be the
3585 /// start of a specifier-qualifier-list.
3586 bool Parser::isTypeSpecifierQualifier() {
3587   switch (Tok.getKind()) {
3588   default: return false;
3589
3590   case tok::identifier:   // foo::bar
3591     if (TryAltiVecVectorToken())
3592       return true;
3593     // Fall through.
3594   case tok::kw_typename:  // typename T::type
3595     // Annotate typenames and C++ scope specifiers.  If we get one, just
3596     // recurse to handle whatever we get.
3597     if (TryAnnotateTypeOrScopeToken())
3598       return true;
3599     if (Tok.is(tok::identifier))
3600       return false;
3601     return isTypeSpecifierQualifier();
3602
3603   case tok::coloncolon:   // ::foo::bar
3604     if (NextToken().is(tok::kw_new) ||    // ::new
3605         NextToken().is(tok::kw_delete))   // ::delete
3606       return false;
3607
3608     if (TryAnnotateTypeOrScopeToken())
3609       return true;
3610     return isTypeSpecifierQualifier();
3611
3612     // GNU attributes support.
3613   case tok::kw___attribute:
3614     // GNU typeof support.
3615   case tok::kw_typeof:
3616
3617     // type-specifiers
3618   case tok::kw_short:
3619   case tok::kw_long:
3620   case tok::kw___int64:
3621   case tok::kw___int128:
3622   case tok::kw_signed:
3623   case tok::kw_unsigned:
3624   case tok::kw__Complex:
3625   case tok::kw__Imaginary:
3626   case tok::kw_void:
3627   case tok::kw_char:
3628   case tok::kw_wchar_t:
3629   case tok::kw_char16_t:
3630   case tok::kw_char32_t:
3631   case tok::kw_int:
3632   case tok::kw_half:
3633   case tok::kw_float:
3634   case tok::kw_double:
3635   case tok::kw_bool:
3636   case tok::kw__Bool:
3637   case tok::kw__Decimal32:
3638   case tok::kw__Decimal64:
3639   case tok::kw__Decimal128:
3640   case tok::kw___vector:
3641
3642     // struct-or-union-specifier (C99) or class-specifier (C++)
3643   case tok::kw_class:
3644   case tok::kw_struct:
3645   case tok::kw___interface:
3646   case tok::kw_union:
3647     // enum-specifier
3648   case tok::kw_enum:
3649
3650     // type-qualifier
3651   case tok::kw_const:
3652   case tok::kw_volatile:
3653   case tok::kw_restrict:
3654
3655     // typedef-name
3656   case tok::annot_typename:
3657     return true;
3658
3659     // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
3660   case tok::less:
3661     return getLangOpts().ObjC1;
3662
3663   case tok::kw___cdecl:
3664   case tok::kw___stdcall:
3665   case tok::kw___fastcall:
3666   case tok::kw___thiscall:
3667   case tok::kw___w64:
3668   case tok::kw___ptr64:
3669   case tok::kw___ptr32:
3670   case tok::kw___pascal:
3671   case tok::kw___unaligned:
3672
3673   case tok::kw___private:
3674   case tok::kw___local:
3675   case tok::kw___global:
3676   case tok::kw___constant:
3677   case tok::kw___read_only:
3678   case tok::kw___read_write:
3679   case tok::kw___write_only:
3680
3681     return true;
3682
3683   case tok::kw_private:
3684     return getLangOpts().OpenCL;
3685
3686   // C11 _Atomic()
3687   case tok::kw__Atomic:
3688     return true;
3689   }
3690 }
3691
3692 /// isDeclarationSpecifier() - Return true if the current token is part of a
3693 /// declaration specifier.
3694 ///
3695 /// \param DisambiguatingWithExpression True to indicate that the purpose of
3696 /// this check is to disambiguate between an expression and a declaration.
3697 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
3698   switch (Tok.getKind()) {
3699   default: return false;
3700
3701   case tok::kw_private:
3702     return getLangOpts().OpenCL;
3703
3704   case tok::identifier:   // foo::bar
3705     // Unfortunate hack to support "Class.factoryMethod" notation.
3706     if (getLangOpts().ObjC1 && NextToken().is(tok::period))
3707       return false;
3708     if (TryAltiVecVectorToken())
3709       return true;
3710     // Fall through.
3711   case tok::kw_decltype: // decltype(T())::type
3712   case tok::kw_typename: // typename T::type
3713     // Annotate typenames and C++ scope specifiers.  If we get one, just
3714     // recurse to handle whatever we get.
3715     if (TryAnnotateTypeOrScopeToken())
3716       return true;
3717     if (Tok.is(tok::identifier))
3718       return false;
3719
3720     // If we're in Objective-C and we have an Objective-C class type followed
3721     // by an identifier and then either ':' or ']', in a place where an
3722     // expression is permitted, then this is probably a class message send
3723     // missing the initial '['. In this case, we won't consider this to be
3724     // the start of a declaration.
3725     if (DisambiguatingWithExpression &&
3726         isStartOfObjCClassMessageMissingOpenBracket())
3727       return false;
3728
3729     return isDeclarationSpecifier();
3730
3731   case tok::coloncolon:   // ::foo::bar
3732     if (NextToken().is(tok::kw_new) ||    // ::new
3733         NextToken().is(tok::kw_delete))   // ::delete
3734       return false;
3735
3736     // Annotate typenames and C++ scope specifiers.  If we get one, just
3737     // recurse to handle whatever we get.
3738     if (TryAnnotateTypeOrScopeToken())
3739       return true;
3740     return isDeclarationSpecifier();
3741
3742     // storage-class-specifier
3743   case tok::kw_typedef:
3744   case tok::kw_extern:
3745   case tok::kw___private_extern__:
3746   case tok::kw_static:
3747   case tok::kw_auto:
3748   case tok::kw_register:
3749   case tok::kw___thread:
3750
3751     // Modules
3752   case tok::kw___module_private__:
3753
3754     // type-specifiers
3755   case tok::kw_short:
3756   case tok::kw_long:
3757   case tok::kw___int64:
3758   case tok::kw___int128:
3759   case tok::kw_signed:
3760   case tok::kw_unsigned:
3761   case tok::kw__Complex:
3762   case tok::kw__Imaginary:
3763   case tok::kw_void:
3764   case tok::kw_char:
3765   case tok::kw_wchar_t:
3766   case tok::kw_char16_t:
3767   case tok::kw_char32_t:
3768
3769   case tok::kw_int:
3770   case tok::kw_half:
3771   case tok::kw_float:
3772   case tok::kw_double:
3773   case tok::kw_bool:
3774   case tok::kw__Bool:
3775   case tok::kw__Decimal32:
3776   case tok::kw__Decimal64:
3777   case tok::kw__Decimal128:
3778   case tok::kw___vector:
3779
3780     // struct-or-union-specifier (C99) or class-specifier (C++)
3781   case tok::kw_class:
3782   case tok::kw_struct:
3783   case tok::kw_union:
3784   case tok::kw___interface:
3785     // enum-specifier
3786   case tok::kw_enum:
3787
3788     // type-qualifier
3789   case tok::kw_const:
3790   case tok::kw_volatile:
3791   case tok::kw_restrict:
3792
3793     // function-specifier
3794   case tok::kw_inline:
3795   case tok::kw_virtual:
3796   case tok::kw_explicit:
3797
3798     // friend keyword.
3799   case tok::kw_friend:
3800
3801     // static_assert-declaration
3802   case tok::kw__Static_assert:
3803
3804     // GNU typeof support.
3805   case tok::kw_typeof:
3806
3807     // GNU attributes.
3808   case tok::kw___attribute:
3809
3810     // C++11 decltype and constexpr.
3811   case tok::annot_decltype:
3812   case tok::kw_constexpr:
3813
3814     // C11 _Atomic()
3815   case tok::kw__Atomic:
3816     return true;
3817
3818     // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
3819   case tok::less:
3820     return getLangOpts().ObjC1;
3821
3822     // typedef-name
3823   case tok::annot_typename:
3824     return !DisambiguatingWithExpression ||
3825            !isStartOfObjCClassMessageMissingOpenBracket();
3826
3827   case tok::kw___declspec:
3828   case tok::kw___cdecl:
3829   case tok::kw___stdcall:
3830   case tok::kw___fastcall:
3831   case tok::kw___thiscall:
3832   case tok::kw___w64:
3833   case tok::kw___ptr64:
3834   case tok::kw___ptr32:
3835   case tok::kw___forceinline:
3836   case tok::kw___pascal:
3837   case tok::kw___unaligned:
3838
3839   case tok::kw___private:
3840   case tok::kw___local:
3841   case tok::kw___global:
3842   case tok::kw___constant:
3843   case tok::kw___read_only:
3844   case tok::kw___read_write:
3845   case tok::kw___write_only:
3846
3847     return true;
3848   }
3849 }
3850
3851 bool Parser::isConstructorDeclarator() {
3852   TentativeParsingAction TPA(*this);
3853
3854   // Parse the C++ scope specifier.
3855   CXXScopeSpec SS;
3856   if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
3857                                      /*EnteringContext=*/true)) {
3858     TPA.Revert();
3859     return false;
3860   }
3861
3862   // Parse the constructor name.
3863   if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
3864     // We already know that we have a constructor name; just consume
3865     // the token.
3866     ConsumeToken();
3867   } else {
3868     TPA.Revert();
3869     return false;
3870   }
3871
3872   // Current class name must be followed by a left parenthesis.
3873   if (Tok.isNot(tok::l_paren)) {
3874     TPA.Revert();
3875     return false;
3876   }
3877   ConsumeParen();
3878
3879   // A right parenthesis, or ellipsis followed by a right parenthesis signals
3880   // that we have a constructor.
3881   if (Tok.is(tok::r_paren) ||
3882       (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
3883     TPA.Revert();
3884     return true;
3885   }
3886
3887   // If we need to, enter the specified scope.
3888   DeclaratorScopeObj DeclScopeObj(*this, SS);
3889   if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
3890     DeclScopeObj.EnterDeclaratorScope();
3891
3892   // Optionally skip Microsoft attributes.
3893   ParsedAttributes Attrs(AttrFactory);
3894   MaybeParseMicrosoftAttributes(Attrs);
3895
3896   // Check whether the next token(s) are part of a declaration
3897   // specifier, in which case we have the start of a parameter and,
3898   // therefore, we know that this is a constructor.
3899   bool IsConstructor = false;
3900   if (isDeclarationSpecifier())
3901     IsConstructor = true;
3902   else if (Tok.is(tok::identifier) ||
3903            (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
3904     // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
3905     // This might be a parenthesized member name, but is more likely to
3906     // be a constructor declaration with an invalid argument type. Keep
3907     // looking.
3908     if (Tok.is(tok::annot_cxxscope))
3909       ConsumeToken();
3910     ConsumeToken();
3911
3912     // If this is not a constructor, we must be parsing a declarator,
3913     // which must have one of the following syntactic forms (see the
3914     // grammar extract at the start of ParseDirectDeclarator):
3915     switch (Tok.getKind()) {
3916     case tok::l_paren:
3917       // C(X   (   int));
3918     case tok::l_square:
3919       // C(X   [   5]);
3920       // C(X   [   [attribute]]);
3921     case tok::coloncolon:
3922       // C(X   ::   Y);
3923       // C(X   ::   *p);
3924     case tok::r_paren:
3925       // C(X   )
3926       // Assume this isn't a constructor, rather than assuming it's a
3927       // constructor with an unnamed parameter of an ill-formed type.
3928       break;
3929
3930     default:
3931       IsConstructor = true;
3932       break;
3933     }
3934   }
3935
3936   TPA.Revert();
3937   return IsConstructor;
3938 }
3939
3940 /// ParseTypeQualifierListOpt
3941 ///          type-qualifier-list: [C99 6.7.5]
3942 ///            type-qualifier
3943 /// [vendor]   attributes
3944 ///              [ only if VendorAttributesAllowed=true ]
3945 ///            type-qualifier-list type-qualifier
3946 /// [vendor]   type-qualifier-list attributes
3947 ///              [ only if VendorAttributesAllowed=true ]
3948 /// [C++0x]    attribute-specifier[opt] is allowed before cv-qualifier-seq
3949 ///              [ only if CXX0XAttributesAllowed=true ]
3950 /// Note: vendor can be GNU, MS, etc.
3951 ///
3952 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
3953                                        bool VendorAttributesAllowed,
3954                                        bool CXX11AttributesAllowed) {
3955   if (getLangOpts().CPlusPlus0x && CXX11AttributesAllowed &&
3956       isCXX11AttributeSpecifier()) {
3957     ParsedAttributesWithRange attrs(AttrFactory);
3958     ParseCXX11Attributes(attrs);
3959     DS.takeAttributesFrom(attrs);
3960   }
3961
3962   SourceLocation EndLoc;
3963
3964   while (1) {
3965     bool isInvalid = false;
3966     const char *PrevSpec = 0;
3967     unsigned DiagID = 0;
3968     SourceLocation Loc = Tok.getLocation();
3969
3970     switch (Tok.getKind()) {
3971     case tok::code_completion:
3972       Actions.CodeCompleteTypeQualifiers(DS);
3973       return cutOffParsing();
3974
3975     case tok::kw_const:
3976       isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec, DiagID,
3977                                  getLangOpts());
3978       break;
3979     case tok::kw_volatile:
3980       isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3981                                  getLangOpts());
3982       break;
3983     case tok::kw_restrict:
3984       isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3985                                  getLangOpts());
3986       break;
3987
3988     // OpenCL qualifiers:
3989     case tok::kw_private:
3990       if (!getLangOpts().OpenCL)
3991         goto DoneWithTypeQuals;
3992     case tok::kw___private:
3993     case tok::kw___global:
3994     case tok::kw___local:
3995     case tok::kw___constant:
3996     case tok::kw___read_only:
3997     case tok::kw___write_only:
3998     case tok::kw___read_write:
3999       ParseOpenCLQualifiers(DS);
4000       break;
4001
4002     case tok::kw___w64:
4003     case tok::kw___ptr64:
4004     case tok::kw___ptr32:
4005     case tok::kw___cdecl:
4006     case tok::kw___stdcall:
4007     case tok::kw___fastcall:
4008     case tok::kw___thiscall:
4009     case tok::kw___unaligned:
4010       if (VendorAttributesAllowed) {
4011         ParseMicrosoftTypeAttributes(DS.getAttributes());
4012         continue;
4013       }
4014       goto DoneWithTypeQuals;
4015     case tok::kw___pascal:
4016       if (VendorAttributesAllowed) {
4017         ParseBorlandTypeAttributes(DS.getAttributes());
4018         continue;
4019       }
4020       goto DoneWithTypeQuals;
4021     case tok::kw___attribute:
4022       if (VendorAttributesAllowed) {
4023         ParseGNUAttributes(DS.getAttributes());
4024         continue; // do *not* consume the next token!
4025       }
4026       // otherwise, FALL THROUGH!
4027     default:
4028       DoneWithTypeQuals:
4029       // If this is not a type-qualifier token, we're done reading type
4030       // qualifiers.  First verify that DeclSpec's are consistent.
4031       DS.Finish(Diags, PP);
4032       if (EndLoc.isValid())
4033         DS.SetRangeEnd(EndLoc);
4034       return;
4035     }
4036
4037     // If the specifier combination wasn't legal, issue a diagnostic.
4038     if (isInvalid) {
4039       assert(PrevSpec && "Method did not return previous specifier!");
4040       Diag(Tok, DiagID) << PrevSpec;
4041     }
4042     EndLoc = ConsumeToken();
4043   }
4044 }
4045
4046
4047 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
4048 ///
4049 void Parser::ParseDeclarator(Declarator &D) {
4050   /// This implements the 'declarator' production in the C grammar, then checks
4051   /// for well-formedness and issues diagnostics.
4052   ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
4053 }
4054
4055 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang) {
4056   if (Kind == tok::star || Kind == tok::caret)
4057     return true;
4058
4059   // We parse rvalue refs in C++03, because otherwise the errors are scary.
4060   if (!Lang.CPlusPlus)
4061     return false;
4062
4063   return Kind == tok::amp || Kind == tok::ampamp;
4064 }
4065
4066 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
4067 /// is parsed by the function passed to it. Pass null, and the direct-declarator
4068 /// isn't parsed at all, making this function effectively parse the C++
4069 /// ptr-operator production.
4070 ///
4071 /// If the grammar of this construct is extended, matching changes must also be
4072 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
4073 /// isConstructorDeclarator.
4074 ///
4075 ///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
4076 /// [C]     pointer[opt] direct-declarator
4077 /// [C++]   direct-declarator
4078 /// [C++]   ptr-operator declarator
4079 ///
4080 ///       pointer: [C99 6.7.5]
4081 ///         '*' type-qualifier-list[opt]
4082 ///         '*' type-qualifier-list[opt] pointer
4083 ///
4084 ///       ptr-operator:
4085 ///         '*' cv-qualifier-seq[opt]
4086 ///         '&'
4087 /// [C++0x] '&&'
4088 /// [GNU]   '&' restrict[opt] attributes[opt]
4089 /// [GNU?]  '&&' restrict[opt] attributes[opt]
4090 ///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
4091 void Parser::ParseDeclaratorInternal(Declarator &D,
4092                                      DirectDeclParseFunction DirectDeclParser) {
4093   if (Diags.hasAllExtensionsSilenced())
4094     D.setExtension();
4095
4096   // C++ member pointers start with a '::' or a nested-name.
4097   // Member pointers get special handling, since there's no place for the
4098   // scope spec in the generic path below.
4099   if (getLangOpts().CPlusPlus &&
4100       (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
4101        Tok.is(tok::annot_cxxscope))) {
4102     bool EnteringContext = D.getContext() == Declarator::FileContext ||
4103                            D.getContext() == Declarator::MemberContext;
4104     CXXScopeSpec SS;
4105     ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext);
4106
4107     if (SS.isNotEmpty()) {
4108       if (Tok.isNot(tok::star)) {
4109         // The scope spec really belongs to the direct-declarator.
4110         D.getCXXScopeSpec() = SS;
4111         if (DirectDeclParser)
4112           (this->*DirectDeclParser)(D);
4113         return;
4114       }
4115
4116       SourceLocation Loc = ConsumeToken();
4117       D.SetRangeEnd(Loc);
4118       DeclSpec DS(AttrFactory);
4119       ParseTypeQualifierListOpt(DS);
4120       D.ExtendWithDeclSpec(DS);
4121
4122       // Recurse to parse whatever is left.
4123       ParseDeclaratorInternal(D, DirectDeclParser);
4124
4125       // Sema will have to catch (syntactically invalid) pointers into global
4126       // scope. It has to catch pointers into namespace scope anyway.
4127       D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
4128                                                       Loc),
4129                     DS.getAttributes(),
4130                     /* Don't replace range end. */SourceLocation());
4131       return;
4132     }
4133   }
4134
4135   tok::TokenKind Kind = Tok.getKind();
4136   // Not a pointer, C++ reference, or block.
4137   if (!isPtrOperatorToken(Kind, getLangOpts())) {
4138     if (DirectDeclParser)
4139       (this->*DirectDeclParser)(D);
4140     return;
4141   }
4142
4143   // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
4144   // '&&' -> rvalue reference
4145   SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
4146   D.SetRangeEnd(Loc);
4147
4148   if (Kind == tok::star || Kind == tok::caret) {
4149     // Is a pointer.
4150     DeclSpec DS(AttrFactory);
4151
4152     // FIXME: GNU attributes are not allowed here in a new-type-id.
4153     ParseTypeQualifierListOpt(DS);
4154     D.ExtendWithDeclSpec(DS);
4155
4156     // Recursively parse the declarator.
4157     ParseDeclaratorInternal(D, DirectDeclParser);
4158     if (Kind == tok::star)
4159       // Remember that we parsed a pointer type, and remember the type-quals.
4160       D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
4161                                                 DS.getConstSpecLoc(),
4162                                                 DS.getVolatileSpecLoc(),
4163                                                 DS.getRestrictSpecLoc()),
4164                     DS.getAttributes(),
4165                     SourceLocation());
4166     else
4167       // Remember that we parsed a Block type, and remember the type-quals.
4168       D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
4169                                                      Loc),
4170                     DS.getAttributes(),
4171                     SourceLocation());
4172   } else {
4173     // Is a reference
4174     DeclSpec DS(AttrFactory);
4175
4176     // Complain about rvalue references in C++03, but then go on and build
4177     // the declarator.
4178     if (Kind == tok::ampamp)
4179       Diag(Loc, getLangOpts().CPlusPlus0x ?
4180            diag::warn_cxx98_compat_rvalue_reference :
4181            diag::ext_rvalue_reference);
4182
4183     // GNU-style and C++11 attributes are allowed here, as is restrict.
4184     ParseTypeQualifierListOpt(DS);
4185     D.ExtendWithDeclSpec(DS);
4186
4187     // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
4188     // cv-qualifiers are introduced through the use of a typedef or of a
4189     // template type argument, in which case the cv-qualifiers are ignored.
4190     if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
4191       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4192         Diag(DS.getConstSpecLoc(),
4193              diag::err_invalid_reference_qualifier_application) << "const";
4194       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4195         Diag(DS.getVolatileSpecLoc(),
4196              diag::err_invalid_reference_qualifier_application) << "volatile";
4197     }
4198
4199     // Recursively parse the declarator.
4200     ParseDeclaratorInternal(D, DirectDeclParser);
4201
4202     if (D.getNumTypeObjects() > 0) {
4203       // C++ [dcl.ref]p4: There shall be no references to references.
4204       DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
4205       if (InnerChunk.Kind == DeclaratorChunk::Reference) {
4206         if (const IdentifierInfo *II = D.getIdentifier())
4207           Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
4208            << II;
4209         else
4210           Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
4211             << "type name";
4212
4213         // Once we've complained about the reference-to-reference, we
4214         // can go ahead and build the (technically ill-formed)
4215         // declarator: reference collapsing will take care of it.
4216       }
4217     }
4218
4219     // Remember that we parsed a reference type. It doesn't have type-quals.
4220     D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
4221                                                 Kind == tok::amp),
4222                   DS.getAttributes(),
4223                   SourceLocation());
4224   }
4225 }
4226
4227 static void diagnoseMisplacedEllipsis(Parser &P, Declarator &D,
4228                                       SourceLocation EllipsisLoc) {
4229   if (EllipsisLoc.isValid()) {
4230     FixItHint Insertion;
4231     if (!D.getEllipsisLoc().isValid()) {
4232       Insertion = FixItHint::CreateInsertion(D.getIdentifierLoc(), "...");
4233       D.setEllipsisLoc(EllipsisLoc);
4234     }
4235     P.Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
4236       << FixItHint::CreateRemoval(EllipsisLoc) << Insertion << !D.hasName();
4237   }
4238 }
4239
4240 /// ParseDirectDeclarator
4241 ///       direct-declarator: [C99 6.7.5]
4242 /// [C99]   identifier
4243 ///         '(' declarator ')'
4244 /// [GNU]   '(' attributes declarator ')'
4245 /// [C90]   direct-declarator '[' constant-expression[opt] ']'
4246 /// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
4247 /// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
4248 /// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
4249 /// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
4250 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
4251 ///                    attribute-specifier-seq[opt]
4252 ///         direct-declarator '(' parameter-type-list ')'
4253 ///         direct-declarator '(' identifier-list[opt] ')'
4254 /// [GNU]   direct-declarator '(' parameter-forward-declarations
4255 ///                    parameter-type-list[opt] ')'
4256 /// [C++]   direct-declarator '(' parameter-declaration-clause ')'
4257 ///                    cv-qualifier-seq[opt] exception-specification[opt]
4258 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
4259 ///                    attribute-specifier-seq[opt] cv-qualifier-seq[opt]
4260 ///                    ref-qualifier[opt] exception-specification[opt]
4261 /// [C++]   declarator-id
4262 /// [C++11] declarator-id attribute-specifier-seq[opt]
4263 ///
4264 ///       declarator-id: [C++ 8]
4265 ///         '...'[opt] id-expression
4266 ///         '::'[opt] nested-name-specifier[opt] type-name
4267 ///
4268 ///       id-expression: [C++ 5.1]
4269 ///         unqualified-id
4270 ///         qualified-id
4271 ///
4272 ///       unqualified-id: [C++ 5.1]
4273 ///         identifier
4274 ///         operator-function-id
4275 ///         conversion-function-id
4276 ///          '~' class-name
4277 ///         template-id
4278 ///
4279 /// Note, any additional constructs added here may need corresponding changes
4280 /// in isConstructorDeclarator.
4281 void Parser::ParseDirectDeclarator(Declarator &D) {
4282   DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
4283
4284   if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
4285     // ParseDeclaratorInternal might already have parsed the scope.
4286     if (D.getCXXScopeSpec().isEmpty()) {
4287       bool EnteringContext = D.getContext() == Declarator::FileContext ||
4288                              D.getContext() == Declarator::MemberContext;
4289       ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(),
4290                                      EnteringContext);
4291     }
4292
4293     if (D.getCXXScopeSpec().isValid()) {
4294       if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
4295         // Change the declaration context for name lookup, until this function
4296         // is exited (and the declarator has been parsed).
4297         DeclScopeObj.EnterDeclaratorScope();
4298     }
4299
4300     // C++0x [dcl.fct]p14:
4301     //   There is a syntactic ambiguity when an ellipsis occurs at the end
4302     //   of a parameter-declaration-clause without a preceding comma. In
4303     //   this case, the ellipsis is parsed as part of the
4304     //   abstract-declarator if the type of the parameter names a template
4305     //   parameter pack that has not been expanded; otherwise, it is parsed
4306     //   as part of the parameter-declaration-clause.
4307     if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
4308         !((D.getContext() == Declarator::PrototypeContext ||
4309            D.getContext() == Declarator::BlockLiteralContext) &&
4310           NextToken().is(tok::r_paren) &&
4311           !Actions.containsUnexpandedParameterPacks(D))) {
4312       SourceLocation EllipsisLoc = ConsumeToken();
4313       if (isPtrOperatorToken(Tok.getKind(), getLangOpts())) {
4314         // The ellipsis was put in the wrong place. Recover, and explain to
4315         // the user what they should have done.
4316         ParseDeclarator(D);
4317         diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
4318         return;
4319       } else
4320         D.setEllipsisLoc(EllipsisLoc);
4321
4322       // The ellipsis can't be followed by a parenthesized declarator. We
4323       // check for that in ParseParenDeclarator, after we have disambiguated
4324       // the l_paren token.
4325     }
4326
4327     if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
4328         Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
4329       // We found something that indicates the start of an unqualified-id.
4330       // Parse that unqualified-id.
4331       bool AllowConstructorName;
4332       if (D.getDeclSpec().hasTypeSpecifier())
4333         AllowConstructorName = false;
4334       else if (D.getCXXScopeSpec().isSet())
4335         AllowConstructorName =
4336           (D.getContext() == Declarator::FileContext ||
4337            (D.getContext() == Declarator::MemberContext &&
4338             D.getDeclSpec().isFriendSpecified()));
4339       else
4340         AllowConstructorName = (D.getContext() == Declarator::MemberContext);
4341
4342       SourceLocation TemplateKWLoc;
4343       if (ParseUnqualifiedId(D.getCXXScopeSpec(),
4344                              /*EnteringContext=*/true,
4345                              /*AllowDestructorName=*/true,
4346                              AllowConstructorName,
4347                              ParsedType(),
4348                              TemplateKWLoc,
4349                              D.getName()) ||
4350           // Once we're past the identifier, if the scope was bad, mark the
4351           // whole declarator bad.
4352           D.getCXXScopeSpec().isInvalid()) {
4353         D.SetIdentifier(0, Tok.getLocation());
4354         D.setInvalidType(true);
4355       } else {
4356         // Parsed the unqualified-id; update range information and move along.
4357         if (D.getSourceRange().getBegin().isInvalid())
4358           D.SetRangeBegin(D.getName().getSourceRange().getBegin());
4359         D.SetRangeEnd(D.getName().getSourceRange().getEnd());
4360       }
4361       goto PastIdentifier;
4362     }
4363   } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
4364     assert(!getLangOpts().CPlusPlus &&
4365            "There's a C++-specific check for tok::identifier above");
4366     assert(Tok.getIdentifierInfo() && "Not an identifier?");
4367     D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
4368     ConsumeToken();
4369     goto PastIdentifier;
4370   }
4371
4372   if (Tok.is(tok::l_paren)) {
4373     // direct-declarator: '(' declarator ')'
4374     // direct-declarator: '(' attributes declarator ')'
4375     // Example: 'char (*X)'   or 'int (*XX)(void)'
4376     ParseParenDeclarator(D);
4377
4378     // If the declarator was parenthesized, we entered the declarator
4379     // scope when parsing the parenthesized declarator, then exited
4380     // the scope already. Re-enter the scope, if we need to.
4381     if (D.getCXXScopeSpec().isSet()) {
4382       // If there was an error parsing parenthesized declarator, declarator
4383       // scope may have been entered before. Don't do it again.
4384       if (!D.isInvalidType() &&
4385           Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
4386         // Change the declaration context for name lookup, until this function
4387         // is exited (and the declarator has been parsed).
4388         DeclScopeObj.EnterDeclaratorScope();
4389     }
4390   } else if (D.mayOmitIdentifier()) {
4391     // This could be something simple like "int" (in which case the declarator
4392     // portion is empty), if an abstract-declarator is allowed.
4393     D.SetIdentifier(0, Tok.getLocation());
4394   } else {
4395     if (Tok.getKind() == tok::annot_pragma_parser_crash)
4396       LLVM_BUILTIN_TRAP;
4397     if (D.getContext() == Declarator::MemberContext)
4398       Diag(Tok, diag::err_expected_member_name_or_semi)
4399         << D.getDeclSpec().getSourceRange();
4400     else if (getLangOpts().CPlusPlus)
4401       Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus;
4402     else
4403       Diag(Tok, diag::err_expected_ident_lparen);
4404     D.SetIdentifier(0, Tok.getLocation());
4405     D.setInvalidType(true);
4406   }
4407
4408  PastIdentifier:
4409   assert(D.isPastIdentifier() &&
4410          "Haven't past the location of the identifier yet?");
4411
4412   // Don't parse attributes unless we have parsed an unparenthesized name.
4413   if (D.hasName() && !D.getNumTypeObjects())
4414     MaybeParseCXX0XAttributes(D);
4415
4416   while (1) {
4417     if (Tok.is(tok::l_paren)) {
4418       // Enter function-declaration scope, limiting any declarators to the
4419       // function prototype scope, including parameter declarators.
4420       ParseScope PrototypeScope(this,
4421                                 Scope::FunctionPrototypeScope|Scope::DeclScope);
4422       // The paren may be part of a C++ direct initializer, eg. "int x(1);".
4423       // In such a case, check if we actually have a function declarator; if it
4424       // is not, the declarator has been fully parsed.
4425       bool IsAmbiguous = false;
4426       if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
4427         // The name of the declarator, if any, is tentatively declared within
4428         // a possible direct initializer.
4429         TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
4430         bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
4431         TentativelyDeclaredIdentifiers.pop_back();
4432         if (!IsFunctionDecl)
4433           break;
4434       }
4435       ParsedAttributes attrs(AttrFactory);
4436       BalancedDelimiterTracker T(*this, tok::l_paren);
4437       T.consumeOpen();
4438       ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
4439       PrototypeScope.Exit();
4440     } else if (Tok.is(tok::l_square)) {
4441       ParseBracketDeclarator(D);
4442     } else {
4443       break;
4444     }
4445   }
4446 }
4447
4448 /// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
4449 /// only called before the identifier, so these are most likely just grouping
4450 /// parens for precedence.  If we find that these are actually function
4451 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
4452 ///
4453 ///       direct-declarator:
4454 ///         '(' declarator ')'
4455 /// [GNU]   '(' attributes declarator ')'
4456 ///         direct-declarator '(' parameter-type-list ')'
4457 ///         direct-declarator '(' identifier-list[opt] ')'
4458 /// [GNU]   direct-declarator '(' parameter-forward-declarations
4459 ///                    parameter-type-list[opt] ')'
4460 ///
4461 void Parser::ParseParenDeclarator(Declarator &D) {
4462   BalancedDelimiterTracker T(*this, tok::l_paren);
4463   T.consumeOpen();
4464
4465   assert(!D.isPastIdentifier() && "Should be called before passing identifier");
4466
4467   // Eat any attributes before we look at whether this is a grouping or function
4468   // declarator paren.  If this is a grouping paren, the attribute applies to
4469   // the type being built up, for example:
4470   //     int (__attribute__(()) *x)(long y)
4471   // If this ends up not being a grouping paren, the attribute applies to the
4472   // first argument, for example:
4473   //     int (__attribute__(()) int x)
4474   // In either case, we need to eat any attributes to be able to determine what
4475   // sort of paren this is.
4476   //
4477   ParsedAttributes attrs(AttrFactory);
4478   bool RequiresArg = false;
4479   if (Tok.is(tok::kw___attribute)) {
4480     ParseGNUAttributes(attrs);
4481
4482     // We require that the argument list (if this is a non-grouping paren) be
4483     // present even if the attribute list was empty.
4484     RequiresArg = true;
4485   }
4486   // Eat any Microsoft extensions.
4487   if  (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
4488        Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) ||
4489        Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64) ||
4490        Tok.is(tok::kw___ptr32) || Tok.is(tok::kw___unaligned)) {
4491     ParseMicrosoftTypeAttributes(attrs);
4492   }
4493   // Eat any Borland extensions.
4494   if  (Tok.is(tok::kw___pascal))
4495     ParseBorlandTypeAttributes(attrs);
4496
4497   // If we haven't past the identifier yet (or where the identifier would be
4498   // stored, if this is an abstract declarator), then this is probably just
4499   // grouping parens. However, if this could be an abstract-declarator, then
4500   // this could also be the start of function arguments (consider 'void()').
4501   bool isGrouping;
4502
4503   if (!D.mayOmitIdentifier()) {
4504     // If this can't be an abstract-declarator, this *must* be a grouping
4505     // paren, because we haven't seen the identifier yet.
4506     isGrouping = true;
4507   } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
4508              (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
4509               NextToken().is(tok::r_paren)) || // C++ int(...)
4510              isDeclarationSpecifier() ||       // 'int(int)' is a function.
4511              isCXX11AttributeSpecifier()) {    // 'int([[]]int)' is a function.
4512     // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
4513     // considered to be a type, not a K&R identifier-list.
4514     isGrouping = false;
4515   } else {
4516     // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
4517     isGrouping = true;
4518   }
4519
4520   // If this is a grouping paren, handle:
4521   // direct-declarator: '(' declarator ')'
4522   // direct-declarator: '(' attributes declarator ')'
4523   if (isGrouping) {
4524     SourceLocation EllipsisLoc = D.getEllipsisLoc();
4525     D.setEllipsisLoc(SourceLocation());
4526
4527     bool hadGroupingParens = D.hasGroupingParens();
4528     D.setGroupingParens(true);
4529     ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
4530     // Match the ')'.
4531     T.consumeClose();
4532     D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
4533                                             T.getCloseLocation()),
4534                   attrs, T.getCloseLocation());
4535
4536     D.setGroupingParens(hadGroupingParens);
4537
4538     // An ellipsis cannot be placed outside parentheses.
4539     if (EllipsisLoc.isValid())
4540       diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
4541
4542     return;
4543   }
4544
4545   // Okay, if this wasn't a grouping paren, it must be the start of a function
4546   // argument list.  Recognize that this declarator will never have an
4547   // identifier (and remember where it would have been), then call into
4548   // ParseFunctionDeclarator to handle of argument list.
4549   D.SetIdentifier(0, Tok.getLocation());
4550
4551   // Enter function-declaration scope, limiting any declarators to the
4552   // function prototype scope, including parameter declarators.
4553   ParseScope PrototypeScope(this,
4554                             Scope::FunctionPrototypeScope|Scope::DeclScope);
4555   ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
4556   PrototypeScope.Exit();
4557 }
4558
4559 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
4560 /// declarator D up to a paren, which indicates that we are parsing function
4561 /// arguments.
4562 ///
4563 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
4564 /// immediately after the open paren - they should be considered to be the
4565 /// first argument of a parameter.
4566 ///
4567 /// If RequiresArg is true, then the first argument of the function is required
4568 /// to be present and required to not be an identifier list.
4569 ///
4570 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
4571 /// (C++11) ref-qualifier[opt], exception-specification[opt],
4572 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
4573 ///
4574 /// [C++11] exception-specification:
4575 ///           dynamic-exception-specification
4576 ///           noexcept-specification
4577 ///
4578 void Parser::ParseFunctionDeclarator(Declarator &D,
4579                                      ParsedAttributes &FirstArgAttrs,
4580                                      BalancedDelimiterTracker &Tracker,
4581                                      bool IsAmbiguous,
4582                                      bool RequiresArg) {
4583   assert(getCurScope()->isFunctionPrototypeScope() &&
4584          "Should call from a Function scope");
4585   // lparen is already consumed!
4586   assert(D.isPastIdentifier() && "Should not call before identifier!");
4587
4588   // This should be true when the function has typed arguments.
4589   // Otherwise, it is treated as a K&R-style function.
4590   bool HasProto = false;
4591   // Build up an array of information about the parsed arguments.
4592   SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
4593   // Remember where we see an ellipsis, if any.
4594   SourceLocation EllipsisLoc;
4595
4596   DeclSpec DS(AttrFactory);
4597   bool RefQualifierIsLValueRef = true;
4598   SourceLocation RefQualifierLoc;
4599   SourceLocation ConstQualifierLoc;
4600   SourceLocation VolatileQualifierLoc;
4601   ExceptionSpecificationType ESpecType = EST_None;
4602   SourceRange ESpecRange;
4603   SmallVector<ParsedType, 2> DynamicExceptions;
4604   SmallVector<SourceRange, 2> DynamicExceptionRanges;
4605   ExprResult NoexceptExpr;
4606   ParsedAttributes FnAttrs(AttrFactory);
4607   TypeResult TrailingReturnType;
4608
4609   Actions.ActOnStartFunctionDeclarator();
4610
4611   /* LocalEndLoc is the end location for the local FunctionTypeLoc.
4612      EndLoc is the end location for the function declarator.
4613      They differ for trailing return types. */
4614   SourceLocation StartLoc, LocalEndLoc, EndLoc;
4615   SourceLocation LParenLoc, RParenLoc;
4616   LParenLoc = Tracker.getOpenLocation();
4617   StartLoc = LParenLoc;
4618
4619   if (isFunctionDeclaratorIdentifierList()) {
4620     if (RequiresArg)
4621       Diag(Tok, diag::err_argument_required_after_attribute);
4622
4623     ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
4624
4625     Tracker.consumeClose();
4626     RParenLoc = Tracker.getCloseLocation();
4627     LocalEndLoc = RParenLoc;
4628     EndLoc = RParenLoc;
4629   } else {
4630     if (Tok.isNot(tok::r_paren))
4631       ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc);
4632     else if (RequiresArg)
4633       Diag(Tok, diag::err_argument_required_after_attribute);
4634
4635     HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
4636
4637     // If we have the closing ')', eat it.
4638     Tracker.consumeClose();
4639     RParenLoc = Tracker.getCloseLocation();
4640     LocalEndLoc = RParenLoc;
4641     EndLoc = RParenLoc;
4642
4643     if (getLangOpts().CPlusPlus) {
4644       // FIXME: Accept these components in any order, and produce fixits to
4645       // correct the order if the user gets it wrong. Ideally we should deal
4646       // with the virt-specifier-seq and pure-specifier in the same way.
4647
4648       // Parse cv-qualifier-seq[opt].
4649       ParseTypeQualifierListOpt(DS, false /*no attributes*/, false);
4650       if (!DS.getSourceRange().getEnd().isInvalid()) {
4651         EndLoc = DS.getSourceRange().getEnd();
4652         ConstQualifierLoc = DS.getConstSpecLoc();
4653         VolatileQualifierLoc = DS.getVolatileSpecLoc();
4654       }
4655
4656       // Parse ref-qualifier[opt].
4657       if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
4658         Diag(Tok, getLangOpts().CPlusPlus0x ?
4659              diag::warn_cxx98_compat_ref_qualifier :
4660              diag::ext_ref_qualifier);
4661
4662         RefQualifierIsLValueRef = Tok.is(tok::amp);
4663         RefQualifierLoc = ConsumeToken();
4664         EndLoc = RefQualifierLoc;
4665       }
4666
4667       // C++11 [expr.prim.general]p3:
4668       //   If a declaration declares a member function or member function
4669       //   template of a class X, the expression this is a prvalue of type
4670       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
4671       //   and the end of the function-definition, member-declarator, or
4672       //   declarator.
4673       bool IsCXX11MemberFunction =
4674         getLangOpts().CPlusPlus0x &&
4675         (D.getContext() == Declarator::MemberContext ||
4676          (D.getContext() == Declarator::FileContext &&
4677           D.getCXXScopeSpec().isValid() &&
4678           Actions.CurContext->isRecord()));
4679       Sema::CXXThisScopeRAII ThisScope(Actions,
4680                                dyn_cast<CXXRecordDecl>(Actions.CurContext),
4681                                DS.getTypeQualifiers(),
4682                                IsCXX11MemberFunction);
4683
4684       // Parse exception-specification[opt].
4685       ESpecType = tryParseExceptionSpecification(ESpecRange,
4686                                                  DynamicExceptions,
4687                                                  DynamicExceptionRanges,
4688                                                  NoexceptExpr);
4689       if (ESpecType != EST_None)
4690         EndLoc = ESpecRange.getEnd();
4691
4692       // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
4693       // after the exception-specification.
4694       MaybeParseCXX0XAttributes(FnAttrs);
4695
4696       // Parse trailing-return-type[opt].
4697       LocalEndLoc = EndLoc;
4698       if (getLangOpts().CPlusPlus0x && Tok.is(tok::arrow)) {
4699         Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
4700         if (D.getDeclSpec().getTypeSpecType() == TST_auto)
4701           StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4702         LocalEndLoc = Tok.getLocation();
4703         SourceRange Range;
4704         TrailingReturnType = ParseTrailingReturnType(Range);
4705         EndLoc = Range.getEnd();
4706       }
4707     }
4708   }
4709
4710   // Remember that we parsed a function type, and remember the attributes.
4711   D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
4712                                              IsAmbiguous,
4713                                              LParenLoc,
4714                                              ParamInfo.data(), ParamInfo.size(),
4715                                              EllipsisLoc, RParenLoc,
4716                                              DS.getTypeQualifiers(),
4717                                              RefQualifierIsLValueRef,
4718                                              RefQualifierLoc, ConstQualifierLoc,
4719                                              VolatileQualifierLoc,
4720                                              /*MutableLoc=*/SourceLocation(),
4721                                              ESpecType, ESpecRange.getBegin(),
4722                                              DynamicExceptions.data(),
4723                                              DynamicExceptionRanges.data(),
4724                                              DynamicExceptions.size(),
4725                                              NoexceptExpr.isUsable() ?
4726                                                NoexceptExpr.get() : 0,
4727                                              StartLoc, LocalEndLoc, D,
4728                                              TrailingReturnType),
4729                 FnAttrs, EndLoc);
4730
4731   Actions.ActOnEndFunctionDeclarator();
4732 }
4733
4734 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
4735 /// identifier list form for a K&R-style function:  void foo(a,b,c)
4736 ///
4737 /// Note that identifier-lists are only allowed for normal declarators, not for
4738 /// abstract-declarators.
4739 bool Parser::isFunctionDeclaratorIdentifierList() {
4740   return !getLangOpts().CPlusPlus
4741          && Tok.is(tok::identifier)
4742          && !TryAltiVecVectorToken()
4743          // K&R identifier lists can't have typedefs as identifiers, per C99
4744          // 6.7.5.3p11.
4745          && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
4746          // Identifier lists follow a really simple grammar: the identifiers can
4747          // be followed *only* by a ", identifier" or ")".  However, K&R
4748          // identifier lists are really rare in the brave new modern world, and
4749          // it is very common for someone to typo a type in a non-K&R style
4750          // list.  If we are presented with something like: "void foo(intptr x,
4751          // float y)", we don't want to start parsing the function declarator as
4752          // though it is a K&R style declarator just because intptr is an
4753          // invalid type.
4754          //
4755          // To handle this, we check to see if the token after the first
4756          // identifier is a "," or ")".  Only then do we parse it as an
4757          // identifier list.
4758          && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren));
4759 }
4760
4761 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
4762 /// we found a K&R-style identifier list instead of a typed parameter list.
4763 ///
4764 /// After returning, ParamInfo will hold the parsed parameters.
4765 ///
4766 ///       identifier-list: [C99 6.7.5]
4767 ///         identifier
4768 ///         identifier-list ',' identifier
4769 ///
4770 void Parser::ParseFunctionDeclaratorIdentifierList(
4771        Declarator &D,
4772        SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo) {
4773   // If there was no identifier specified for the declarator, either we are in
4774   // an abstract-declarator, or we are in a parameter declarator which was found
4775   // to be abstract.  In abstract-declarators, identifier lists are not valid:
4776   // diagnose this.
4777   if (!D.getIdentifier())
4778     Diag(Tok, diag::ext_ident_list_in_param);
4779
4780   // Maintain an efficient lookup of params we have seen so far.
4781   llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
4782
4783   while (1) {
4784     // If this isn't an identifier, report the error and skip until ')'.
4785     if (Tok.isNot(tok::identifier)) {
4786       Diag(Tok, diag::err_expected_ident);
4787       SkipUntil(tok::r_paren, /*StopAtSemi=*/true, /*DontConsume=*/true);
4788       // Forget we parsed anything.
4789       ParamInfo.clear();
4790       return;
4791     }
4792
4793     IdentifierInfo *ParmII = Tok.getIdentifierInfo();
4794
4795     // Reject 'typedef int y; int test(x, y)', but continue parsing.
4796     if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
4797       Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
4798
4799     // Verify that the argument identifier has not already been mentioned.
4800     if (!ParamsSoFar.insert(ParmII)) {
4801       Diag(Tok, diag::err_param_redefinition) << ParmII;
4802     } else {
4803       // Remember this identifier in ParamInfo.
4804       ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
4805                                                      Tok.getLocation(),
4806                                                      0));
4807     }
4808
4809     // Eat the identifier.
4810     ConsumeToken();
4811
4812     // The list continues if we see a comma.
4813     if (Tok.isNot(tok::comma))
4814       break;
4815     ConsumeToken();
4816   }
4817 }
4818
4819 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
4820 /// after the opening parenthesis. This function will not parse a K&R-style
4821 /// identifier list.
4822 ///
4823 /// D is the declarator being parsed.  If FirstArgAttrs is non-null, then the
4824 /// caller parsed those arguments immediately after the open paren - they should
4825 /// be considered to be part of the first parameter.
4826 ///
4827 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
4828 /// be the location of the ellipsis, if any was parsed.
4829 ///
4830 ///       parameter-type-list: [C99 6.7.5]
4831 ///         parameter-list
4832 ///         parameter-list ',' '...'
4833 /// [C++]   parameter-list '...'
4834 ///
4835 ///       parameter-list: [C99 6.7.5]
4836 ///         parameter-declaration
4837 ///         parameter-list ',' parameter-declaration
4838 ///
4839 ///       parameter-declaration: [C99 6.7.5]
4840 ///         declaration-specifiers declarator
4841 /// [C++]   declaration-specifiers declarator '=' assignment-expression
4842 /// [C++11]                                       initializer-clause
4843 /// [GNU]   declaration-specifiers declarator attributes
4844 ///         declaration-specifiers abstract-declarator[opt]
4845 /// [C++]   declaration-specifiers abstract-declarator[opt]
4846 ///           '=' assignment-expression
4847 /// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
4848 /// [C++11] attribute-specifier-seq parameter-declaration
4849 ///
4850 void Parser::ParseParameterDeclarationClause(
4851        Declarator &D,
4852        ParsedAttributes &FirstArgAttrs,
4853        SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo,
4854        SourceLocation &EllipsisLoc) {
4855
4856   while (1) {
4857     if (Tok.is(tok::ellipsis)) {
4858       // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
4859       // before deciding this was a parameter-declaration-clause.
4860       EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
4861       break;
4862     }
4863
4864     // Parse the declaration-specifiers.
4865     // Just use the ParsingDeclaration "scope" of the declarator.
4866     DeclSpec DS(AttrFactory);
4867
4868     // Parse any C++11 attributes.
4869     MaybeParseCXX0XAttributes(DS.getAttributes());
4870
4871     // Skip any Microsoft attributes before a param.
4872     if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
4873       ParseMicrosoftAttributes(DS.getAttributes());
4874
4875     SourceLocation DSStart = Tok.getLocation();
4876
4877     // If the caller parsed attributes for the first argument, add them now.
4878     // Take them so that we only apply the attributes to the first parameter.
4879     // FIXME: If we can leave the attributes in the token stream somehow, we can
4880     // get rid of a parameter (FirstArgAttrs) and this statement. It might be
4881     // too much hassle.
4882     DS.takeAttributesFrom(FirstArgAttrs);
4883
4884     ParseDeclarationSpecifiers(DS);
4885
4886     // Parse the declarator.  This is "PrototypeContext", because we must
4887     // accept either 'declarator' or 'abstract-declarator' here.
4888     Declarator ParmDecl(DS, Declarator::PrototypeContext);
4889     ParseDeclarator(ParmDecl);
4890
4891     // Parse GNU attributes, if present.
4892     MaybeParseGNUAttributes(ParmDecl);
4893
4894     // Remember this parsed parameter in ParamInfo.
4895     IdentifierInfo *ParmII = ParmDecl.getIdentifier();
4896
4897     // DefArgToks is used when the parsing of default arguments needs
4898     // to be delayed.
4899     CachedTokens *DefArgToks = 0;
4900
4901     // If no parameter was specified, verify that *something* was specified,
4902     // otherwise we have a missing type and identifier.
4903     if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
4904         ParmDecl.getNumTypeObjects() == 0) {
4905       // Completely missing, emit error.
4906       Diag(DSStart, diag::err_missing_param);
4907     } else {
4908       // Otherwise, we have something.  Add it and let semantic analysis try
4909       // to grok it and add the result to the ParamInfo we are building.
4910
4911       // Inform the actions module about the parameter declarator, so it gets
4912       // added to the current scope.
4913       Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
4914
4915       // Parse the default argument, if any. We parse the default
4916       // arguments in all dialects; the semantic analysis in
4917       // ActOnParamDefaultArgument will reject the default argument in
4918       // C.
4919       if (Tok.is(tok::equal)) {
4920         SourceLocation EqualLoc = Tok.getLocation();
4921
4922         // Parse the default argument
4923         if (D.getContext() == Declarator::MemberContext) {
4924           // If we're inside a class definition, cache the tokens
4925           // corresponding to the default argument. We'll actually parse
4926           // them when we see the end of the class definition.
4927           // FIXME: Can we use a smart pointer for Toks?
4928           DefArgToks = new CachedTokens;
4929
4930           if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
4931                                     /*StopAtSemi=*/true,
4932                                     /*ConsumeFinalToken=*/false)) {
4933             delete DefArgToks;
4934             DefArgToks = 0;
4935             Actions.ActOnParamDefaultArgumentError(Param);
4936           } else {
4937             // Mark the end of the default argument so that we know when to
4938             // stop when we parse it later on.
4939             Token DefArgEnd;
4940             DefArgEnd.startToken();
4941             DefArgEnd.setKind(tok::cxx_defaultarg_end);
4942             DefArgEnd.setLocation(Tok.getLocation());
4943             DefArgToks->push_back(DefArgEnd);
4944             Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
4945                                                 (*DefArgToks)[1].getLocation());
4946           }
4947         } else {
4948           // Consume the '='.
4949           ConsumeToken();
4950
4951           // The argument isn't actually potentially evaluated unless it is
4952           // used.
4953           EnterExpressionEvaluationContext Eval(Actions,
4954                                               Sema::PotentiallyEvaluatedIfUsed,
4955                                                 Param);
4956
4957           ExprResult DefArgResult;
4958           if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
4959             Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
4960             DefArgResult = ParseBraceInitializer();
4961           } else
4962             DefArgResult = ParseAssignmentExpression();
4963           if (DefArgResult.isInvalid()) {
4964             Actions.ActOnParamDefaultArgumentError(Param);
4965             SkipUntil(tok::comma, tok::r_paren, true, true);
4966           } else {
4967             // Inform the actions module about the default argument
4968             Actions.ActOnParamDefaultArgument(Param, EqualLoc,
4969                                               DefArgResult.take());
4970           }
4971         }
4972       }
4973
4974       ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
4975                                           ParmDecl.getIdentifierLoc(), Param,
4976                                           DefArgToks));
4977     }
4978
4979     // If the next token is a comma, consume it and keep reading arguments.
4980     if (Tok.isNot(tok::comma)) {
4981       if (Tok.is(tok::ellipsis)) {
4982         EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
4983
4984         if (!getLangOpts().CPlusPlus) {
4985           // We have ellipsis without a preceding ',', which is ill-formed
4986           // in C. Complain and provide the fix.
4987           Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
4988             << FixItHint::CreateInsertion(EllipsisLoc, ", ");
4989         }
4990       }
4991
4992       break;
4993     }
4994
4995     // Consume the comma.
4996     ConsumeToken();
4997   }
4998
4999 }
5000
5001 /// [C90]   direct-declarator '[' constant-expression[opt] ']'
5002 /// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5003 /// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5004 /// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5005 /// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
5006 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5007 ///                           attribute-specifier-seq[opt]
5008 void Parser::ParseBracketDeclarator(Declarator &D) {
5009   if (CheckProhibitedCXX11Attribute())
5010     return;
5011
5012   BalancedDelimiterTracker T(*this, tok::l_square);
5013   T.consumeOpen();
5014
5015   // C array syntax has many features, but by-far the most common is [] and [4].
5016   // This code does a fast path to handle some of the most obvious cases.
5017   if (Tok.getKind() == tok::r_square) {
5018     T.consumeClose();
5019     ParsedAttributes attrs(AttrFactory);
5020     MaybeParseCXX0XAttributes(attrs);
5021
5022     // Remember that we parsed the empty array type.
5023     ExprResult NumElements;
5024     D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
5025                                             T.getOpenLocation(),
5026                                             T.getCloseLocation()),
5027                   attrs, T.getCloseLocation());
5028     return;
5029   } else if (Tok.getKind() == tok::numeric_constant &&
5030              GetLookAheadToken(1).is(tok::r_square)) {
5031     // [4] is very common.  Parse the numeric constant expression.
5032     ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
5033     ConsumeToken();
5034
5035     T.consumeClose();
5036     ParsedAttributes attrs(AttrFactory);
5037     MaybeParseCXX0XAttributes(attrs);
5038
5039     // Remember that we parsed a array type, and remember its features.
5040     D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0,
5041                                             ExprRes.release(),
5042                                             T.getOpenLocation(),
5043                                             T.getCloseLocation()),
5044                   attrs, T.getCloseLocation());
5045     return;
5046   }
5047
5048   // If valid, this location is the position where we read the 'static' keyword.
5049   SourceLocation StaticLoc;
5050   if (Tok.is(tok::kw_static))
5051     StaticLoc = ConsumeToken();
5052
5053   // If there is a type-qualifier-list, read it now.
5054   // Type qualifiers in an array subscript are a C99 feature.
5055   DeclSpec DS(AttrFactory);
5056   ParseTypeQualifierListOpt(DS, false /*no attributes*/);
5057
5058   // If we haven't already read 'static', check to see if there is one after the
5059   // type-qualifier-list.
5060   if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
5061     StaticLoc = ConsumeToken();
5062
5063   // Handle "direct-declarator [ type-qual-list[opt] * ]".
5064   bool isStar = false;
5065   ExprResult NumElements;
5066
5067   // Handle the case where we have '[*]' as the array size.  However, a leading
5068   // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
5069   // the token after the star is a ']'.  Since stars in arrays are
5070   // infrequent, use of lookahead is not costly here.
5071   if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
5072     ConsumeToken();  // Eat the '*'.
5073
5074     if (StaticLoc.isValid()) {
5075       Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
5076       StaticLoc = SourceLocation();  // Drop the static.
5077     }
5078     isStar = true;
5079   } else if (Tok.isNot(tok::r_square)) {
5080     // Note, in C89, this production uses the constant-expr production instead
5081     // of assignment-expr.  The only difference is that assignment-expr allows
5082     // things like '=' and '*='.  Sema rejects these in C89 mode because they
5083     // are not i-c-e's, so we don't need to distinguish between the two here.
5084
5085     // Parse the constant-expression or assignment-expression now (depending
5086     // on dialect).
5087     if (getLangOpts().CPlusPlus) {
5088       NumElements = ParseConstantExpression();
5089     } else {
5090       EnterExpressionEvaluationContext Unevaluated(Actions,
5091                                                    Sema::ConstantEvaluated);
5092       NumElements = ParseAssignmentExpression();
5093     }
5094   }
5095
5096   // If there was an error parsing the assignment-expression, recover.
5097   if (NumElements.isInvalid()) {
5098     D.setInvalidType(true);
5099     // If the expression was invalid, skip it.
5100     SkipUntil(tok::r_square);
5101     return;
5102   }
5103
5104   T.consumeClose();
5105
5106   ParsedAttributes attrs(AttrFactory);
5107   MaybeParseCXX0XAttributes(attrs);
5108
5109   // Remember that we parsed a array type, and remember its features.
5110   D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
5111                                           StaticLoc.isValid(), isStar,
5112                                           NumElements.release(),
5113                                           T.getOpenLocation(),
5114                                           T.getCloseLocation()),
5115                 attrs, T.getCloseLocation());
5116 }
5117
5118 /// [GNU]   typeof-specifier:
5119 ///           typeof ( expressions )
5120 ///           typeof ( type-name )
5121 /// [GNU/C++] typeof unary-expression
5122 ///
5123 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
5124   assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
5125   Token OpTok = Tok;
5126   SourceLocation StartLoc = ConsumeToken();
5127
5128   const bool hasParens = Tok.is(tok::l_paren);
5129
5130   EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
5131                                                Sema::ReuseLambdaContextDecl);
5132
5133   bool isCastExpr;
5134   ParsedType CastTy;
5135   SourceRange CastRange;
5136   ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
5137                                                           CastTy, CastRange);
5138   if (hasParens)
5139     DS.setTypeofParensRange(CastRange);
5140
5141   if (CastRange.getEnd().isInvalid())
5142     // FIXME: Not accurate, the range gets one token more than it should.
5143     DS.SetRangeEnd(Tok.getLocation());
5144   else
5145     DS.SetRangeEnd(CastRange.getEnd());
5146
5147   if (isCastExpr) {
5148     if (!CastTy) {
5149       DS.SetTypeSpecError();
5150       return;
5151     }
5152
5153     const char *PrevSpec = 0;
5154     unsigned DiagID;
5155     // Check for duplicate type specifiers (e.g. "int typeof(int)").
5156     if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
5157                            DiagID, CastTy))
5158       Diag(StartLoc, DiagID) << PrevSpec;
5159     return;
5160   }
5161
5162   // If we get here, the operand to the typeof was an expresion.
5163   if (Operand.isInvalid()) {
5164     DS.SetTypeSpecError();
5165     return;
5166   }
5167
5168   // We might need to transform the operand if it is potentially evaluated.
5169   Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
5170   if (Operand.isInvalid()) {
5171     DS.SetTypeSpecError();
5172     return;
5173   }
5174
5175   const char *PrevSpec = 0;
5176   unsigned DiagID;
5177   // Check for duplicate type specifiers (e.g. "int typeof(int)").
5178   if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
5179                          DiagID, Operand.get()))
5180     Diag(StartLoc, DiagID) << PrevSpec;
5181 }
5182
5183 /// [C11]   atomic-specifier:
5184 ///           _Atomic ( type-name )
5185 ///
5186 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
5187   assert(Tok.is(tok::kw__Atomic) && "Not an atomic specifier");
5188
5189   SourceLocation StartLoc = ConsumeToken();
5190   BalancedDelimiterTracker T(*this, tok::l_paren);
5191   if (T.expectAndConsume(diag::err_expected_lparen_after, "_Atomic")) {
5192     SkipUntil(tok::r_paren);
5193     return;
5194   }
5195
5196   TypeResult Result = ParseTypeName();
5197   if (Result.isInvalid()) {
5198     SkipUntil(tok::r_paren);
5199     return;
5200   }
5201
5202   // Match the ')'
5203   T.consumeClose();
5204
5205   if (T.getCloseLocation().isInvalid())
5206     return;
5207
5208   DS.setTypeofParensRange(T.getRange());
5209   DS.SetRangeEnd(T.getCloseLocation());
5210
5211   const char *PrevSpec = 0;
5212   unsigned DiagID;
5213   if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
5214                          DiagID, Result.release()))
5215     Diag(StartLoc, DiagID) << PrevSpec;
5216 }
5217
5218
5219 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
5220 /// from TryAltiVecVectorToken.
5221 bool Parser::TryAltiVecVectorTokenOutOfLine() {
5222   Token Next = NextToken();
5223   switch (Next.getKind()) {
5224   default: return false;
5225   case tok::kw_short:
5226   case tok::kw_long:
5227   case tok::kw_signed:
5228   case tok::kw_unsigned:
5229   case tok::kw_void:
5230   case tok::kw_char:
5231   case tok::kw_int:
5232   case tok::kw_float:
5233   case tok::kw_double:
5234   case tok::kw_bool:
5235   case tok::kw___pixel:
5236     Tok.setKind(tok::kw___vector);
5237     return true;
5238   case tok::identifier:
5239     if (Next.getIdentifierInfo() == Ident_pixel) {
5240       Tok.setKind(tok::kw___vector);
5241       return true;
5242     }
5243     return false;
5244   }
5245 }
5246
5247 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
5248                                       const char *&PrevSpec, unsigned &DiagID,
5249                                       bool &isInvalid) {
5250   if (Tok.getIdentifierInfo() == Ident_vector) {
5251     Token Next = NextToken();
5252     switch (Next.getKind()) {
5253     case tok::kw_short:
5254     case tok::kw_long:
5255     case tok::kw_signed:
5256     case tok::kw_unsigned:
5257     case tok::kw_void:
5258     case tok::kw_char:
5259     case tok::kw_int:
5260     case tok::kw_float:
5261     case tok::kw_double:
5262     case tok::kw_bool:
5263     case tok::kw___pixel:
5264       isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
5265       return true;
5266     case tok::identifier:
5267       if (Next.getIdentifierInfo() == Ident_pixel) {
5268         isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
5269         return true;
5270       }
5271       break;
5272     default:
5273       break;
5274     }
5275   } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
5276              DS.isTypeAltiVecVector()) {
5277     isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
5278     return true;
5279   }
5280   return false;
5281 }