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