Coverage Report

Created: 2020-09-15 12:33

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Parse/ParseDecl.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements the Declaration portions of the Parser interfaces.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Parse/Parser.h"
14
#include "clang/Parse/RAIIObjectsForParser.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/DeclTemplate.h"
17
#include "clang/AST/PrettyDeclStackTrace.h"
18
#include "clang/Basic/AddressSpaces.h"
19
#include "clang/Basic/Attributes.h"
20
#include "clang/Basic/CharInfo.h"
21
#include "clang/Basic/TargetInfo.h"
22
#include "clang/Parse/ParseDiagnostic.h"
23
#include "clang/Sema/Lookup.h"
24
#include "clang/Sema/ParsedTemplate.h"
25
#include "clang/Sema/Scope.h"
26
#include "llvm/ADT/Optional.h"
27
#include "llvm/ADT/SmallSet.h"
28
#include "llvm/ADT/SmallString.h"
29
#include "llvm/ADT/StringSwitch.h"
30
31
using namespace clang;
32
33
//===----------------------------------------------------------------------===//
34
// C99 6.7: Declarations.
35
//===----------------------------------------------------------------------===//
36
37
/// ParseTypeName
38
///       type-name: [C99 6.7.6]
39
///         specifier-qualifier-list abstract-declarator[opt]
40
///
41
/// Called type-id in C++.
42
TypeResult Parser::ParseTypeName(SourceRange *Range,
43
                                 DeclaratorContext Context,
44
                                 AccessSpecifier AS,
45
                                 Decl **OwnedType,
46
3.75M
                                 ParsedAttributes *Attrs) {
47
3.75M
  DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
48
3.75M
  if (DSC == DeclSpecContext::DSC_normal)
49
281k
    DSC = DeclSpecContext::DSC_type_specifier;
50
3.75M
51
  // Parse the common declaration-specifiers piece.
52
3.75M
  DeclSpec DS(AttrFactory);
53
3.75M
  if (Attrs)
54
56.3k
    DS.addAttributes(*Attrs);
55
3.75M
  ParseSpecifierQualifierList(DS, AS, DSC);
56
3.75M
  if (OwnedType)
57
56.3k
    *OwnedType = DS.isTypeSpecOwned() ? 
DS.getRepAsDecl()43
:
nullptr56.3k
;
58
3.75M
59
  // Parse the abstract-declarator, if present.
60
3.75M
  Declarator DeclaratorInfo(DS, Context);
61
3.75M
  ParseDeclarator(DeclaratorInfo);
62
3.75M
  if (Range)
63
20.0k
    *Range = DeclaratorInfo.getSourceRange();
64
3.75M
65
3.75M
  if (DeclaratorInfo.isInvalidType())
66
299
    return true;
67
3.75M
68
3.75M
  return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
69
3.75M
}
70
71
/// Normalizes an attribute name by dropping prefixed and suffixed __.
72
62.1M
static StringRef normalizeAttrName(StringRef Name) {
73
62.1M
  if (Name.size() >= 4 && 
Name.startswith("__")62.1M
&&
Name.endswith("__")55.5M
)
74
17.4M
    return Name.drop_front(2).drop_back(2);
75
44.6M
  return Name;
76
44.6M
}
77
78
/// isAttributeLateParsed - Return true if the attribute has arguments that
79
/// require late parsing.
80
2.91M
static bool isAttributeLateParsed(const IdentifierInfo &II) {
81
2.91M
#define CLANG_ATTR_LATE_PARSED_LIST
82
2.91M
    return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
83
2.91M
#include "clang/Parse/AttrParserStringSwitches.inc"
84
2.91M
        .Default(false);
85
2.91M
#undef CLANG_ATTR_LATE_PARSED_LIST
86
2.91M
}
87
88
/// Check if the a start and end source location expand to the same macro.
89
static bool FindLocsWithCommonFileID(Preprocessor &PP, SourceLocation StartLoc,
90
27.4M
                                     SourceLocation EndLoc) {
91
27.4M
  if (!StartLoc.isMacroID() || 
!EndLoc.isMacroID()19.5M
)
92
7.90M
    return false;
93
19.5M
94
19.5M
  SourceManager &SM = PP.getSourceManager();
95
19.5M
  if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
96
17.2k
    return false;
97
19.5M
98
19.5M
  bool AttrStartIsInMacro =
99
19.5M
      Lexer::isAtStartOfMacroExpansion(StartLoc, SM, PP.getLangOpts());
100
19.5M
  bool AttrEndIsInMacro =
101
19.5M
      Lexer::isAtEndOfMacroExpansion(EndLoc, SM, PP.getLangOpts());
102
19.5M
  return AttrStartIsInMacro && 
AttrEndIsInMacro7.06M
;
103
19.5M
}
104
105
/// ParseGNUAttributes - Parse a non-empty attributes list.
106
///
107
/// [GNU] attributes:
108
///         attribute
109
///         attributes attribute
110
///
111
/// [GNU]  attribute:
112
///          '__attribute__' '(' '(' attribute-list ')' ')'
113
///
114
/// [GNU]  attribute-list:
115
///          attrib
116
///          attribute_list ',' attrib
117
///
118
/// [GNU]  attrib:
119
///          empty
120
///          attrib-name
121
///          attrib-name '(' identifier ')'
122
///          attrib-name '(' identifier ',' nonempty-expr-list ')'
123
///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
124
///
125
/// [GNU]  attrib-name:
126
///          identifier
127
///          typespec
128
///          typequal
129
///          storageclass
130
///
131
/// Whether an attribute takes an 'identifier' is determined by the
132
/// attrib-name. GCC's behavior here is not worth imitating:
133
///
134
///  * In C mode, if the attribute argument list starts with an identifier
135
///    followed by a ',' or an ')', and the identifier doesn't resolve to
136
///    a type, it is parsed as an identifier. If the attribute actually
137
///    wanted an expression, it's out of luck (but it turns out that no
138
///    attributes work that way, because C constant expressions are very
139
///    limited).
140
///  * In C++ mode, if the attribute argument list starts with an identifier,
141
///    and the attribute *wants* an identifier, it is parsed as an identifier.
142
///    At block scope, any additional tokens between the identifier and the
143
///    ',' or ')' are ignored, otherwise they produce a parse error.
144
///
145
/// We follow the C++ model, but don't allow junk after the identifier.
146
void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
147
                                SourceLocation *endLoc,
148
                                LateParsedAttrList *LateAttrs,
149
15.2M
                                Declarator *D) {
150
15.2M
  assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
151
15.2M
152
42.7M
  while (Tok.is(tok::kw___attribute)) {
153
27.4M
    SourceLocation AttrTokLoc = ConsumeToken();
154
27.4M
    unsigned OldNumAttrs = attrs.size();
155
23.9M
    unsigned OldNumLateAttrs = LateAttrs ? 
LateAttrs->size()3.52M
: 0;
156
27.4M
157
27.4M
    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
158
0
                         "attribute")) {
159
0
      SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
160
0
      return;
161
0
    }
162
27.4M
    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
163
0
      SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
164
0
      return;
165
0
    }
166
    // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
167
44.7M
    
do 27.4M
{
168
      // Eat preceeding commas to allow __attribute__((,,,foo))
169
61.9M
      while (TryConsumeToken(tok::comma))
170
17.2M
        ;
171
44.7M
172
      // Expect an identifier or declaration specifier (const, int, etc.)
173
44.7M
      if (Tok.isAnnotation())
174
0
        break;
175
44.7M
      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
176
44.7M
      if (!AttrName)
177
34
        break;
178
44.7M
179
44.7M
      SourceLocation AttrNameLoc = ConsumeToken();
180
44.7M
181
44.7M
      if (Tok.isNot(tok::l_paren)) {
182
25.2M
        attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
183
25.2M
                     ParsedAttr::AS_GNU);
184
25.2M
        continue;
185
25.2M
      }
186
19.5M
187
      // Handle "parameterized" attributes
188
19.5M
      if (!LateAttrs || 
!isAttributeLateParsed(*AttrName)2.91M
) {
189
19.5M
        ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
190
19.5M
                              SourceLocation(), ParsedAttr::AS_GNU, D);
191
19.5M
        continue;
192
19.5M
      }
193
9.85k
194
      // Handle attributes with arguments that require late parsing.
195
9.85k
      LateParsedAttribute *LA =
196
9.85k
          new LateParsedAttribute(this, *AttrName, AttrNameLoc);
197
9.85k
      LateAttrs->push_back(LA);
198
9.85k
199
      // Attributes in a class are parsed at the end of the class, along
200
      // with other late-parsed declarations.
201
9.85k
      if (!ClassStack.empty() && 
!LateAttrs->parseSoon()5.09k
)
202
5.08k
        getCurrentClass().LateParsedDeclarations.push_back(LA);
203
9.85k
204
      // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
205
      // recursively consumes balanced parens.
206
9.85k
      LA->Toks.push_back(Tok);
207
9.85k
      ConsumeParen();
208
      // Consume everything up to and including the matching right parens.
209
9.85k
      ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
210
9.85k
211
9.85k
      Token Eof;
212
9.85k
      Eof.startToken();
213
9.85k
      Eof.setLocation(Tok.getLocation());
214
9.85k
      LA->Toks.push_back(Eof);
215
44.7M
    } while (Tok.is(tok::comma));
216
27.4M
217
27.4M
    if (ExpectAndConsume(tok::r_paren))
218
3
      SkipUntil(tok::r_paren, StopAtSemi);
219
27.4M
    SourceLocation Loc = Tok.getLocation();
220
27.4M
    if (ExpectAndConsume(tok::r_paren))
221
1
      SkipUntil(tok::r_paren, StopAtSemi);
222
27.4M
    if (endLoc)
223
5.84M
      *endLoc = Loc;
224
27.4M
225
    // If this was declared in a macro, attach the macro IdentifierInfo to the
226
    // parsed attribute.
227
27.4M
    auto &SM = PP.getSourceManager();
228
27.4M
    if (!SM.isWrittenInBuiltinFile(SM.getSpellingLoc(AttrTokLoc)) &&
229
27.4M
        FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)) {
230
4.31M
      CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
231
4.31M
      StringRef FoundName =
232
4.31M
          Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
233
4.31M
      IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
234
4.31M
235
11.8M
      for (unsigned i = OldNumAttrs; i < attrs.size(); 
++i7.55M
)
236
7.55M
        attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
237
4.31M
238
4.31M
      if (LateAttrs) {
239
997k
        for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); 
++i9.69k
)
240
9.69k
          (*LateAttrs)[i]->MacroII = MacroII;
241
987k
      }
242
4.31M
    }
243
27.4M
  }
244
15.2M
}
245
246
/// Determine whether the given attribute has an identifier argument.
247
7.85M
static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
248
7.85M
#define CLANG_ATTR_IDENTIFIER_ARG_LIST
249
7.85M
  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
250
7.85M
#include "clang/Parse/AttrParserStringSwitches.inc"
251
7.85M
           .Default(false);
252
7.85M
#undef CLANG_ATTR_IDENTIFIER_ARG_LIST
253
7.85M
}
254
255
/// Determine whether the given attribute has a variadic identifier argument.
256
21.1k
static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II) {
257
21.1k
#define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
258
21.1k
  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
259
21.1k
#include "clang/Parse/AttrParserStringSwitches.inc"
260
21.1k
           .Default(false);
261
21.1k
#undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
262
21.1k
}
263
264
/// Determine whether the given attribute treats kw_this as an identifier.
265
11.8M
static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II) {
266
11.8M
#define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
267
11.8M
  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
268
11.8M
#include "clang/Parse/AttrParserStringSwitches.inc"
269
11.8M
           .Default(false);
270
11.8M
#undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
271
11.8M
}
272
273
/// Determine whether the given attribute parses a type argument.
274
23.6M
static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
275
23.6M
#define CLANG_ATTR_TYPE_ARG_LIST
276
23.6M
  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
277
23.6M
#include "clang/Parse/AttrParserStringSwitches.inc"
278
23.6M
           .Default(false);
279
23.6M
#undef CLANG_ATTR_TYPE_ARG_LIST
280
23.6M
}
281
282
/// Determine whether the given attribute requires parsing its arguments
283
/// in an unevaluated context or not.
284
4.07M
static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
285
4.07M
#define CLANG_ATTR_ARG_CONTEXT_LIST
286
4.07M
  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
287
4.07M
#include "clang/Parse/AttrParserStringSwitches.inc"
288
4.07M
           .Default(false);
289
4.07M
#undef CLANG_ATTR_ARG_CONTEXT_LIST
290
4.07M
}
291
292
15.5M
IdentifierLoc *Parser::ParseIdentifierLoc() {
293
15.5M
  assert(Tok.is(tok::identifier) && "expected an identifier");
294
15.5M
  IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
295
15.5M
                                            Tok.getLocation(),
296
15.5M
                                            Tok.getIdentifierInfo());
297
15.5M
  ConsumeToken();
298
15.5M
  return IL;
299
15.5M
}
300
301
void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
302
                                       SourceLocation AttrNameLoc,
303
                                       ParsedAttributes &Attrs,
304
                                       SourceLocation *EndLoc,
305
                                       IdentifierInfo *ScopeName,
306
                                       SourceLocation ScopeLoc,
307
50
                                       ParsedAttr::Syntax Syntax) {
308
50
  BalancedDelimiterTracker Parens(*this, tok::l_paren);
309
50
  Parens.consumeOpen();
310
50
311
50
  TypeResult T;
312
50
  if (Tok.isNot(tok::r_paren))
313
46
    T = ParseTypeName();
314
50
315
50
  if (Parens.consumeClose())
316
5
    return;
317
45
318
45
  if (T.isInvalid())
319
5
    return;
320
40
321
40
  if (T.isUsable())
322
36
    Attrs.addNewTypeAttr(&AttrName,
323
36
                         SourceRange(AttrNameLoc, Parens.getCloseLocation()),
324
36
                         ScopeName, ScopeLoc, T.get(), Syntax);
325
4
  else
326
4
    Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
327
4
                 ScopeName, ScopeLoc, nullptr, 0, Syntax);
328
40
}
329
330
unsigned Parser::ParseAttributeArgsCommon(
331
    IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
332
    ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
333
11.8M
    SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
334
  // Ignore the left paren location for now.
335
11.8M
  ConsumeParen();
336
11.8M
337
11.8M
  bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
338
11.8M
  bool AttributeIsTypeArgAttr = attributeIsTypeArgAttr(*AttrName);
339
11.8M
340
  // Interpret "kw_this" as an identifier if the attributed requests it.
341
11.8M
  if (ChangeKWThisToIdent && 
Tok.is(tok::kw_this)142
)
342
1
    Tok.setKind(tok::identifier);
343
11.8M
344
11.8M
  ArgsVector ArgExprs;
345
11.8M
  if (Tok.is(tok::identifier)) {
346
    // If this attribute wants an 'identifier' argument, make it so.
347
7.85M
    bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName) ||
348
10.4k
                           attributeHasVariadicIdentifierArg(*AttrName);
349
7.85M
    ParsedAttr::Kind AttrKind =
350
7.85M
        ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
351
7.85M
352
    // If we don't know how to parse this attribute, but this is the only
353
    // token in this argument, assume it's meant to be an identifier.
354
7.85M
    if (AttrKind == ParsedAttr::UnknownAttribute ||
355
7.85M
        AttrKind == ParsedAttr::IgnoredAttribute) {
356
7
      const Token &Next = NextToken();
357
7
      IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
358
7
    }
359
7.85M
360
7.85M
    if (IsIdentifierArg)
361
7.84M
      ArgExprs.push_back(ParseIdentifierLoc());
362
7.85M
  }
363
11.8M
364
11.8M
  ParsedType TheParsedType;
365
11.8M
  if (!ArgExprs.empty() ? 
Tok.is(tok::comma)7.84M
:
Tok.isNot(tok::r_paren)3.96M
) {
366
    // Eat the comma.
367
4.00M
    if (!ArgExprs.empty())
368
37.2k
      ConsumeToken();
369
4.00M
370
    // Parse the non-empty comma-separated list of expressions.
371
4.07M
    do {
372
      // Interpret "kw_this" as an identifier if the attributed requests it.
373
4.07M
      if (ChangeKWThisToIdent && 
Tok.is(tok::kw_this)269
)
374
4
        Tok.setKind(tok::identifier);
375
4.07M
376
4.07M
      ExprResult ArgExpr;
377
4.07M
      if (AttributeIsTypeArgAttr) {
378
33
        TypeResult T = ParseTypeName();
379
33
        if (T.isInvalid()) {
380
2
          SkipUntil(tok::r_paren, StopAtSemi);
381
2
          return 0;
382
2
        }
383
31
        if (T.isUsable())
384
31
          TheParsedType = T.get();
385
31
        break; // FIXME: Multiple type arguments are not implemented.
386
4.07M
      } else if (Tok.is(tok::identifier) &&
387
10.7k
                 attributeHasVariadicIdentifierArg(*AttrName)) {
388
133
        ArgExprs.push_back(ParseIdentifierLoc());
389
4.07M
      } else {
390
4.07M
        bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
391
4.07M
        EnterExpressionEvaluationContext Unevaluated(
392
4.07M
            Actions,
393
3.10k
            Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
394
4.06M
                   : Sema::ExpressionEvaluationContext::ConstantEvaluated);
395
4.07M
396
4.07M
        ExprResult ArgExpr(
397
4.07M
            Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
398
4.07M
        if (ArgExpr.isInvalid()) {
399
36
          SkipUntil(tok::r_paren, StopAtSemi);
400
36
          return 0;
401
36
        }
402
4.07M
        ArgExprs.push_back(ArgExpr.get());
403
4.07M
      }
404
      // Eat the comma, move to the next argument
405
4.07M
    } while (TryConsumeToken(tok::comma));
406
4.00M
  }
407
11.8M
408
11.8M
  SourceLocation RParen = Tok.getLocation();
409
11.8M
  if (!ExpectAndConsume(tok::r_paren)) {
410
11.8M
    SourceLocation AttrLoc = ScopeLoc.isValid() ? 
ScopeLoc156
: AttrNameLoc;
411
11.8M
412
11.8M
    if (AttributeIsTypeArgAttr && 
!TheParsedType.get().isNull()34
) {
413
31
      Attrs.addNewTypeAttr(AttrName, SourceRange(AttrNameLoc, RParen),
414
31
                           ScopeName, ScopeLoc, TheParsedType, Syntax);
415
11.8M
    } else {
416
11.8M
      Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
417
11.8M
                   ArgExprs.data(), ArgExprs.size(), Syntax);
418
11.8M
    }
419
11.8M
  }
420
11.8M
421
11.8M
  if (EndLoc)
422
98.2k
    *EndLoc = RParen;
423
11.8M
424
11.8M
  return static_cast<unsigned>(ArgExprs.size() + !TheParsedType.get().isNull());
425
11.8M
}
426
427
/// Parse the arguments to a parameterized GNU attribute or
428
/// a C++11 attribute in "gnu" namespace.
429
void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
430
                                   SourceLocation AttrNameLoc,
431
                                   ParsedAttributes &Attrs,
432
                                   SourceLocation *EndLoc,
433
                                   IdentifierInfo *ScopeName,
434
                                   SourceLocation ScopeLoc,
435
                                   ParsedAttr::Syntax Syntax,
436
19.5M
                                   Declarator *D) {
437
19.5M
438
19.5M
  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
439
19.5M
440
19.5M
  ParsedAttr::Kind AttrKind =
441
19.5M
      ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
442
19.5M
443
19.5M
  if (AttrKind == ParsedAttr::AT_Availability) {
444
7.71M
    ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
445
7.71M
                               ScopeLoc, Syntax);
446
7.71M
    return;
447
11.8M
  } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
448
75
    ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
449
75
                                       ScopeName, ScopeLoc, Syntax);
450
75
    return;
451
11.8M
  } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
452
618
    ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
453
618
                                    ScopeName, ScopeLoc, Syntax);
454
618
    return;
455
11.8M
  } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
456
179
    ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
457
179
                                     ScopeName, ScopeLoc, Syntax);
458
179
    return;
459
11.8M
  } else if (attributeIsTypeArgAttr(*AttrName)) {
460
50
    ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
461
50
                              ScopeLoc, Syntax);
462
50
    return;
463
50
  }
464
11.8M
465
  // These may refer to the function arguments, but need to be parsed early to
466
  // participate in determining whether it's a redeclaration.
467
11.8M
  llvm::Optional<ParseScope> PrototypeScope;
468
11.8M
  if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
469
10.4k
      D && 
D->isFunctionDeclarator()1.80k
) {
470
1.80k
    DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
471
1.80k
    PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
472
1.80k
                                     Scope::FunctionDeclarationScope |
473
1.80k
                                     Scope::DeclScope);
474
6.11k
    for (unsigned i = 0; i != FTI.NumParams; 
++i4.30k
) {
475
4.30k
      ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
476
4.30k
      Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
477
4.30k
    }
478
1.80k
  }
479
11.8M
480
11.8M
  ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
481
11.8M
                           ScopeLoc, Syntax);
482
11.8M
}
483
484
unsigned Parser::ParseClangAttributeArgs(
485
    IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
486
    ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
487
96
    SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
488
96
  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
489
96
490
96
  ParsedAttr::Kind AttrKind =
491
96
      ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
492
96
493
96
  switch (AttrKind) {
494
71
  default:
495
71
    return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
496
71
                                    ScopeName, ScopeLoc, Syntax);
497
5
  case ParsedAttr::AT_ExternalSourceSymbol:
498
5
    ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
499
5
                                       ScopeName, ScopeLoc, Syntax);
500
5
    break;
501
7
  case ParsedAttr::AT_Availability:
502
7
    ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
503
7
                               ScopeLoc, Syntax);
504
7
    break;
505
4
  case ParsedAttr::AT_ObjCBridgeRelated:
506
4
    ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
507
4
                                    ScopeName, ScopeLoc, Syntax);
508
4
    break;
509
9
  case ParsedAttr::AT_TypeTagForDatatype:
510
9
    ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
511
9
                                     ScopeName, ScopeLoc, Syntax);
512
9
    break;
513
25
  }
514
25
  return !Attrs.empty() ? 
Attrs.begin()->getNumArgs()17
:
08
;
515
25
}
516
517
bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
518
                                        SourceLocation AttrNameLoc,
519
567
                                        ParsedAttributes &Attrs) {
520
  // If the attribute isn't known, we will not attempt to parse any
521
  // arguments.
522
567
  if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
523
1
                    getTargetInfo(), getLangOpts())) {
524
    // Eat the left paren, then skip to the ending right paren.
525
1
    ConsumeParen();
526
1
    SkipUntil(tok::r_paren);
527
1
    return false;
528
1
  }
529
566
530
566
  SourceLocation OpenParenLoc = Tok.getLocation();
531
566
532
566
  if (AttrName->getName() == "property") {
533
    // The property declspec is more complex in that it can take one or two
534
    // assignment expressions as a parameter, but the lhs of the assignment
535
    // must be named get or put.
536
103
537
103
    BalancedDelimiterTracker T(*this, tok::l_paren);
538
103
    T.expectAndConsume(diag::err_expected_lparen_after,
539
103
                       AttrName->getNameStart(), tok::r_paren);
540
103
541
103
    enum AccessorKind {
542
103
      AK_Invalid = -1,
543
103
      AK_Put = 0,
544
103
      AK_Get = 1 // indices into AccessorNames
545
103
    };
546
103
    IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
547
103
    bool HasInvalidAccessor = false;
548
103
549
    // Parse the accessor specifications.
550
140
    while (true) {
551
      // Stop if this doesn't look like an accessor spec.
552
140
      if (!Tok.is(tok::identifier)) {
553
        // If the user wrote a completely empty list, use a special diagnostic.
554
2
        if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
555
2
            AccessorNames[AK_Put] == nullptr &&
556
2
            AccessorNames[AK_Get] == nullptr) {
557
1
          Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
558
1
          break;
559
1
        }
560
1
561
1
        Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
562
1
        break;
563
1
      }
564
138
565
138
      AccessorKind Kind;
566
138
      SourceLocation KindLoc = Tok.getLocation();
567
138
      StringRef KindStr = Tok.getIdentifierInfo()->getName();
568
138
      if (KindStr == "get") {
569
97
        Kind = AK_Get;
570
41
      } else if (KindStr == "put") {
571
38
        Kind = AK_Put;
572
38
573
        // Recover from the common mistake of using 'set' instead of 'put'.
574
3
      } else if (KindStr == "set") {
575
1
        Diag(KindLoc, diag::err_ms_property_has_set_accessor)
576
1
            << FixItHint::CreateReplacement(KindLoc, "put");
577
1
        Kind = AK_Put;
578
1
579
        // Handle the mistake of forgetting the accessor kind by skipping
580
        // this accessor.
581
2
      } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
582
1
        Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
583
1
        ConsumeToken();
584
1
        HasInvalidAccessor = true;
585
1
        goto next_property_accessor;
586
1
587
        // Otherwise, complain about the unknown accessor kind.
588
1
      } else {
589
1
        Diag(KindLoc, diag::err_ms_property_unknown_accessor);
590
1
        HasInvalidAccessor = true;
591
1
        Kind = AK_Invalid;
592
1
593
        // Try to keep parsing unless it doesn't look like an accessor spec.
594
1
        if (!NextToken().is(tok::equal))
595
0
          break;
596
137
      }
597
137
598
      // Consume the identifier.
599
137
      ConsumeToken();
600
137
601
      // Consume the '='.
602
137
      if (!TryConsumeToken(tok::equal)) {
603
3
        Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
604
3
            << KindStr;
605
3
        break;
606
3
      }
607
134
608
      // Expect the method name.
609
134
      if (!Tok.is(tok::identifier)) {
610
1
        Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
611
1
        break;
612
1
      }
613
133
614
133
      if (Kind == AK_Invalid) {
615
        // Just drop invalid accessors.
616
132
      } else if (AccessorNames[Kind] != nullptr) {
617
        // Complain about the repeated accessor, ignore it, and keep parsing.
618
1
        Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
619
131
      } else {
620
131
        AccessorNames[Kind] = Tok.getIdentifierInfo();
621
131
      }
622
133
      ConsumeToken();
623
133
624
134
    next_property_accessor:
625
      // Keep processing accessors until we run out.
626
134
      if (TryConsumeToken(tok::comma))
627
37
        continue;
628
97
629
      // If we run into the ')', stop without consuming it.
630
97
      if (Tok.is(tok::r_paren))
631
96
        break;
632
1
633
1
      Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
634
1
      break;
635
1
    }
636
103
637
    // Only add the property attribute if it was well-formed.
638
103
    if (!HasInvalidAccessor)
639
101
      Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
640
101
                               AccessorNames[AK_Get], AccessorNames[AK_Put],
641
101
                               ParsedAttr::AS_Declspec);
642
103
    T.skipToEnd();
643
103
    return !HasInvalidAccessor;
644
463
  }
645
463
646
463
  unsigned NumArgs =
647
463
      ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
648
463
                               SourceLocation(), ParsedAttr::AS_Declspec);
649
463
650
  // If this attribute's args were parsed, and it was expected to have
651
  // arguments but none were provided, emit a diagnostic.
652
463
  if (!Attrs.empty() && 
Attrs.begin()->getMaxArgs()461
&&
!NumArgs460
) {
653
1
    Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
654
1
    return false;
655
1
  }
656
462
  return true;
657
462
}
658
659
/// [MS] decl-specifier:
660
///             __declspec ( extended-decl-modifier-seq )
661
///
662
/// [MS] extended-decl-modifier-seq:
663
///             extended-decl-modifier[opt]
664
///             extended-decl-modifier extended-decl-modifier-seq
665
void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
666
7.93k
                                     SourceLocation *End) {
667
7.93k
  assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
668
7.93k
  assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
669
7.93k
670
15.9k
  while (Tok.is(tok::kw___declspec)) {
671
8.05k
    ConsumeToken();
672
8.05k
    BalancedDelimiterTracker T(*this, tok::l_paren);
673
8.05k
    if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
674
8.05k
                           tok::r_paren))
675
0
      return;
676
8.05k
677
    // An empty declspec is perfectly legal and should not warn.  Additionally,
678
    // you can specify multiple attributes per declspec.
679
16.1k
    
while (8.05k
Tok.isNot(tok::r_paren)) {
680
      // Attribute not present.
681
8.06k
      if (TryConsumeToken(tok::comma))
682
3
        continue;
683
8.05k
684
      // We expect either a well-known identifier or a generic string.  Anything
685
      // else is a malformed declspec.
686
8.05k
      bool IsString = Tok.getKind() == tok::string_literal;
687
8.05k
      if (!IsString && 
Tok.getKind() != tok::identifier8.05k
&&
688
2
          Tok.getKind() != tok::kw_restrict) {
689
1
        Diag(Tok, diag::err_ms_declspec_type);
690
1
        T.skipToEnd();
691
1
        return;
692
1
      }
693
8.05k
694
8.05k
      IdentifierInfo *AttrName;
695
8.05k
      SourceLocation AttrNameLoc;
696
8.05k
      if (IsString) {
697
2
        SmallString<8> StrBuffer;
698
2
        bool Invalid = false;
699
2
        StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
700
2
        if (Invalid) {
701
0
          T.skipToEnd();
702
0
          return;
703
0
        }
704
2
        AttrName = PP.getIdentifierInfo(Str);
705
2
        AttrNameLoc = ConsumeStringToken();
706
8.05k
      } else {
707
8.05k
        AttrName = Tok.getIdentifierInfo();
708
8.05k
        AttrNameLoc = ConsumeToken();
709
8.05k
      }
710
8.05k
711
8.05k
      bool AttrHandled = false;
712
8.05k
713
      // Parse attribute arguments.
714
8.05k
      if (Tok.is(tok::l_paren))
715
567
        AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
716
7.48k
      else if (AttrName->getName() == "property")
717
        // The property attribute must have an argument list.
718
1
        Diag(Tok.getLocation(), diag::err_expected_lparen_after)
719
1
            << AttrName->getName();
720
8.05k
721
8.05k
      if (!AttrHandled)
722
7.49k
        Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
723
7.49k
                     ParsedAttr::AS_Declspec);
724
8.05k
    }
725
8.05k
    T.consumeClose();
726
8.05k
    if (End)
727
13
      *End = T.getCloseLocation();
728
8.05k
  }
729
7.93k
}
730
731
393k
void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
732
  // Treat these like attributes
733
394k
  while (true) {
734
394k
    switch (Tok.getKind()) {
735
945
    case tok::kw___fastcall:
736
945
    case tok::kw___stdcall:
737
945
    case tok::kw___thiscall:
738
945
    case tok::kw___regcall:
739
945
    case tok::kw___cdecl:
740
945
    case tok::kw___vectorcall:
741
945
    case tok::kw___ptr64:
742
945
    case tok::kw___w64:
743
945
    case tok::kw___ptr32:
744
945
    case tok::kw___sptr:
745
945
    case tok::kw___uptr: {
746
945
      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
747
945
      SourceLocation AttrNameLoc = ConsumeToken();
748
945
      attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
749
945
                   ParsedAttr::AS_Keyword);
750
945
      break;
751
945
    }
752
393k
    default:
753
393k
      return;
754
394k
    }
755
394k
  }
756
393k
}
757
758
294
void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
759
294
  SourceLocation StartLoc = Tok.getLocation();
760
294
  SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
761
294
762
294
  if (EndLoc.isValid()) {
763
12
    SourceRange Range(StartLoc, EndLoc);
764
12
    Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
765
12
  }
766
294
}
767
768
294
SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
769
294
  SourceLocation EndLoc;
770
294
771
320
  while (true) {
772
320
    switch (Tok.getKind()) {
773
26
    case tok::kw_const:
774
26
    case tok::kw_volatile:
775
26
    case tok::kw___fastcall:
776
26
    case tok::kw___stdcall:
777
26
    case tok::kw___thiscall:
778
26
    case tok::kw___cdecl:
779
26
    case tok::kw___vectorcall:
780
26
    case tok::kw___ptr32:
781
26
    case tok::kw___ptr64:
782
26
    case tok::kw___w64:
783
26
    case tok::kw___unaligned:
784
26
    case tok::kw___sptr:
785
26
    case tok::kw___uptr:
786
26
      EndLoc = ConsumeToken();
787
26
      break;
788
294
    default:
789
294
      return EndLoc;
790
320
    }
791
320
  }
792
294
}
793
794
18
void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
795
  // Treat these like attributes
796
36
  while (Tok.is(tok::kw___pascal)) {
797
18
    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
798
18
    SourceLocation AttrNameLoc = ConsumeToken();
799
18
    attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
800
18
                 ParsedAttr::AS_Keyword);
801
18
  }
802
18
}
803
804
834
void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
805
  // Treat these like attributes
806
1.66k
  while (Tok.is(tok::kw___kernel)) {
807
834
    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
808
834
    SourceLocation AttrNameLoc = ConsumeToken();
809
834
    attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
810
834
                 ParsedAttr::AS_Keyword);
811
834
  }
812
834
}
813
814
42.0k
void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
815
42.0k
  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
816
42.0k
  SourceLocation AttrNameLoc = Tok.getLocation();
817
42.0k
  Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
818
42.0k
               ParsedAttr::AS_Keyword);
819
42.0k
}
820
821
856k
void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
822
  // Treat these like attributes, even though they're type specifiers.
823
1.71M
  while (true) {
824
1.71M
    switch (Tok.getKind()) {
825
856k
    case tok::kw__Nonnull:
826
856k
    case tok::kw__Nullable:
827
856k
    case tok::kw__Null_unspecified: {
828
856k
      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
829
856k
      SourceLocation AttrNameLoc = ConsumeToken();
830
856k
      if (!getLangOpts().ObjC)
831
50.0k
        Diag(AttrNameLoc, diag::ext_nullability)
832
50.0k
          << AttrName;
833
856k
      attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
834
856k
                   ParsedAttr::AS_Keyword);
835
856k
      break;
836
856k
    }
837
856k
    default:
838
856k
      return;
839
1.71M
    }
840
1.71M
  }
841
856k
}
842
843
7.45M
static bool VersionNumberSeparator(const char Separator) {
844
7.45M
  return (Separator == '.' || 
Separator == '_'119k
);
845
7.45M
}
846
847
/// Parse a version number.
848
///
849
/// version:
850
///   simple-integer
851
///   simple-integer '.' simple-integer
852
///   simple-integer '_' simple-integer
853
///   simple-integer '.' simple-integer '.' simple-integer
854
///   simple-integer '_' simple-integer '_' simple-integer
855
7.44M
VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
856
7.44M
  Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
857
7.44M
858
7.44M
  if (!Tok.is(tok::numeric_constant)) {
859
1
    Diag(Tok, diag::err_expected_version);
860
1
    SkipUntil(tok::comma, tok::r_paren,
861
1
              StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
862
1
    return VersionTuple();
863
1
  }
864
7.44M
865
  // Parse the major (and possibly minor and subminor) versions, which
866
  // are stored in the numeric constant. We utilize a quirk of the
867
  // lexer, which is that it handles something like 1.2.3 as a single
868
  // numeric constant, rather than two separate tokens.
869
7.44M
  SmallString<512> Buffer;
870
7.44M
  Buffer.resize(Tok.getLength()+1);
871
7.44M
  const char *ThisTokBegin = &Buffer[0];
872
7.44M
873
  // Get the spelling of the token, which eliminates trigraphs, etc.
874
7.44M
  bool Invalid = false;
875
7.44M
  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
876
7.44M
  if (Invalid)
877
0
    return VersionTuple();
878
7.44M
879
  // Parse the major version.
880
7.44M
  unsigned AfterMajor = 0;
881
7.44M
  unsigned Major = 0;
882
19.6M
  while (AfterMajor < ActualLength && 
isDigit(ThisTokBegin[AfterMajor])19.5M
) {
883
12.1M
    Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
884
12.1M
    ++AfterMajor;
885
12.1M
  }
886
7.44M
887
7.44M
  if (AfterMajor == 0) {
888
0
    Diag(Tok, diag::err_expected_version);
889
0
    SkipUntil(tok::comma, tok::r_paren,
890
0
              StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
891
0
    return VersionTuple();
892
0
  }
893
7.44M
894
7.44M
  if (AfterMajor == ActualLength) {
895
49.4k
    ConsumeToken();
896
49.4k
897
    // We only had a single version component.
898
49.4k
    if (Major == 0) {
899
0
      Diag(Tok, diag::err_zero_version);
900
0
      return VersionTuple();
901
0
    }
902
49.4k
903
49.4k
    return VersionTuple(Major);
904
49.4k
  }
905
7.39M
906
7.39M
  const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
907
7.39M
  if (!VersionNumberSeparator(AfterMajorSeparator)
908
7.39M
      || (AfterMajor + 1 == ActualLength)) {
909
0
    Diag(Tok, diag::err_expected_version);
910
0
    SkipUntil(tok::comma, tok::r_paren,
911
0
              StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
912
0
    return VersionTuple();
913
0
  }
914
7.39M
915
  // Parse the minor version.
916
7.39M
  unsigned AfterMinor = AfterMajor + 1;
917
7.39M
  unsigned Minor = 0;
918
15.4M
  while (AfterMinor < ActualLength && 
isDigit(ThisTokBegin[AfterMinor])8.11M
) {
919
8.04M
    Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
920
8.04M
    ++AfterMinor;
921
8.04M
  }
922
7.39M
923
7.39M
  if (AfterMinor == ActualLength) {
924
7.32M
    ConsumeToken();
925
7.32M
926
    // We had major.minor.
927
7.32M
    if (Major == 0 && 
Minor == 00
) {
928
0
      Diag(Tok, diag::err_zero_version);
929
0
      return VersionTuple();
930
0
    }
931
7.32M
932
7.32M
    return VersionTuple(Major, Minor);
933
7.32M
  }
934
67.8k
935
67.8k
  const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
936
  // If what follows is not a '.' or '_', we have a problem.
937
67.8k
  if (!VersionNumberSeparator(AfterMinorSeparator)) {
938
0
    Diag(Tok, diag::err_expected_version);
939
0
    SkipUntil(tok::comma, tok::r_paren,
940
0
              StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
941
0
    return VersionTuple();
942
0
  }
943
67.8k
944
  // Warn if separators, be it '.' or '_', do not match.
945
67.8k
  if (AfterMajorSeparator != AfterMinorSeparator)
946
6
    Diag(Tok, diag::warn_expected_consistent_version_separator);
947
67.8k
948
  // Parse the subminor version.
949
67.8k
  unsigned AfterSubminor = AfterMinor + 1;
950
67.8k
  unsigned Subminor = 0;
951
135k
  while (AfterSubminor < ActualLength && 
isDigit(ThisTokBegin[AfterSubminor])67.8k
) {
952
67.8k
    Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
953
67.8k
    ++AfterSubminor;
954
67.8k
  }
955
67.8k
956
67.8k
  if (AfterSubminor != ActualLength) {
957
0
    Diag(Tok, diag::err_expected_version);
958
0
    SkipUntil(tok::comma, tok::r_paren,
959
0
              StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
960
0
    return VersionTuple();
961
0
  }
962
67.8k
  ConsumeToken();
963
67.8k
  return VersionTuple(Major, Minor, Subminor);
964
67.8k
}
965
966
/// Parse the contents of the "availability" attribute.
967
///
968
/// availability-attribute:
969
///   'availability' '(' platform ',' opt-strict version-arg-list,
970
///                      opt-replacement, opt-message')'
971
///
972
/// platform:
973
///   identifier
974
///
975
/// opt-strict:
976
///   'strict' ','
977
///
978
/// version-arg-list:
979
///   version-arg
980
///   version-arg ',' version-arg-list
981
///
982
/// version-arg:
983
///   'introduced' '=' version
984
///   'deprecated' '=' version
985
///   'obsoleted' = version
986
///   'unavailable'
987
/// opt-replacement:
988
///   'replacement' '=' <string>
989
/// opt-message:
990
///   'message' '=' <string>
991
void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
992
                                        SourceLocation AvailabilityLoc,
993
                                        ParsedAttributes &attrs,
994
                                        SourceLocation *endLoc,
995
                                        IdentifierInfo *ScopeName,
996
                                        SourceLocation ScopeLoc,
997
7.71M
                                        ParsedAttr::Syntax Syntax) {
998
7.71M
  enum { Introduced, Deprecated, Obsoleted, Unknown };
999
7.71M
  AvailabilityChange Changes[Unknown];
1000
7.71M
  ExprResult MessageExpr, ReplacementExpr;
1001
7.71M
1002
  // Opening '('.
1003
7.71M
  BalancedDelimiterTracker T(*this, tok::l_paren);
1004
7.71M
  if (T.consumeOpen()) {
1005
0
    Diag(Tok, diag::err_expected) << tok::l_paren;
1006
0
    return;
1007
0
  }
1008
7.71M
1009
  // Parse the platform name.
1010
7.71M
  if (Tok.isNot(tok::identifier)) {
1011
0
    Diag(Tok, diag::err_availability_expected_platform);
1012
0
    SkipUntil(tok::r_paren, StopAtSemi);
1013
0
    return;
1014
0
  }
1015
7.71M
  IdentifierLoc *Platform = ParseIdentifierLoc();
1016
7.71M
  if (const IdentifierInfo *const Ident = Platform->Ident) {
1017
    // Canonicalize platform name from "macosx" to "macos".
1018
7.71M
    if (Ident->getName() == "macosx")
1019
1.19M
      Platform->Ident = PP.getIdentifierInfo("macos");
1020
    // Canonicalize platform name from "macosx_app_extension" to
1021
    // "macos_app_extension".
1022
6.51M
    else if (Ident->getName() == "macosx_app_extension")
1023
4
      Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1024
6.51M
    else
1025
6.51M
      Platform->Ident = PP.getIdentifierInfo(
1026
6.51M
          AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1027
7.71M
  }
1028
7.71M
1029
  // Parse the ',' following the platform name.
1030
7.71M
  if (ExpectAndConsume(tok::comma)) {
1031
0
    SkipUntil(tok::r_paren, StopAtSemi);
1032
0
    return;
1033
0
  }
1034
7.71M
1035
  // If we haven't grabbed the pointers for the identifiers
1036
  // "introduced", "deprecated", and "obsoleted", do so now.
1037
7.71M
  if (!Ident_introduced) {
1038
1.83k
    Ident_introduced = PP.getIdentifierInfo("introduced");
1039
1.83k
    Ident_deprecated = PP.getIdentifierInfo("deprecated");
1040
1.83k
    Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
1041
1.83k
    Ident_unavailable = PP.getIdentifierInfo("unavailable");
1042
1.83k
    Ident_message = PP.getIdentifierInfo("message");
1043
1.83k
    Ident_strict = PP.getIdentifierInfo("strict");
1044
1.83k
    Ident_replacement = PP.getIdentifierInfo("replacement");
1045
1.83k
  }
1046
7.71M
1047
  // Parse the optional "strict", the optional "replacement" and the set of
1048
  // introductions/deprecations/removals.
1049
7.71M
  SourceLocation UnavailableLoc, StrictLoc;
1050
9.80M
  do {
1051
9.80M
    if (Tok.isNot(tok::identifier)) {
1052
0
      Diag(Tok, diag::err_availability_expected_change);
1053
0
      SkipUntil(tok::r_paren, StopAtSemi);
1054
0
      return;
1055
0
    }
1056
9.80M
    IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1057
9.80M
    SourceLocation KeywordLoc = ConsumeToken();
1058
9.80M
1059
9.80M
    if (Keyword == Ident_strict) {
1060
14.2k
      if (StrictLoc.isValid()) {
1061
0
        Diag(KeywordLoc, diag::err_availability_redundant)
1062
0
          << Keyword << SourceRange(StrictLoc);
1063
0
      }
1064
14.2k
      StrictLoc = KeywordLoc;
1065
14.2k
      continue;
1066
14.2k
    }
1067
9.78M
1068
9.78M
    if (Keyword == Ident_unavailable) {
1069
1.55M
      if (UnavailableLoc.isValid()) {
1070
1
        Diag(KeywordLoc, diag::err_availability_redundant)
1071
1
          << Keyword << SourceRange(UnavailableLoc);
1072
1
      }
1073
1.55M
      UnavailableLoc = KeywordLoc;
1074
1.55M
      continue;
1075
1.55M
    }
1076
8.23M
1077
8.23M
    if (Keyword == Ident_deprecated && 
Platform->Ident1.35M
&&
1078
1.35M
        Platform->Ident->isStr("swift")) {
1079
      // For swift, we deprecate for all versions.
1080
3
      if (Changes[Deprecated].KeywordLoc.isValid()) {
1081
0
        Diag(KeywordLoc, diag::err_availability_redundant)
1082
0
          << Keyword
1083
0
          << SourceRange(Changes[Deprecated].KeywordLoc);
1084
0
      }
1085
3
1086
3
      Changes[Deprecated].KeywordLoc = KeywordLoc;
1087
      // Use a fake version here.
1088
3
      Changes[Deprecated].Version = VersionTuple(1);
1089
3
      continue;
1090
3
    }
1091
8.23M
1092
8.23M
    if (Tok.isNot(tok::equal)) {
1093
1
      Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1094
1
      SkipUntil(tok::r_paren, StopAtSemi);
1095
1
      return;
1096
1
    }
1097
8.23M
    ConsumeToken();
1098
8.23M
    if (Keyword == Ident_message || 
Keyword == Ident_replacement7.55M
) {
1099
785k
      if (Tok.isNot(tok::string_literal)) {
1100
2
        Diag(Tok, diag::err_expected_string_literal)
1101
2
          << /*Source='availability attribute'*/2;
1102
2
        SkipUntil(tok::r_paren, StopAtSemi);
1103
2
        return;
1104
2
      }
1105
785k
      if (Keyword == Ident_message)
1106
678k
        MessageExpr = ParseStringLiteralExpression();
1107
106k
      else
1108
106k
        ReplacementExpr = ParseStringLiteralExpression();
1109
      // Also reject wide string literals.
1110
785k
      if (StringLiteral *MessageStringLiteral =
1111
678k
              cast_or_null<StringLiteral>(MessageExpr.get())) {
1112
678k
        if (MessageStringLiteral->getCharByteWidth() != 1) {
1113
1
          Diag(MessageStringLiteral->getSourceRange().getBegin(),
1114
1
               diag::err_expected_string_literal)
1115
1
            << /*Source='availability attribute'*/ 2;
1116
1
          SkipUntil(tok::r_paren, StopAtSemi);
1117
1
          return;
1118
1
        }
1119
785k
      }
1120
785k
      if (Keyword == Ident_message)
1121
678k
        break;
1122
106k
      else
1123
106k
        continue;
1124
7.44M
    }
1125
7.44M
1126
    // Special handling of 'NA' only when applied to introduced or
1127
    // deprecated.
1128
7.44M
    if ((Keyword == Ident_introduced || 
Keyword == Ident_deprecated1.35M
) &&
1129
7.44M
        Tok.is(tok::identifier)) {
1130
8.21k
      IdentifierInfo *NA = Tok.getIdentifierInfo();
1131
8.21k
      if (NA->getName() == "NA") {
1132
8.21k
        ConsumeToken();
1133
8.21k
        if (Keyword == Ident_introduced)
1134
8.21k
          UnavailableLoc = KeywordLoc;
1135
8.21k
        continue;
1136
8.21k
      }
1137
7.44M
    }
1138
7.44M
1139
7.44M
    SourceRange VersionRange;
1140
7.44M
    VersionTuple Version = ParseVersionTuple(VersionRange);
1141
7.44M
1142
7.44M
    if (Version.empty()) {
1143
0
      SkipUntil(tok::r_paren, StopAtSemi);
1144
0
      return;
1145
0
    }
1146
7.44M
1147
7.44M
    unsigned Index;
1148
7.44M
    if (Keyword == Ident_introduced)
1149
6.08M
      Index = Introduced;
1150
1.35M
    else if (Keyword == Ident_deprecated)
1151
1.35M
      Index = Deprecated;
1152
30
    else if (Keyword == Ident_obsoleted)
1153
29
      Index = Obsoleted;
1154
1
    else
1155
1
      Index = Unknown;
1156
7.44M
1157
7.44M
    if (Index < Unknown) {
1158
7.44M
      if (!Changes[Index].KeywordLoc.isInvalid()) {
1159
1
        Diag(KeywordLoc, diag::err_availability_redundant)
1160
1
          << Keyword
1161
1
          << SourceRange(Changes[Index].KeywordLoc,
1162
1
                         Changes[Index].VersionRange.getEnd());
1163
1
      }
1164
7.44M
1165
7.44M
      Changes[Index].KeywordLoc = KeywordLoc;
1166
7.44M
      Changes[Index].Version = Version;
1167
7.44M
      Changes[Index].VersionRange = VersionRange;
1168
1
    } else {
1169
1
      Diag(KeywordLoc, diag::err_availability_unknown_change)
1170
1
        << Keyword << VersionRange;
1171
1
    }
1172
7.44M
1173
9.12M
  } while (TryConsumeToken(tok::comma));
1174
7.71M
1175
  // Closing ')'.
1176
7.71M
  if (T.consumeClose())
1177
1
    return;
1178
7.71M
1179
7.71M
  if (endLoc)
1180
5.57M
    *endLoc = T.getCloseLocation();
1181
7.71M
1182
  // The 'unavailable' availability cannot be combined with any other
1183
  // availability changes. Make sure that hasn't happened.
1184
7.71M
  if (UnavailableLoc.isValid()) {
1185
1.56M
    bool Complained = false;
1186
6.25M
    for (unsigned Index = Introduced; Index != Unknown; 
++Index4.69M
) {
1187
4.69M
      if (Changes[Index].KeywordLoc.isValid()) {
1188
1
        if (!Complained) {
1189
1
          Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1190
1
            << SourceRange(Changes[Index].KeywordLoc,
1191
1
                           Changes[Index].VersionRange.getEnd());
1192
1
          Complained = true;
1193
1
        }
1194
1
1195
        // Clear out the availability.
1196
1
        Changes[Index] = AvailabilityChange();
1197
1
      }
1198
4.69M
    }
1199
1.56M
  }
1200
7.71M
1201
  // Record this attribute
1202
7.71M
  attrs.addNew(&Availability,
1203
7.71M
               SourceRange(AvailabilityLoc, T.getCloseLocation()),
1204
7.71M
               ScopeName, ScopeLoc,
1205
7.71M
               Platform,
1206
7.71M
               Changes[Introduced],
1207
7.71M
               Changes[Deprecated],
1208
7.71M
               Changes[Obsoleted],
1209
7.71M
               UnavailableLoc, MessageExpr.get(),
1210
7.71M
               Syntax, StrictLoc, ReplacementExpr.get());
1211
7.71M
}
1212
1213
/// Parse the contents of the "external_source_symbol" attribute.
1214
///
1215
/// external-source-symbol-attribute:
1216
///   'external_source_symbol' '(' keyword-arg-list ')'
1217
///
1218
/// keyword-arg-list:
1219
///   keyword-arg
1220
///   keyword-arg ',' keyword-arg-list
1221
///
1222
/// keyword-arg:
1223
///   'language' '=' <string>
1224
///   'defined_in' '=' <string>
1225
///   'generated_declaration'
1226
void Parser::ParseExternalSourceSymbolAttribute(
1227
    IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1228
    ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1229
80
    SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1230
  // Opening '('.
1231
80
  BalancedDelimiterTracker T(*this, tok::l_paren);
1232
80
  if (T.expectAndConsume())
1233
0
    return;
1234
80
1235
  // Initialize the pointers for the keyword identifiers when required.
1236
80
  if (!Ident_language) {
1237
24
    Ident_language = PP.getIdentifierInfo("language");
1238
24
    Ident_defined_in = PP.getIdentifierInfo("defined_in");
1239
24
    Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1240
24
  }
1241
80
1242
80
  ExprResult Language;
1243
80
  bool HasLanguage = false;
1244
80
  ExprResult DefinedInExpr;
1245
80
  bool HasDefinedIn = false;
1246
80
  IdentifierLoc *GeneratedDeclaration = nullptr;
1247
80
1248
  // Parse the language/defined_in/generated_declaration keywords
1249
177
  do {
1250
177
    if (Tok.isNot(tok::identifier)) {
1251
5
      Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1252
5
      SkipUntil(tok::r_paren, StopAtSemi);
1253
5
      return;
1254
5
    }
1255
172
1256
172
    SourceLocation KeywordLoc = Tok.getLocation();
1257
172
    IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1258
172
    if (Keyword == Ident_generated_declaration) {
1259
41
      if (GeneratedDeclaration) {
1260
4
        Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1261
4
        SkipUntil(tok::r_paren, StopAtSemi);
1262
4
        return;
1263
4
      }
1264
37
      GeneratedDeclaration = ParseIdentifierLoc();
1265
37
      continue;
1266
37
    }
1267
131
1268
131
    if (Keyword != Ident_language && 
Keyword != Ident_defined_in64
) {
1269
2
      Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1270
2
      SkipUntil(tok::r_paren, StopAtSemi);
1271
2
      return;
1272
2
    }
1273
129
1274
129
    ConsumeToken();
1275
129
    if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1276
1
                         Keyword->getName())) {
1277
1
      SkipUntil(tok::r_paren, StopAtSemi);
1278
1
      return;
1279
1
    }
1280
128
1281
128
    bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1282
128
    if (Keyword == Ident_language)
1283
66
      HasLanguage = true;
1284
62
    else
1285
62
      HasDefinedIn = true;
1286
128
1287
128
    if (Tok.isNot(tok::string_literal)) {
1288
9
      Diag(Tok, diag::err_expected_string_literal)
1289
9
          << /*Source='external_source_symbol attribute'*/ 3
1290
9
          << /*language | source container*/ (Keyword != Ident_language);
1291
9
      SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1292
9
      continue;
1293
9
    }
1294
119
    if (Keyword == Ident_language) {
1295
61
      if (HadLanguage) {
1296
2
        Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1297
2
            << Keyword;
1298
2
        ParseStringLiteralExpression();
1299
2
        continue;
1300
2
      }
1301
59
      Language = ParseStringLiteralExpression();
1302
58
    } else {
1303
58
      assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1304
58
      if (HadDefinedIn) {
1305
2
        Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1306
2
            << Keyword;
1307
2
        ParseStringLiteralExpression();
1308
2
        continue;
1309
2
      }
1310
56
      DefinedInExpr = ParseStringLiteralExpression();
1311
56
    }
1312
165
  } while (TryConsumeToken(tok::comma));
1313
80
1314
  // Closing ')'.
1315
68
  if (T.consumeClose())
1316
3
    return;
1317
65
  if (EndLoc)
1318
30
    *EndLoc = T.getCloseLocation();
1319
65
1320
65
  ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1321
65
                      GeneratedDeclaration};
1322
65
  Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1323
65
               ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1324
65
}
1325
1326
/// Parse the contents of the "objc_bridge_related" attribute.
1327
/// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1328
/// related_class:
1329
///     Identifier
1330
///
1331
/// opt-class_method:
1332
///     Identifier: | <empty>
1333
///
1334
/// opt-instance_method:
1335
///     Identifier | <empty>
1336
///
1337
void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1338
                                SourceLocation ObjCBridgeRelatedLoc,
1339
                                ParsedAttributes &attrs,
1340
                                SourceLocation *endLoc,
1341
                                IdentifierInfo *ScopeName,
1342
                                SourceLocation ScopeLoc,
1343
622
                                ParsedAttr::Syntax Syntax) {
1344
  // Opening '('.
1345
622
  BalancedDelimiterTracker T(*this, tok::l_paren);
1346
622
  if (T.consumeOpen()) {
1347
0
    Diag(Tok, diag::err_expected) << tok::l_paren;
1348
0
    return;
1349
0
  }
1350
622
1351
  // Parse the related class name.
1352
622
  if (Tok.isNot(tok::identifier)) {
1353
4
    Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1354
4
    SkipUntil(tok::r_paren, StopAtSemi);
1355
4
    return;
1356
4
  }
1357
618
  IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1358
618
  if (ExpectAndConsume(tok::comma)) {
1359
0
    SkipUntil(tok::r_paren, StopAtSemi);
1360
0
    return;
1361
0
  }
1362
618
1363
  // Parse class method name.  It's non-optional in the sense that a trailing
1364
  // comma is required, but it can be the empty string, and then we record a
1365
  // nullptr.
1366
618
  IdentifierLoc *ClassMethod = nullptr;
1367
618
  if (Tok.is(tok::identifier)) {
1368
21
    ClassMethod = ParseIdentifierLoc();
1369
21
    if (!TryConsumeToken(tok::colon)) {
1370
2
      Diag(Tok, diag::err_objcbridge_related_selector_name);
1371
2
      SkipUntil(tok::r_paren, StopAtSemi);
1372
2
      return;
1373
2
    }
1374
616
  }
1375
616
  if (!TryConsumeToken(tok::comma)) {
1376
2
    if (Tok.is(tok::colon))
1377
1
      Diag(Tok, diag::err_objcbridge_related_selector_name);
1378
1
    else
1379
1
      Diag(Tok, diag::err_expected) << tok::comma;
1380
2
    SkipUntil(tok::r_paren, StopAtSemi);
1381
2
    return;
1382
2
  }
1383
614
1384
  // Parse instance method name.  Also non-optional but empty string is
1385
  // permitted.
1386
614
  IdentifierLoc *InstanceMethod = nullptr;
1387
614
  if (Tok.is(tok::identifier))
1388
19
    InstanceMethod = ParseIdentifierLoc();
1389
595
  else if (Tok.isNot(tok::r_paren)) {
1390
1
    Diag(Tok, diag::err_expected) << tok::r_paren;
1391
1
    SkipUntil(tok::r_paren, StopAtSemi);
1392
1
    return;
1393
1
  }
1394
613
1395
  // Closing ')'.
1396
613
  if (T.consumeClose())
1397
0
    return;
1398
613
1399
613
  if (endLoc)
1400
2
    *endLoc = T.getCloseLocation();
1401
613
1402
  // Record this attribute
1403
613
  attrs.addNew(&ObjCBridgeRelated,
1404
613
               SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1405
613
               ScopeName, ScopeLoc,
1406
613
               RelatedClass,
1407
613
               ClassMethod,
1408
613
               InstanceMethod,
1409
613
               Syntax);
1410
613
}
1411
1412
void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1413
                                              SourceLocation AttrNameLoc,
1414
                                              ParsedAttributes &Attrs,
1415
                                              SourceLocation *EndLoc,
1416
                                              IdentifierInfo *ScopeName,
1417
                                              SourceLocation ScopeLoc,
1418
188
                                              ParsedAttr::Syntax Syntax) {
1419
188
  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1420
188
1421
188
  BalancedDelimiterTracker T(*this, tok::l_paren);
1422
188
  T.consumeOpen();
1423
188
1424
188
  if (Tok.isNot(tok::identifier)) {
1425
0
    Diag(Tok, diag::err_expected) << tok::identifier;
1426
0
    T.skipToEnd();
1427
0
    return;
1428
0
  }
1429
188
  IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1430
188
1431
188
  if (ExpectAndConsume(tok::comma)) {
1432
0
    T.skipToEnd();
1433
0
    return;
1434
0
  }
1435
188
1436
188
  SourceRange MatchingCTypeRange;
1437
188
  TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1438
188
  if (MatchingCType.isInvalid()) {
1439
8
    T.skipToEnd();
1440
8
    return;
1441
8
  }
1442
180
1443
180
  bool LayoutCompatible = false;
1444
180
  bool MustBeNull = false;
1445
233
  while (TryConsumeToken(tok::comma)) {
1446
65
    if (Tok.isNot(tok::identifier)) {
1447
4
      Diag(Tok, diag::err_expected) << tok::identifier;
1448
4
      T.skipToEnd();
1449
4
      return;
1450
4
    }
1451
61
    IdentifierInfo *Flag = Tok.getIdentifierInfo();
1452
61
    if (Flag->isStr("layout_compatible"))
1453
46
      LayoutCompatible = true;
1454
15
    else if (Flag->isStr("must_be_null"))
1455
7
      MustBeNull = true;
1456
8
    else {
1457
8
      Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1458
8
      T.skipToEnd();
1459
8
      return;
1460
8
    }
1461
53
    ConsumeToken(); // consume flag
1462
53
  }
1463
180
1464
168
  if (!T.consumeClose()) {
1465
168
    Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1466
168
                                   ArgumentKind, MatchingCType.get(),
1467
168
                                   LayoutCompatible, MustBeNull, Syntax);
1468
168
  }
1469
168
1470
168
  if (EndLoc)
1471
168
    *EndLoc = T.getCloseLocation();
1472
168
}
1473
1474
/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1475
/// of a C++11 attribute-specifier in a location where an attribute is not
1476
/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1477
/// situation.
1478
///
1479
/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1480
/// this doesn't appear to actually be an attribute-specifier, and the caller
1481
/// should try to parse it.
1482
12
bool Parser::DiagnoseProhibitedCXX11Attribute() {
1483
12
  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1484
12
1485
12
  switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1486
4
  case CAK_NotAttributeSpecifier:
1487
    // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1488
4
    return false;
1489
0
1490
4
  case CAK_InvalidAttributeSpecifier:
1491
4
    Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1492
4
    return false;
1493
0
1494
4
  case CAK_AttributeSpecifier:
1495
    // Parse and discard the attributes.
1496
4
    SourceLocation BeginLoc = ConsumeBracket();
1497
4
    ConsumeBracket();
1498
4
    SkipUntil(tok::r_square);
1499
4
    assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1500
4
    SourceLocation EndLoc = ConsumeBracket();
1501
4
    Diag(BeginLoc, diag::err_attributes_not_allowed)
1502
4
      << SourceRange(BeginLoc, EndLoc);
1503
4
    return true;
1504
0
  }
1505
0
  llvm_unreachable("All cases handled above.");
1506
0
}
1507
1508
/// We have found the opening square brackets of a C++11
1509
/// attribute-specifier in a location where an attribute is not permitted, but
1510
/// we know where the attributes ought to be written. Parse them anyway, and
1511
/// provide a fixit moving them to the right place.
1512
void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1513
24
                                             SourceLocation CorrectLocation) {
1514
24
  assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1515
24
         Tok.is(tok::kw_alignas));
1516
24
1517
  // Consume the attributes.
1518
24
  SourceLocation Loc = Tok.getLocation();
1519
24
  ParseCXX11Attributes(Attrs);
1520
24
  CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1521
  // FIXME: use err_attributes_misplaced
1522
24
  Diag(Loc, diag::err_attributes_not_allowed)
1523
24
    << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1524
24
    << FixItHint::CreateRemoval(AttrRange);
1525
24
}
1526
1527
void Parser::DiagnoseProhibitedAttributes(
1528
120
    const SourceRange &Range, const SourceLocation CorrectLocation) {
1529
120
  if (CorrectLocation.isValid()) {
1530
13
    CharSourceRange AttrRange(Range, true);
1531
13
    Diag(CorrectLocation, diag::err_attributes_misplaced)
1532
13
        << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1533
13
        << FixItHint::CreateRemoval(AttrRange);
1534
13
  } else
1535
107
    Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
1536
120
}
1537
1538
void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1539
1.64k
                                     unsigned DiagID) {
1540
28
  for (const ParsedAttr &AL : Attrs) {
1541
28
    if (!AL.isCXX11Attribute() && 
!AL.isC2xAttribute()1
)
1542
0
      continue;
1543
28
    if (AL.getKind() == ParsedAttr::UnknownAttribute)
1544
7
      Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL;
1545
21
    else {
1546
21
      Diag(AL.getLoc(), DiagID) << AL;
1547
21
      AL.setInvalid();
1548
21
    }
1549
28
  }
1550
1.64k
}
1551
1552
// Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1553
// applies to var, not the type Foo.
1554
// As an exception to the rule, __declspec(align(...)) before the
1555
// class-key affects the type instead of the variable.
1556
// Also, Microsoft-style [attributes] seem to affect the type instead of the
1557
// variable.
1558
// This function moves attributes that should apply to the type off DS to Attrs.
1559
void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1560
                                            DeclSpec &DS,
1561
2.40M
                                            Sema::TagUseKind TUK) {
1562
2.40M
  if (TUK == Sema::TUK_Reference)
1563
793k
    return;
1564
1.61M
1565
1.61M
  llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
1566
1.61M
1567
242
  for (ParsedAttr &AL : DS.getAttributes()) {
1568
242
    if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1569
47
         AL.isDeclspecAttribute()) ||
1570
234
        AL.isMicrosoftAttribute())
1571
59
      ToBeMoved.push_back(&AL);
1572
242
  }
1573
1.61M
1574
59
  for (ParsedAttr *AL : ToBeMoved) {
1575
59
    DS.getAttributes().remove(AL);
1576
59
    Attrs.addAtEnd(AL);
1577
59
  }
1578
1.61M
}
1579
1580
/// ParseDeclaration - Parse a full 'declaration', which consists of
1581
/// declaration-specifiers, some number of declarators, and a semicolon.
1582
/// 'Context' should be a DeclaratorContext value.  This returns the
1583
/// location of the semicolon in DeclEnd.
1584
///
1585
///       declaration: [C99 6.7]
1586
///         block-declaration ->
1587
///           simple-declaration
1588
///           others                   [FIXME]
1589
/// [C++]   template-declaration
1590
/// [C++]   namespace-definition
1591
/// [C++]   using-directive
1592
/// [C++]   using-declaration
1593
/// [C++11/C11] static_assert-declaration
1594
///         others... [FIXME]
1595
///
1596
Parser::DeclGroupPtrTy
1597
Parser::ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
1598
                         ParsedAttributesWithRange &attrs,
1599
4.19M
                         SourceLocation *DeclSpecStart) {
1600
4.19M
  ParenBraceBracketBalancer BalancerRAIIObj(*this);
1601
  // Must temporarily exit the objective-c container scope for
1602
  // parsing c none objective-c decls.
1603
4.19M
  ObjCDeclContextSwitch ObjCDC(*this);
1604
4.19M
1605
4.19M
  Decl *SingleDecl = nullptr;
1606
4.19M
  switch (Tok.getKind()) {
1607
929k
  case tok::kw_template:
1608
929k
  case tok::kw_export:
1609
929k
    ProhibitAttributes(attrs);
1610
929k
    SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
1611
929k
    break;
1612
18.0k
  case tok::kw_inline:
1613
    // Could be the start of an inline namespace. Allowed as an ext in C++03.
1614
18.0k
    if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1615
18.0k
      ProhibitAttributes(attrs);
1616
18.0k
      SourceLocation InlineLoc = ConsumeToken();
1617
18.0k
      return ParseNamespace(Context, DeclEnd, InlineLoc);
1618
18.0k
    }
1619
6
    return ParseSimpleDeclaration(Context, DeclEnd, attrs, true, nullptr,
1620
6
                                  DeclSpecStart);
1621
54.0k
  case tok::kw_namespace:
1622
54.0k
    ProhibitAttributes(attrs);
1623
54.0k
    return ParseNamespace(Context, DeclEnd);
1624
133k
  case tok::kw_using:
1625
133k
    return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1626
133k
                                            DeclEnd, attrs);
1627
28.2k
  case tok::kw_static_assert:
1628
28.2k
  case tok::kw__Static_assert:
1629
28.2k
    ProhibitAttributes(attrs);
1630
28.2k
    SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1631
28.2k
    break;
1632
3.02M
  default:
1633
3.02M
    return ParseSimpleDeclaration(Context, DeclEnd, attrs, true, nullptr,
1634
3.02M
                                  DeclSpecStart);
1635
957k
  }
1636
957k
1637
  // This routine returns a DeclGroup, if the thing we parsed only contains a
1638
  // single decl, convert it now.
1639
957k
  return Actions.ConvertDeclToDeclGroup(SingleDecl);
1640
957k
}
1641
1642
///       simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1643
///         declaration-specifiers init-declarator-list[opt] ';'
1644
/// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1645
///             init-declarator-list ';'
1646
///[C90/C++]init-declarator-list ';'                             [TODO]
1647
/// [OMP]   threadprivate-directive
1648
/// [OMP]   allocate-directive                                   [TODO]
1649
///
1650
///       for-range-declaration: [C++11 6.5p1: stmt.ranged]
1651
///         attribute-specifier-seq[opt] type-specifier-seq declarator
1652
///
1653
/// If RequireSemi is false, this does not check for a ';' at the end of the
1654
/// declaration.  If it is true, it checks for and eats it.
1655
///
1656
/// If FRI is non-null, we might be parsing a for-range-declaration instead
1657
/// of a simple-declaration. If we find that we are, we also parse the
1658
/// for-range-initializer, and place it here.
1659
///
1660
/// DeclSpecStart is used when decl-specifiers are parsed before parsing
1661
/// the Declaration. The SourceLocation for this Decl is set to
1662
/// DeclSpecStart if DeclSpecStart is non-null.
1663
Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(
1664
    DeclaratorContext Context, SourceLocation &DeclEnd,
1665
    ParsedAttributesWithRange &Attrs, bool RequireSemi, ForRangeInit *FRI,
1666
3.13M
    SourceLocation *DeclSpecStart) {
1667
  // Parse the common declaration-specifiers piece.
1668
3.13M
  ParsingDeclSpec DS(*this);
1669
3.13M
1670
3.13M
  DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1671
3.13M
  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1672
3.13M
1673
  // If we had a free-standing type definition with a missing semicolon, we
1674
  // may get this far before the problem becomes obvious.
1675
3.13M
  if (DS.hasTagDefinition() &&
1676
355k
      DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1677
0
    return nullptr;
1678
3.13M
1679
  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1680
  // declaration-specifiers init-declarator-list[opt] ';'
1681
3.13M
  if (Tok.is(tok::semi)) {
1682
31.8k
    ProhibitAttributes(Attrs);
1683
31.8k
    DeclEnd = Tok.getLocation();
1684
31.8k
    if (RequireSemi) ConsumeToken();
1685
31.8k
    RecordDecl *AnonRecord = nullptr;
1686
31.8k
    Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1687
31.8k
                                                       DS, AnonRecord);
1688
31.8k
    DS.complete(TheDecl);
1689
31.8k
    if (AnonRecord) {
1690
36
      Decl* decls[] = {AnonRecord, TheDecl};
1691
36
      return Actions.BuildDeclaratorGroup(decls);
1692
36
    }
1693
31.8k
    return Actions.ConvertDeclToDeclGroup(TheDecl);
1694
31.8k
  }
1695
3.10M
1696
3.10M
  if (DeclSpecStart)
1697
2.22k
    DS.SetRangeStart(*DeclSpecStart);
1698
3.10M
1699
3.10M
  DS.takeAttributesFrom(Attrs);
1700
3.10M
  return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1701
3.10M
}
1702
1703
/// Returns true if this might be the start of a declarator, or a common typo
1704
/// for a declarator.
1705
168k
bool Parser::MightBeDeclarator(DeclaratorContext Context) {
1706
168k
  switch (Tok.getKind()) {
1707
18
  case tok::annot_cxxscope:
1708
18
  case tok::annot_template_id:
1709
18
  case tok::caret:
1710
18
  case tok::code_completion:
1711
18
  case tok::coloncolon:
1712
18
  case tok::ellipsis:
1713
18
  case tok::kw___attribute:
1714
18
  case tok::kw_operator:
1715
18
  case tok::l_paren:
1716
18
  case tok::star:
1717
18
    return true;
1718
18
1719
21
  case tok::amp:
1720
21
  case tok::ampamp:
1721
21
    return getLangOpts().CPlusPlus;
1722
21
1723
0
  case tok::l_square: // Might be an attribute on an unnamed bit-field.
1724
0
    return Context == DeclaratorContext::MemberContext &&
1725
0
           getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
1726
21
1727
1.81k
  case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1728
1.81k
    return Context == DeclaratorContext::MemberContext ||
1729
0
           getLangOpts().CPlusPlus;
1730
21
1731
166k
  case tok::identifier:
1732
166k
    switch (NextToken().getKind()) {
1733
151k
    case tok::code_completion:
1734
151k
    case tok::coloncolon:
1735
151k
    case tok::comma:
1736
151k
    case tok::equal:
1737
151k
    case tok::equalequal: // Might be a typo for '='.
1738
151k
    case tok::kw_alignas:
1739
151k
    case tok::kw_asm:
1740
151k
    case tok::kw___attribute:
1741
151k
    case tok::l_brace:
1742
151k
    case tok::l_paren:
1743
151k
    case tok::l_square:
1744
151k
    case tok::less:
1745
151k
    case tok::r_brace:
1746
151k
    case tok::r_paren:
1747
151k
    case tok::r_square:
1748
151k
    case tok::semi:
1749
151k
      return true;
1750
151k
1751
15.2k
    case tok::colon:
1752
      // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1753
      // and in block scope it's probably a label. Inside a class definition,
1754
      // this is a bit-field.
1755
15.2k
      return Context == DeclaratorContext::MemberContext ||
1756
3
             (getLangOpts().CPlusPlus &&
1757
3
              Context == DeclaratorContext::FileContext);
1758
151k
1759
18
    case tok::identifier: // Possible virt-specifier.
1760
18
      return getLangOpts().CPlusPlus11 && 
isCXX11VirtSpecifier(NextToken())14
;
1761
151k
1762
10
    default:
1763
10
      return false;
1764
0
    }
1765
0
1766
56
  default:
1767
56
    return false;
1768
168k
  }
1769
168k
}
1770
1771
/// Skip until we reach something which seems like a sensible place to pick
1772
/// up parsing after a malformed declaration. This will sometimes stop sooner
1773
/// than SkipUntil(tok::r_brace) would, but will never stop later.
1774
448
void Parser::SkipMalformedDecl() {
1775
1.01k
  while (true) {
1776
1.01k
    switch (Tok.getKind()) {
1777
72
    case tok::l_brace:
1778
      // Skip until matching }, then stop. We've probably skipped over
1779
      // a malformed class or function definition or similar.
1780
72
      ConsumeBrace();
1781
72
      SkipUntil(tok::r_brace);
1782
72
      if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1783
        // This declaration isn't over yet. Keep skipping.
1784
4
        continue;
1785
4
      }
1786
68
      TryConsumeToken(tok::semi);
1787
68
      return;
1788
68
1789
0
    case tok::l_square:
1790
0
      ConsumeBracket();
1791
0
      SkipUntil(tok::r_square);
1792
0
      continue;
1793
68
1794
39
    case tok::l_paren:
1795
39
      ConsumeParen();
1796
39
      SkipUntil(tok::r_paren);
1797
39
      continue;
1798
68
1799
9
    case tok::r_brace:
1800
9
      return;
1801
68
1802
240
    case tok::semi:
1803
240
      ConsumeToken();
1804
240
      return;
1805
68
1806
2
    case tok::kw_inline:
1807
      // 'inline namespace' at the start of a line is almost certainly
1808
      // a good place to pick back up parsing, except in an Objective-C
1809
      // @interface context.
1810
2
      if (Tok.isAtStartOfLine() && 
NextToken().is(tok::kw_namespace)1
&&
1811
1
          (!ParsingInObjCContainer || 
CurParsedObjCImpl0
))
1812
1
        return;
1813
1
      break;
1814
1
1815
6
    case tok::kw_namespace:
1816
      // 'namespace' at the start of a line is almost certainly a good
1817
      // place to pick back up parsing, except in an Objective-C
1818
      // @interface context.
1819
6
      if (Tok.isAtStartOfLine() &&
1820
4
          (!ParsingInObjCContainer || 
CurParsedObjCImpl3
))
1821
2
        return;
1822
4
      break;
1823
4
1824
2
    case tok::at:
1825
      // @end is very much like } in Objective-C contexts.
1826
2
      if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1827
2
          ParsingInObjCContainer)
1828
2
        return;
1829
0
      break;
1830
0
1831
15
    case tok::minus:
1832
15
    case tok::plus:
1833
      // - and + probably start new method declarations in Objective-C contexts.
1834
15
      if (Tok.isAtStartOfLine() && 
ParsingInObjCContainer4
)
1835
4
        return;
1836
11
      break;
1837
11
1838
122
    case tok::eof:
1839
122
    case tok::annot_module_begin:
1840
122
    case tok::annot_module_end:
1841
122
    case tok::annot_module_include:
1842
122
      return;
1843
122
1844
512
    default:
1845
512
      break;
1846
528
    }
1847
528
1848
528
    ConsumeAnyToken();
1849
528
  }
1850
448
}
1851
1852
/// ParseDeclGroup - Having concluded that this is either a function
1853
/// definition or a group of object declarations, actually parse the
1854
/// result.
1855
Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1856
                                              DeclaratorContext Context,
1857
                                              SourceLocation *DeclEnd,
1858
16.6M
                                              ForRangeInit *FRI) {
1859
  // Parse the first declarator.
1860
16.6M
  ParsingDeclarator D(*this, DS, Context);
1861
16.6M
  ParseDeclarator(D);
1862
16.6M
1863
  // Bail out if the first declarator didn't seem well-formed.
1864
16.6M
  if (!D.hasName() && 
!D.mayOmitIdentifier()323
) {
1865
323
    SkipMalformedDecl();
1866
323
    return nullptr;
1867
323
  }
1868
16.6M
1869
16.6M
  if (Tok.is(tok::kw_requires))
1870
36
    ParseTrailingRequiresClause(D);
1871
16.6M
1872
  // Save late-parsed attributes for now; they need to be parsed in the
1873
  // appropriate function scope after the function Decl has been constructed.
1874
  // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1875
16.6M
  LateParsedAttrList LateParsedAttrs(true);
1876
16.6M
  if (D.isFunctionDeclarator()) {
1877
12.3M
    MaybeParseGNUAttributes(D, &LateParsedAttrs);
1878
12.3M
1879
    // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1880
    // attribute. If we find the keyword here, tell the user to put it
1881
    // at the start instead.
1882
12.3M
    if (Tok.is(tok::kw__Noreturn)) {
1883
6
      SourceLocation Loc = ConsumeToken();
1884
6
      const char *PrevSpec;
1885
6
      unsigned DiagID;
1886
6
1887
      // We can offer a fixit if it's valid to mark this function as _Noreturn
1888
      // and we don't have any other declarators in this declaration.
1889
6
      bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1890
6
      MaybeParseGNUAttributes(D, &LateParsedAttrs);
1891
6
      Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
1892
6
1893
6
      Diag(Loc, diag::err_c11_noreturn_misplaced)
1894
6
          << (Fixit ? FixItHint::CreateRemoval(Loc) : 
FixItHint()0
)
1895
6
          << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
1896
0
                    : FixItHint());
1897
6
    }
1898
12.3M
  }
1899
16.6M
1900
  // Check to see if we have a function *definition* which must have a body.
1901
16.6M
  if (D.isFunctionDeclarator()) {
1902
12.3M
    if (Tok.is(tok::equal) && 
NextToken().is(tok::code_completion)539
) {
1903
2
      Actions.CodeCompleteAfterFunctionEquals(D);
1904
2
      cutOffParsing();
1905
2
      return nullptr;
1906
2
    }
1907
    // Look at the next token to make sure that this isn't a function
1908
    // declaration.  We have to check this because __attribute__ might be the
1909
    // start of a function definition in GCC-extended K&R C.
1910
12.3M
    if (!isDeclarationAfterDeclarator()) {
1911
2.09M
1912
      // Function definitions are only allowed at file scope and in C++ classes.
1913
      // The C++ inline method definition case is handled elsewhere, so we only
1914
      // need to handle the file scope definition case.
1915
2.09M
      if (Context == DeclaratorContext::FileContext) {
1916
2.09M
        if (isStartOfFunctionDefinition(D)) {
1917
2.09M
          if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1918
9
            Diag(Tok, diag::err_function_declared_typedef);
1919
9
1920
            // Recover by treating the 'typedef' as spurious.
1921
9
            DS.ClearStorageClassSpecs();
1922
9
          }
1923
2.09M
1924
2.09M
          Decl *TheDecl = ParseFunctionDefinition(D, ParsedTemplateInfo(),
1925
2.09M
                                                  &LateParsedAttrs);
1926
2.09M
          return Actions.ConvertDeclToDeclGroup(TheDecl);
1927
2.09M
        }
1928
35
1929
35
        if (isDeclarationSpecifier()) {
1930
          // If there is an invalid declaration specifier right after the
1931
          // function prototype, then we must be in a missing semicolon case
1932
          // where this isn't actually a body.  Just fall through into the code
1933
          // that handles it as a prototype, and let the top-level code handle
1934
          // the erroneous declspec where it would otherwise expect a comma or
1935
          // semicolon.
1936
33
        } else {
1937
33
          Diag(Tok, diag::err_expected_fn_body);
1938
33
          SkipUntil(tok::semi);
1939
33
          return nullptr;
1940
33
        }
1941
11
      } else {
1942
11
        if (Tok.is(tok::l_brace)) {
1943
8
          Diag(Tok, diag::err_function_definition_not_allowed);
1944
8
          SkipMalformedDecl();
1945
8
          return nullptr;
1946
8
        }
1947
14.5M
      }
1948
2.09M
    }
1949
12.3M
  }
1950
14.5M
1951
14.5M
  if (ParseAsmAttributesAfterDeclarator(D))
1952
8
    return nullptr;
1953
14.5M
1954
  // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1955
  // must parse and analyze the for-range-initializer before the declaration is
1956
  // analyzed.
1957
  //
1958
  // Handle the Objective-C for-in loop variable similarly, although we
1959
  // don't need to parse the container in advance.
1960
14.5M
  if (FRI && 
(108k
Tok.is(tok::colon)108k
||
isTokIdentifier_in()107k
)) {
1961
1.29k
    bool IsForRangeLoop = false;
1962
1.29k
    if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
1963
1.26k
      IsForRangeLoop = true;
1964
1.26k
      if (getLangOpts().OpenMP)
1965
118
        Actions.startOpenMPCXXRangeFor();
1966
1.26k
      if (Tok.is(tok::l_brace))
1967
10
        FRI->RangeExpr = ParseBraceInitializer();
1968
1.25k
      else
1969
1.25k
        FRI->RangeExpr = ParseExpression();
1970
1.26k
    }
1971
1.29k
1972
1.29k
    Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1973
1.29k
    if (IsForRangeLoop) {
1974
1.26k
      Actions.ActOnCXXForRangeDecl(ThisDecl);
1975
37
    } else {
1976
      // Obj-C for loop
1977
37
      if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
1978
36
        VD->setObjCForDecl(true);
1979
37
    }
1980
1.29k
    Actions.FinalizeDeclaration(ThisDecl);
1981
1.29k
    D.complete(ThisDecl);
1982
1.29k
    return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
1983
1.29k
  }
1984
14.5M
1985
14.5M
  SmallVector<Decl *, 8> DeclsInGroup;
1986
14.5M
  Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
1987
14.5M
      D, ParsedTemplateInfo(), FRI);
1988
14.5M
  if (LateParsedAttrs.size() > 0)
1989
646
    ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
1990
14.5M
  D.complete(FirstDecl);
1991
14.5M
  if (FirstDecl)
1992
14.5M
    DeclsInGroup.push_back(FirstDecl);
1993
14.5M
1994
14.5M
  bool ExpectSemi = Context != DeclaratorContext::ForContext;
1995
14.5M
1996
  // If we don't have a comma, it is either the end of the list (a ';') or an
1997
  // error, bail out.
1998
14.5M
  SourceLocation CommaLoc;
1999
14.7M
  while (TryConsumeToken(tok::comma, CommaLoc)) {
2000
220k
    if (Tok.isAtStartOfLine() && 
ExpectSemi151k
&&
!MightBeDeclarator(Context)150k
) {
2001
      // This comma was followed by a line-break and something which can't be
2002
      // the start of a declarator. The comma was probably a typo for a
2003
      // semicolon.
2004
40
      Diag(CommaLoc, diag::err_expected_semi_declaration)
2005
40
        << FixItHint::CreateReplacement(CommaLoc, ";");
2006
40
      ExpectSemi = false;
2007
40
      break;
2008
40
    }
2009
220k
2010
    // Parse the next declarator.
2011
220k
    D.clear();
2012
220k
    D.setCommaLoc(CommaLoc);
2013
220k
2014
    // Accept attributes in an init-declarator.  In the first declarator in a
2015
    // declaration, these would be part of the declspec.  In subsequent
2016
    // declarators, they become part of the declarator itself, so that they
2017
    // don't apply to declarators after *this* one.  Examples:
2018
    //    short __attribute__((common)) var;    -> declspec
2019
    //    short var __attribute__((common));    -> declarator
2020
    //    short x, __attribute__((common)) var;    -> declarator
2021
220k
    MaybeParseGNUAttributes(D);
2022
220k
2023
    // MSVC parses but ignores qualifiers after the comma as an extension.
2024
220k
    if (getLangOpts().MicrosoftExt)
2025
294
      DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2026
220k
2027
220k
    ParseDeclarator(D);
2028
220k
    if (!D.isInvalidType()) {
2029
      // C++2a [dcl.decl]p1
2030
      //    init-declarator:
2031
      //        declarator initializer[opt]
2032
      //        declarator requires-clause
2033
220k
      if (Tok.is(tok::kw_requires))
2034
0
        ParseTrailingRequiresClause(D);
2035
220k
      Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2036
220k
      D.complete(ThisDecl);
2037
220k
      if (ThisDecl)
2038
220k
        DeclsInGroup.push_back(ThisDecl);
2039
220k
    }
2040
220k
  }
2041
14.5M
2042
14.5M
  if (DeclEnd)
2043
3.10M
    *DeclEnd = Tok.getLocation();
2044
14.5M
2045
14.5M
  if (ExpectSemi &&
2046
14.4M
      ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
2047
13.2M
                           ? diag::err_invalid_token_after_toplevel_declarator
2048
1.17M
                           : diag::err_expected_semi_declaration)) {
2049
    // Okay, there was no semicolon and one was expected.  If we see a
2050
    // declaration specifier, just assume it was missing and continue parsing.
2051
    // Otherwise things are very confused and we skip to recover.
2052
268
    if (!isDeclarationSpecifier()) {
2053
243
      SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2054
243
      TryConsumeToken(tok::semi);
2055
243
    }
2056
268
  }
2057
14.5M
2058
14.5M
  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2059
14.5M
}
2060
2061
/// Parse an optional simple-asm-expr and attributes, and attach them to a
2062
/// declarator. Returns true on an error.
2063
14.8M
bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2064
  // If a simple-asm-expr is present, parse it.
2065
14.8M
  if (Tok.is(tok::kw_asm)) {
2066
59.0k
    SourceLocation Loc;
2067
59.0k
    ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2068
59.0k
    if (AsmLabel.isInvalid()) {
2069
8
      SkipUntil(tok::semi, StopBeforeMatch);
2070
8
      return true;
2071
8
    }
2072
59.0k
2073
59.0k
    D.setAsmLabel(AsmLabel.get());
2074
59.0k
    D.SetRangeEnd(Loc);
2075
59.0k
  }
2076
14.8M
2077
14.8M
  MaybeParseGNUAttributes(D);
2078
14.8M
  return false;
2079
14.8M
}
2080
2081
/// Parse 'declaration' after parsing 'declaration-specifiers
2082
/// declarator'. This method parses the remainder of the declaration
2083
/// (including any attributes or initializer, among other things) and
2084
/// finalizes the declaration.
2085
///
2086
///       init-declarator: [C99 6.7]
2087
///         declarator
2088
///         declarator '=' initializer
2089
/// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
2090
/// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2091
/// [C++]   declarator initializer[opt]
2092
///
2093
/// [C++] initializer:
2094
/// [C++]   '=' initializer-clause
2095
/// [C++]   '(' expression-list ')'
2096
/// [C++0x] '=' 'default'                                                [TODO]
2097
/// [C++0x] '=' 'delete'
2098
/// [C++0x] braced-init-list
2099
///
2100
/// According to the standard grammar, =default and =delete are function
2101
/// definitions, but that definitely doesn't fit with the parser here.
2102
///
2103
Decl *Parser::ParseDeclarationAfterDeclarator(
2104
344k
    Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2105
344k
  if (ParseAsmAttributesAfterDeclarator(D))
2106
0
    return nullptr;
2107
344k
2108
344k
  return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2109
344k
}
2110
2111
Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2112
14.8M
    Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2113
  // RAII type used to track whether we're inside an initializer.
2114
14.8M
  struct InitializerScopeRAII {
2115
14.8M
    Parser &P;
2116
14.8M
    Declarator &D;
2117
14.8M
    Decl *ThisDecl;
2118
14.8M
2119
14.8M
    InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2120
753k
        : P(P), D(D), ThisDecl(ThisDecl) {
2121
753k
      if (ThisDecl && 
P.getLangOpts().CPlusPlus753k
) {
2122
583k
        Scope *S = nullptr;
2123
583k
        if (D.getCXXScopeSpec().isSet()) {
2124
2.02k
          P.EnterScope(0);
2125
2.02k
          S = P.getCurScope();
2126
2.02k
        }
2127
583k
        P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2128
583k
      }
2129
753k
    }
2130
753k
    ~InitializerScopeRAII() { pop(); }
2131
1.50M
    void pop() {
2132
1.50M
      if (ThisDecl && 
P.getLangOpts().CPlusPlus753k
) {
2133
583k
        Scope *S = nullptr;
2134
583k
        if (D.getCXXScopeSpec().isSet())
2135
2.02k
          S = P.getCurScope();
2136
583k
        P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2137
583k
        if (S)
2138
2.02k
          P.ExitScope();
2139
583k
      }
2140
1.50M
      ThisDecl = nullptr;
2141
1.50M
    }
2142
14.8M
  };
2143
14.8M
2144
  // Inform the current actions module that we just parsed this declarator.
2145
14.8M
  Decl *ThisDecl = nullptr;
2146
14.8M
  switch (TemplateInfo.Kind) {
2147
14.7M
  case ParsedTemplateInfo::NonTemplate:
2148
14.7M
    ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2149
14.7M
    break;
2150
0
2151
81.3k
  case ParsedTemplateInfo::Template:
2152
81.3k
  case ParsedTemplateInfo::ExplicitSpecialization: {
2153
81.3k
    ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2154
81.3k
                                               *TemplateInfo.TemplateParams,
2155
81.3k
                                               D);
2156
81.3k
    if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
2157
      // Re-direct this decl to refer to the templated decl so that we can
2158
      // initialize it.
2159
1.88k
      ThisDecl = VT->getTemplatedDecl();
2160
81.3k
    break;
2161
81.3k
  }
2162
42.6k
  case ParsedTemplateInfo::ExplicitInstantiation: {
2163
42.6k
    if (Tok.is(tok::semi)) {
2164
42.6k
      DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2165
42.6k
          getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2166
42.6k
      if (ThisRes.isInvalid()) {
2167
102
        SkipUntil(tok::semi, StopBeforeMatch);
2168
102
        return nullptr;
2169
102
      }
2170
42.5k
      ThisDecl = ThisRes.get();
2171
6
    } else {
2172
      // FIXME: This check should be for a variable template instantiation only.
2173
6
2174
      // Check that this is a valid instantiation
2175
6
      if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
2176
        // If the declarator-id is not a template-id, issue a diagnostic and
2177
        // recover by ignoring the 'template' keyword.
2178
3
        Diag(Tok, diag::err_template_defn_explicit_instantiation)
2179
3
            << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2180
3
        ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2181
3
      } else {
2182
3
        SourceLocation LAngleLoc =
2183
3
            PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2184
3
        Diag(D.getIdentifierLoc(),
2185
3
             diag::err_explicit_instantiation_with_definition)
2186
3
            << SourceRange(TemplateInfo.TemplateLoc)
2187
3
            << FixItHint::CreateInsertion(LAngleLoc, "<>");
2188
3
2189
        // Recover as if it were an explicit specialization.
2190
3
        TemplateParameterLists FakedParamLists;
2191
3
        FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2192
3
            0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
2193
3
            LAngleLoc, nullptr));
2194
3
2195
3
        ThisDecl =
2196
3
            Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2197
3
      }
2198
6
    }
2199
42.5k
    break;
2200
14.8M
    }
2201
14.8M
  }
2202
14.8M
2203
  // Parse declarator '=' initializer.
2204
  // If a '==' or '+=' is found, suggest a fixit to '='.
2205
14.8M
  if (isTokenEqualOrEqualTypo()) {
2206
690k
    SourceLocation EqualLoc = ConsumeToken();
2207
690k
2208
690k
    if (Tok.is(tok::kw_delete)) {
2209
3
      if (D.isFunctionDeclarator())
2210
1
        Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2211
1
          << 1 /* delete */;
2212
2
      else
2213
2
        Diag(ConsumeToken(), diag::err_deleted_non_function);
2214
690k
    } else if (Tok.is(tok::kw_default)) {
2215
2
      if (D.isFunctionDeclarator())
2216
1
        Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2217
1
          << 0 /* default */;
2218
1
      else
2219
1
        Diag(ConsumeToken(), diag::err_default_special_members)
2220
1
            << getLangOpts().CPlusPlus20;
2221
690k
    } else {
2222
690k
      InitializerScopeRAII InitScope(*this, D, ThisDecl);
2223
690k
2224
690k
      if (Tok.is(tok::code_completion)) {
2225
42
        Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2226
42
        Actions.FinalizeDeclaration(ThisDecl);
2227
42
        cutOffParsing();
2228
42
        return nullptr;
2229
42
      }
2230
690k
2231
690k
      PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2232
690k
      ExprResult Init = ParseInitializer();
2233
690k
2234
      // If this is the only decl in (possibly) range based for statement,
2235
      // our best guess is that the user meant ':' instead of '='.
2236
690k
      if (Tok.is(tok::r_paren) && 
FRI4
&&
D.isFirstDeclarator()3
) {
2237
3
        Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2238
3
            << FixItHint::CreateReplacement(EqualLoc, ":");
2239
        // We are trying to stop parser from looking for ';' in this for
2240
        // statement, therefore preventing spurious errors to be issued.
2241
3
        FRI->ColonLoc = EqualLoc;
2242
3
        Init = ExprError();
2243
3
        FRI->RangeExpr = Init;
2244
3
      }
2245
690k
2246
690k
      InitScope.pop();
2247
690k
2248
690k
      if (Init.isInvalid()) {
2249
1.22k
        SmallVector<tok::TokenKind, 2> StopTokens;
2250
1.22k
        StopTokens.push_back(tok::comma);
2251
1.22k
        if (D.getContext() == DeclaratorContext::ForContext ||
2252
1.22k
            D.getContext() == DeclaratorContext::InitStmtContext)
2253
3
          StopTokens.push_back(tok::r_paren);
2254
1.22k
        SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2255
1.22k
        Actions.ActOnInitializerError(ThisDecl);
2256
1.22k
      } else
2257
689k
        Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2258
689k
                                     /*DirectInit=*/false);
2259
690k
    }
2260
14.2M
  } else if (Tok.is(tok::l_paren)) {
2261
    // Parse C++ direct initializer: '(' expression-list ')'
2262
57.8k
    BalancedDelimiterTracker T(*this, tok::l_paren);
2263
57.8k
    T.consumeOpen();
2264
57.8k
2265
57.8k
    ExprVector Exprs;
2266
57.8k
    CommaLocsTy CommaLocs;
2267
57.8k
2268
57.8k
    InitializerScopeRAII InitScope(*this, D, ThisDecl);
2269
57.8k
2270
57.8k
    auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2271
13
    auto RunSignatureHelp = [&]() {
2272
13
      QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2273
13
          getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2274
13
          ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2275
13
      CalledSignatureHelp = true;
2276
13
      return PreferredType;
2277
13
    };
2278
84.7k
    auto SetPreferredType = [&] {
2279
84.7k
      PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2280
84.7k
    };
2281
57.8k
2282
57.8k
    llvm::function_ref<void()> ExpressionStarts;
2283
57.8k
    if (ThisVarDecl) {
2284
      // ParseExpressionList can sometimes succeed even when ThisDecl is not
2285
      // VarDecl. This is an error and it is reported in a call to
2286
      // Actions.ActOnInitializerError(). However, we call
2287
      // ProduceConstructorSignatureHelp only on VarDecls.
2288
57.8k
      ExpressionStarts = SetPreferredType;
2289
57.8k
    }
2290
57.8k
    if (ParseExpressionList(Exprs, CommaLocs, ExpressionStarts)) {
2291
76
      if (ThisVarDecl && 
PP.isCodeCompletionReached()75
&&
!CalledSignatureHelp19
) {
2292
2
        Actions.ProduceConstructorSignatureHelp(
2293
2
            getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2294
2
            ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2295
2
        CalledSignatureHelp = true;
2296
2
      }
2297
76
      Actions.ActOnInitializerError(ThisDecl);
2298
76
      SkipUntil(tok::r_paren, StopAtSemi);
2299
57.7k
    } else {
2300
      // Match the ')'.
2301
57.7k
      T.consumeClose();
2302
57.7k
2303
57.7k
      assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2304
57.7k
             "Unexpected number of commas!");
2305
57.7k
2306
57.7k
      InitScope.pop();
2307
57.7k
2308
57.7k
      ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2309
57.7k
                                                          T.getCloseLocation(),
2310
57.7k
                                                          Exprs);
2311
57.7k
      Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2312
57.7k
                                   /*DirectInit=*/true);
2313
57.7k
    }
2314
14.1M
  } else if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)1.72M
&&
2315
5.25k
             (!CurParsedObjCImpl || 
!D.isFunctionDeclarator()1
)) {
2316
    // Parse C++0x braced-init-list.
2317
5.25k
    Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2318
5.25k
2319
5.25k
    InitializerScopeRAII InitScope(*this, D, ThisDecl);
2320
5.25k
2321
5.25k
    PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2322
5.25k
    ExprResult Init(ParseBraceInitializer());
2323
5.25k
2324
5.25k
    InitScope.pop();
2325
5.25k
2326
5.25k
    if (Init.isInvalid()) {
2327
9
      Actions.ActOnInitializerError(ThisDecl);
2328
9
    } else
2329
5.24k
      Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2330
5.25k
2331
14.1M
  } else {
2332
14.1M
    Actions.ActOnUninitializedDecl(ThisDecl);
2333
14.1M
  }
2334
14.8M
2335
14.8M
  Actions.FinalizeDeclaration(ThisDecl);
2336
14.8M
2337
14.8M
  return ThisDecl;
2338
14.8M
}
2339
2340
/// ParseSpecifierQualifierList
2341
///        specifier-qualifier-list:
2342
///          type-specifier specifier-qualifier-list[opt]
2343
///          type-qualifier specifier-qualifier-list[opt]
2344
/// [GNU]    attributes     specifier-qualifier-list[opt]
2345
///
2346
void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2347
13.6M
                                         DeclSpecContext DSC) {
2348
  /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
2349
  /// parse declaration-specifiers and complain about extra stuff.
2350
  /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2351
13.6M
  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2352
13.6M
2353
  // Validate declspec for type-name.
2354
13.6M
  unsigned Specs = DS.getParsedSpecifiers();
2355
13.6M
  if (isTypeSpecifier(DSC) && 
!DS.hasTypeSpecifier()4.02M
) {
2356
146
    Diag(Tok, diag::err_expected_type);
2357
146
    DS.SetTypeSpecError();
2358
13.6M
  } else if (Specs == DeclSpec::PQ_None && 
!DS.hasAttributes()44
) {
2359
27
    Diag(Tok, diag::err_typename_requires_specqual);
2360
27
    if (!DS.hasTypeSpecifier())
2361
27
      DS.SetTypeSpecError();
2362
27
  }
2363
13.6M
2364
  // Issue diagnostic and remove storage class if present.
2365
13.6M
  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2366
16
    if (DS.getStorageClassSpecLoc().isValid())
2367
11
      Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2368
5
    else
2369
5
      Diag(DS.getThreadStorageClassSpecLoc(),
2370
5
           diag::err_typename_invalid_storageclass);
2371
16
    DS.ClearStorageClassSpecs();
2372
16
  }
2373
13.6M
2374
  // Issue diagnostic and remove function specifier if present.
2375
13.6M
  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2376
6
    if (DS.isInlineSpecified())
2377
2
      Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2378
6
    if (DS.isVirtualSpecified())
2379
2
      Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2380
6
    if (DS.hasExplicitSpecifier())
2381
2
      Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2382
6
    DS.ClearFunctionSpecs();
2383
6
  }
2384
13.6M
2385
  // Issue diagnostic and remove constexpr specifier if present.
2386
13.6M
  if (DS.hasConstexprSpecifier() && 
DSC != DeclSpecContext::DSC_condition34
) {
2387
7
    Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2388
7
        << DS.getConstexprSpecifier();
2389
7
    DS.ClearConstexprSpec();
2390
7
  }
2391
13.6M
}
2392
2393
/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2394
/// specified token is valid after the identifier in a declarator which
2395
/// immediately follows the declspec.  For example, these things are valid:
2396
///
2397
///      int x   [             4];         // direct-declarator
2398
///      int x   (             int y);     // direct-declarator
2399
///  int(int x   )                         // direct-declarator
2400
///      int x   ;                         // simple-declaration
2401
///      int x   =             17;         // init-declarator-list
2402
///      int x   ,             y;          // init-declarator-list
2403
///      int x   __asm__       ("foo");    // init-declarator-list
2404
///      int x   :             4;          // struct-declarator
2405
///      int x   {             5};         // C++'0x unified initializers
2406
///
2407
/// This is not, because 'x' does not immediately follow the declspec (though
2408
/// ')' happens to be valid anyway).
2409
///    int (x)
2410
///
2411
427
static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2412
427
  return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2413
427
                   tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2414
427
                   tok::colon);
2415
427
}
2416
2417
/// ParseImplicitInt - This method is called when we have an non-typename
2418
/// identifier in a declspec (which normally terminates the decl spec) when
2419
/// the declspec has no type specifier.  In this case, the declspec is either
2420
/// malformed or is "implicit int" (in K&R and C89).
2421
///
2422
/// This method handles diagnosing this prettily and returns false if the
2423
/// declspec is done being processed.  If it recovers and thinks there may be
2424
/// other pieces of declspec after it, it returns true.
2425
///
2426
bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2427
                              const ParsedTemplateInfo &TemplateInfo,
2428
                              AccessSpecifier AS, DeclSpecContext DSC,
2429
1.58k
                              ParsedAttributesWithRange &Attrs) {
2430
1.58k
  assert(Tok.is(tok::identifier) && "should have identifier");
2431
1.58k
2432
1.58k
  SourceLocation Loc = Tok.getLocation();
2433
  // If we see an identifier that is not a type name, we normally would
2434
  // parse it as the identifier being declared.  However, when a typename
2435
  // is typo'd or the definition is not included, this will incorrectly
2436
  // parse the typename as the identifier name and fall over misparsing
2437
  // later parts of the diagnostic.
2438
  //
2439
  // As such, we try to do some look-ahead in cases where this would
2440
  // otherwise be an "implicit-int" case to see if this is invalid.  For
2441
  // example: "static foo_t x = 4;"  In this case, if we parsed foo_t as
2442
  // an identifier with implicit int, we'd get a parse error because the
2443
  // next token is obviously invalid for a type.  Parse these as a case
2444
  // with an invalid type specifier.
2445
1.58k
  assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2446
1.58k
2447
  // Since we know that this either implicit int (which is rare) or an
2448
  // error, do lookahead to try to do better recovery. This never applies
2449
  // within a type specifier. Outside of C++, we allow this even if the
2450
  // language doesn't "officially" support implicit int -- we support
2451
  // implicit int as an extension in C99 and C11.
2452
1.58k
  if (!isTypeSpecifier(DSC) && 
!getLangOpts().CPlusPlus1.46k
&&
2453
427
      isValidAfterIdentifierInDeclarator(NextToken())) {
2454
    // If this token is valid for implicit int, e.g. "static x = 4", then
2455
    // we just avoid eating the identifier, so it will be parsed as the
2456
    // identifier in the declarator.
2457
85
    return false;
2458
85
  }
2459
1.50k
2460
  // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2461
  // for incomplete declarations such as `pipe p`.
2462
1.50k
  if (getLangOpts().OpenCLCPlusPlus && 
DS.isTypeSpecPipe()1
)
2463
1
    return false;
2464
1.50k
2465
1.50k
  if (getLangOpts().CPlusPlus &&
2466
1.14k
      DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2467
    // Don't require a type specifier if we have the 'auto' storage class
2468
    // specifier in C++98 -- we'll promote it to a type specifier.
2469
72
    if (SS)
2470
3
      AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2471
72
    return false;
2472
72
  }
2473
1.43k
2474
1.43k
  if (getLangOpts().CPlusPlus && 
(1.07k
!SS1.07k
||
SS->isEmpty()444
) &&
2475
629
      getLangOpts().MSVCCompat) {
2476
    // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2477
    // Give Sema a chance to recover if we are in a template with dependent base
2478
    // classes.
2479
36
    if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2480
15
            *Tok.getIdentifierInfo(), Tok.getLocation(),
2481
15
            DSC == DeclSpecContext::DSC_template_type_arg)) {
2482
15
      const char *PrevSpec;
2483
15
      unsigned DiagID;
2484
15
      DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2485
15
                         Actions.getASTContext().getPrintingPolicy());
2486
15
      DS.SetRangeEnd(Tok.getLocation());
2487
15
      ConsumeToken();
2488
15
      return false;
2489
15
    }
2490
1.41k
  }
2491
1.41k
2492
  // Otherwise, if we don't consume this token, we are going to emit an
2493
  // error anyway.  Try to recover from various common problems.  Check
2494
  // to see if this was a reference to a tag name without a tag specified.
2495
  // This is a common problem in C (saying 'foo' instead of 'struct foo').
2496
  //
2497
  // C++ doesn't need this, and isTagName doesn't take SS.
2498
1.41k
  if (SS == nullptr) {
2499
971
    const char *TagName = nullptr, *FixitTagName = nullptr;
2500
971
    tok::TokenKind TagKind = tok::unknown;
2501
971
2502
971
    switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2503
937
      default: break;
2504
11
      case DeclSpec::TST_enum:
2505
11
        TagName="enum"  ; FixitTagName = "enum "  ; TagKind=tok::kw_enum ;break;
2506
0
      case DeclSpec::TST_union:
2507
0
        TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2508
14
      case DeclSpec::TST_struct:
2509
14
        TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2510
0
      case DeclSpec::TST_interface:
2511
0
        TagName="__interface"; FixitTagName = "__interface ";
2512
0
        TagKind=tok::kw___interface;break;
2513
9
      case DeclSpec::TST_class:
2514
9
        TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2515
971
    }
2516
971
2517
971
    if (TagName) {
2518
34
      IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2519
34
      LookupResult R(Actions, TokenName, SourceLocation(),
2520
34
                     Sema::LookupOrdinaryName);
2521
34
2522
34
      Diag(Loc, diag::err_use_of_tag_name_without_tag)
2523
34
        << TokenName << TagName << getLangOpts().CPlusPlus
2524
34
        << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2525
34
2526
34
      if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2527
19
        for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2528
38
             I != IEnd; 
++I19
)
2529
19
          Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2530
19
            << TokenName << TagName;
2531
19
      }
2532
34
2533
      // Parse this as a tag as if the missing tag were present.
2534
34
      if (TagKind == tok::kw_enum)
2535
11
        ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2536
11
                           DeclSpecContext::DSC_normal);
2537
23
      else
2538
23
        ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2539
23
                            /*EnteringContext*/ false,
2540
23
                            DeclSpecContext::DSC_normal, Attrs);
2541
34
      return true;
2542
34
    }
2543
1.38k
  }
2544
1.38k
2545
  // Determine whether this identifier could plausibly be the name of something
2546
  // being declared (with a missing type).
2547
1.38k
  if (!isTypeSpecifier(DSC) && 
(1.27k
!SS1.27k
||
DSC == DeclSpecContext::DSC_top_level421
||
2548
1.12k
                                
DSC == DeclSpecContext::DSC_class257
)) {
2549
    // Look ahead to the next token to try to figure out what this declaration
2550
    // was supposed to be.
2551
1.12k
    switch (NextToken().getKind()) {
2552
64
    case tok::l_paren: {
2553
      // static x(4); // 'x' is not a type
2554
      // x(int n);    // 'x' is not a type
2555
      // x (*p)[];    // 'x' is a type
2556
      //
2557
      // Since we're in an error case, we can afford to perform a tentative
2558
      // parse to determine which case we're in.
2559
64
      TentativeParsingAction PA(*this);
2560
64
      ConsumeToken();
2561
64
      TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2562
64
      PA.Revert();
2563
64
2564
64
      if (TPR != TPResult::False) {
2565
        // The identifier is followed by a parenthesized declarator.
2566
        // It's supposed to be a type.
2567
2
        break;
2568
2
      }
2569
62
2570
      // If we're in a context where we could be declaring a constructor,
2571
      // check whether this is a constructor declaration with a bogus name.
2572
62
      if (DSC == DeclSpecContext::DSC_class ||
2573
40
          (DSC == DeclSpecContext::DSC_top_level && 
SS38
)) {
2574
40
        IdentifierInfo *II = Tok.getIdentifierInfo();
2575
40
        if (Actions.isCurrentClassNameTypo(II, SS)) {
2576
10
          Diag(Loc, diag::err_constructor_bad_name)
2577
10
            << Tok.getIdentifierInfo() << II
2578
10
            << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2579
10
          Tok.setIdentifierInfo(II);
2580
10
        }
2581
40
      }
2582
      // Fall through.
2583
62
      LLVM_FALLTHROUGH;
2584
62
    }
2585
175
    case tok::comma:
2586
175
    case tok::equal:
2587
175
    case tok::kw_asm:
2588
175
    case tok::l_brace:
2589
175
    case tok::l_square:
2590
175
    case tok::semi:
2591
      // This looks like a variable or function declaration. The type is
2592
      // probably missing. We're done parsing decl-specifiers.
2593
      // But only if we are not in a function prototype scope.
2594
175
      if (getCurScope()->isFunctionPrototypeScope())
2595
8
        break;
2596
167
      if (SS)
2597
35
        AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2598
167
      return false;
2599
167
2600
952
    default:
2601
      // This is probably supposed to be a type. This includes cases like:
2602
      //   int f(itn);
2603
      //   struct S { unsigned : 4; };
2604
952
      break;
2605
1.21k
    }
2606
1.21k
  }
2607
1.21k
2608
  // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2609
  // and attempt to recover.
2610
1.21k
  ParsedType T;
2611
1.21k
  IdentifierInfo *II = Tok.getIdentifierInfo();
2612
1.21k
  bool IsTemplateName = getLangOpts().CPlusPlus && 
NextToken().is(tok::less)872
;
2613
1.21k
  Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2614
1.21k
                                  IsTemplateName);
2615
1.21k
  if (T) {
2616
    // The action has suggested that the type T could be used. Set that as
2617
    // the type in the declaration specifiers, consume the would-be type
2618
    // name token, and we're done.
2619
402
    const char *PrevSpec;
2620
402
    unsigned DiagID;
2621
402
    DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2622
402
                       Actions.getASTContext().getPrintingPolicy());
2623
402
    DS.SetRangeEnd(Tok.getLocation());
2624
402
    ConsumeToken();
2625
    // There may be other declaration specifiers after this.
2626
402
    return true;
2627
812
  } else if (II != Tok.getIdentifierInfo()) {
2628
    // If no type was suggested, the correction is to a keyword
2629
12
    Tok.setKind(II->getTokenID());
2630
    // There may be other declaration specifiers after this.
2631
12
    return true;
2632
12
  }
2633
800
2634
  // Otherwise, the action had no suggestion for us.  Mark this as an error.
2635
800
  DS.SetTypeSpecError();
2636
800
  DS.SetRangeEnd(Tok.getLocation());
2637
800
  ConsumeToken();
2638
800
2639
  // Eat any following template arguments.
2640
800
  if (IsTemplateName) {
2641
2
    SourceLocation LAngle, RAngle;
2642
2
    TemplateArgList Args;
2643
2
    ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2644
2
  }
2645
800
2646
  // TODO: Could inject an invalid typedef decl in an enclosing scope to
2647
  // avoid rippling error messages on subsequent uses of the same type,
2648
  // could be useful if #include was forgotten.
2649
800
  return true;
2650
800
}
2651
2652
/// Determine the declaration specifier context from the declarator
2653
/// context.
2654
///
2655
/// \param Context the declarator context, which is one of the
2656
/// DeclaratorContext enumerator values.
2657
Parser::DeclSpecContext
2658
7.85M
Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2659
7.85M
  if (Context == DeclaratorContext::MemberContext)
2660
0
    return DeclSpecContext::DSC_class;
2661
7.85M
  if (Context == DeclaratorContext::FileContext)
2662
2.77M
    return DeclSpecContext::DSC_top_level;
2663
5.07M
  if (Context == DeclaratorContext::TemplateParamContext)
2664
0
    return DeclSpecContext::DSC_template_param;
2665
5.07M
  if (Context == DeclaratorContext::TemplateArgContext ||
2666
1.74M
      Context == DeclaratorContext::TemplateTypeArgContext)
2667
3.40M
    return DeclSpecContext::DSC_template_type_arg;
2668
1.67M
  if (Context == DeclaratorContext::TrailingReturnContext ||
2669
1.67M
      Context == DeclaratorContext::TrailingReturnVarContext)
2670
18.4k
    return DeclSpecContext::DSC_trailing;
2671
1.65M
  if (Context == DeclaratorContext::AliasDeclContext ||
2672
1.64M
      Context == DeclaratorContext::AliasTemplateContext)
2673
56.3k
    return DeclSpecContext::DSC_alias_declaration;
2674
1.60M
  return DeclSpecContext::DSC_normal;
2675
1.60M
}
2676
2677
/// ParseAlignArgument - Parse the argument to an alignment-specifier.
2678
///
2679
/// FIXME: Simply returns an alignof() expression if the argument is a
2680
/// type. Ideally, the type should be propagated directly into Sema.
2681
///
2682
/// [C11]   type-id
2683
/// [C11]   constant-expression
2684
/// [C++0x] type-id ...[opt]
2685
/// [C++0x] assignment-expression ...[opt]
2686
ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2687
8.58k
                                      SourceLocation &EllipsisLoc) {
2688
8.58k
  ExprResult ER;
2689
8.58k
  if (isTypeIdInParens()) {
2690
76
    SourceLocation TypeLoc = Tok.getLocation();
2691
76
    ParsedType Ty = ParseTypeName().get();
2692
76
    SourceRange TypeRange(Start, Tok.getLocation());
2693
76
    ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2694
76
                                               Ty.getAsOpaquePtr(), TypeRange);
2695
76
  } else
2696
8.50k
    ER = ParseConstantExpression();
2697
8.58k
2698
8.58k
  if (getLangOpts().CPlusPlus11)
2699
8.53k
    TryConsumeToken(tok::ellipsis, EllipsisLoc);
2700
8.58k
2701
8.58k
  return ER;
2702
8.58k
}
2703
2704
/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2705
/// attribute to Attrs.
2706
///
2707
/// alignment-specifier:
2708
/// [C11]   '_Alignas' '(' type-id ')'
2709
/// [C11]   '_Alignas' '(' constant-expression ')'
2710
/// [C++11] 'alignas' '(' type-id ...[opt] ')'
2711
/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2712
void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2713
8.58k
                                     SourceLocation *EndLoc) {
2714
8.58k
  assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2715
8.58k
         "Not an alignment-specifier!");
2716
8.58k
2717
8.58k
  IdentifierInfo *KWName = Tok.getIdentifierInfo();
2718
8.58k
  SourceLocation KWLoc = ConsumeToken();
2719
8.58k
2720
8.58k
  BalancedDelimiterTracker T(*this, tok::l_paren);
2721
8.58k
  if (T.expectAndConsume())
2722
1
    return;
2723
8.58k
2724
8.58k
  SourceLocation EllipsisLoc;
2725
8.58k
  ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2726
8.58k
  if (ArgExpr.isInvalid()) {
2727
10
    T.skipToEnd();
2728
10
    return;
2729
10
  }
2730
8.57k
2731
8.57k
  T.consumeClose();
2732
8.57k
  if (EndLoc)
2733
7.38k
    *EndLoc = T.getCloseLocation();
2734
8.57k
2735
8.57k
  ArgsVector ArgExprs;
2736
8.57k
  ArgExprs.push_back(ArgExpr.get());
2737
8.57k
  Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2738
8.57k
               ParsedAttr::AS_Keyword, EllipsisLoc);
2739
8.57k
}
2740
2741
905
ExprResult Parser::ParseExtIntegerArgument() {
2742
905
  assert(Tok.is(tok::kw__ExtInt) && "Not an extended int type");
2743
905
  ConsumeToken();
2744
905
2745
905
  BalancedDelimiterTracker T(*this, tok::l_paren);
2746
905
  if (T.expectAndConsume())
2747
1
    return ExprError();
2748
904
2749
904
  ExprResult ER = ParseConstantExpression();
2750
904
  if (ER.isInvalid()) {
2751
1
    T.skipToEnd();
2752
1
    return ExprError();
2753
1
  }
2754
903
2755
903
  if(T.consumeClose())
2756
1
    return ExprError();
2757
902
  return ER;
2758
902
}
2759
2760
/// Determine whether we're looking at something that might be a declarator
2761
/// in a simple-declaration. If it can't possibly be a declarator, maybe
2762
/// diagnose a missing semicolon after a prior tag definition in the decl
2763
/// specifier.
2764
///
2765
/// \return \c true if an error occurred and this can't be any kind of
2766
/// declaration.
2767
bool
2768
Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2769
                                              DeclSpecContext DSContext,
2770
1.34M
                                              LateParsedAttrList *LateAttrs) {
2771
1.34M
  assert(DS.hasTagDefinition() && "shouldn't call this");
2772
1.34M
2773
1.34M
  bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2774
1.30M
                          DSContext == DeclSpecContext::DSC_top_level);
2775
1.34M
2776
1.34M
  if (getLangOpts().CPlusPlus &&
2777
339k
      Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2778
339k
                  tok::annot_template_id) &&
2779
62.8k
      TryAnnotateCXXScopeToken(EnteringContext)) {
2780
0
    SkipMalformedDecl();
2781
0
    return true;
2782
0
  }
2783
1.34M
2784
1.34M
  bool HasScope = Tok.is(tok::annot_cxxscope);
2785
  // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2786
1.34M
  Token AfterScope = HasScope ? 
NextToken()20
: Tok;
2787
1.34M
2788
  // Determine whether the following tokens could possibly be a
2789
  // declarator.
2790
1.34M
  bool MightBeDeclarator = true;
2791
1.34M
  if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2792
    // A declarator-id can't start with 'typename'.
2793
0
    MightBeDeclarator = false;
2794
1.34M
  } else if (AfterScope.is(tok::annot_template_id)) {
2795
    // If we have a type expressed as a template-id, this cannot be a
2796
    // declarator-id (such a type cannot be redeclared in a simple-declaration).
2797
8
    TemplateIdAnnotation *Annot =
2798
8
        static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2799
8
    if (Annot->Kind == TNK_Type_template)
2800
8
      MightBeDeclarator = false;
2801
1.34M
  } else if (AfterScope.is(tok::identifier)) {
2802
330k
    const Token &Next = HasScope ? 
GetLookAheadToken(2)10
: NextToken();
2803
330k
2804
    // These tokens cannot come after the declarator-id in a
2805
    // simple-declaration, and are likely to come after a type-specifier.
2806
330k
    if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2807
5
                     tok::annot_cxxscope, tok::coloncolon)) {
2808
      // Missing a semicolon.
2809
5
      MightBeDeclarator = false;
2810
330k
    } else if (HasScope) {
2811
      // If the declarator-id has a scope specifier, it must redeclare a
2812
      // previously-declared entity. If that's a type (and this is not a
2813
      // typedef), that's an error.
2814
9
      CXXScopeSpec SS;
2815
9
      Actions.RestoreNestedNameSpecifierAnnotation(
2816
9
          Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2817
9
      IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2818
9
      Sema::NameClassification Classification = Actions.ClassifyName(
2819
9
          getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2820
9
          /*CCC=*/nullptr);
2821
9
      switch (Classification.getKind()) {
2822
0
      case Sema::NC_Error:
2823
0
        SkipMalformedDecl();
2824
0
        return true;
2825
0
2826
0
      case Sema::NC_Keyword:
2827
0
        llvm_unreachable("typo correction is not possible here");
2828
0
2829
1
      case Sema::NC_Type:
2830
1
      case Sema::NC_TypeTemplate:
2831
1
      case Sema::NC_UndeclaredNonType:
2832
1
      case Sema::NC_UndeclaredTemplate:
2833
        // Not a previously-declared non-type entity.
2834
1
        MightBeDeclarator = false;
2835
1
        break;
2836
1
2837
8
      case Sema::NC_Unknown:
2838
8
      case Sema::NC_NonType:
2839
8
      case Sema::NC_DependentNonType:
2840
8
      case Sema::NC_OverloadSet:
2841
8
      case Sema::NC_VarTemplate:
2842
8
      case Sema::NC_FunctionTemplate:
2843
8
      case Sema::NC_Concept:
2844
        // Might be a redeclaration of a prior entity.
2845
8
        break;
2846
1.34M
      }
2847
1.34M
    }
2848
330k
  }
2849
1.34M
2850
1.34M
  if (MightBeDeclarator)
2851
1.34M
    return false;
2852
14
2853
14
  const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2854
14
  Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
2855
14
       diag::err_expected_after)
2856
14
      << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2857
14
2858
  // Try to recover from the typo, by dropping the tag definition and parsing
2859
  // the problematic tokens as a type.
2860
  //
2861
  // FIXME: Split the DeclSpec into pieces for the standalone
2862
  // declaration and pieces for the following declaration, instead
2863
  // of assuming that all the other pieces attach to new declaration,
2864
  // and call ParsedFreeStandingDeclSpec as appropriate.
2865
14
  DS.ClearTypeSpecType();
2866
14
  ParsedTemplateInfo NotATemplate;
2867
14
  ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2868
14
  return false;
2869
14
}
2870
2871
// Choose the apprpriate diagnostic error for why fixed point types are
2872
// disabled, set the previous specifier, and mark as invalid.
2873
static void SetupFixedPointError(const LangOptions &LangOpts,
2874
                                 const char *&PrevSpec, unsigned &DiagID,
2875
9
                                 bool &isInvalid) {
2876
9
  assert(!LangOpts.FixedPoint);
2877
9
  DiagID = diag::err_fixed_point_not_enabled;
2878
9
  PrevSpec = "";  // Not used by diagnostic
2879
9
  isInvalid = true;
2880
9
}
2881
2882
/// ParseDeclarationSpecifiers
2883
///       declaration-specifiers: [C99 6.7]
2884
///         storage-class-specifier declaration-specifiers[opt]
2885
///         type-specifier declaration-specifiers[opt]
2886
/// [C99]   function-specifier declaration-specifiers[opt]
2887
/// [C11]   alignment-specifier declaration-specifiers[opt]
2888
/// [GNU]   attributes declaration-specifiers[opt]
2889
/// [Clang] '__module_private__' declaration-specifiers[opt]
2890
/// [ObjC1] '__kindof' declaration-specifiers[opt]
2891
///
2892
///       storage-class-specifier: [C99 6.7.1]
2893
///         'typedef'
2894
///         'extern'
2895
///         'static'
2896
///         'auto'
2897
///         'register'
2898
/// [C++]   'mutable'
2899
/// [C++11] 'thread_local'
2900
/// [C11]   '_Thread_local'
2901
/// [GNU]   '__thread'
2902
///       function-specifier: [C99 6.7.4]
2903
/// [C99]   'inline'
2904
/// [C++]   'virtual'
2905
/// [C++]   'explicit'
2906
/// [OpenCL] '__kernel'
2907
///       'friend': [C++ dcl.friend]
2908
///       'constexpr': [C++0x dcl.constexpr]
2909
void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2910
                                        const ParsedTemplateInfo &TemplateInfo,
2911
                                        AccessSpecifier AS,
2912
                                        DeclSpecContext DSContext,
2913
69.9M
                                        LateParsedAttrList *LateAttrs) {
2914
69.9M
  if (DS.getSourceRange().isInvalid()) {
2915
    // Start the range at the current token but make the end of the range
2916
    // invalid.  This will make the entire range invalid unless we successfully
2917
    // consume a token.
2918
69.9M
    DS.SetRangeStart(Tok.getLocation());
2919
69.9M
    DS.SetRangeEnd(SourceLocation());
2920
69.9M
  }
2921
69.9M
2922
69.9M
  bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2923
67.5M
                          DSContext == DeclSpecContext::DSC_top_level);
2924
69.9M
  bool AttrsLastTime = false;
2925
69.9M
  ParsedAttributesWithRange attrs(AttrFactory);
2926
  // We use Sema's policy to get bool macros right.
2927
69.9M
  PrintingPolicy Policy = Actions.getPrintingPolicy();
2928
183M
  while (1) {
2929
183M
    bool isInvalid = false;
2930
183M
    bool isStorageClass = false;
2931
183M
    const char *PrevSpec = nullptr;
2932
183M
    unsigned DiagID = 0;
2933
183M
2934
    // This value needs to be set to the location of the last token if the last
2935
    // token of the specifier is already consumed.
2936
183M
    SourceLocation ConsumedEnd;
2937
183M
2938
    // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2939
    // implementation for VS2013 uses _Atomic as an identifier for one of the
2940
    // classes in <atomic>.
2941
    //
2942
    // A typedef declaration containing _Atomic<...> is among the places where
2943
    // the class is used.  If we are currently parsing such a declaration, treat
2944
    // the token as an identifier.
2945
183M
    if (getLangOpts().MSVCCompat && 
Tok.is(tok::kw__Atomic)1.02M
&&
2946
31
        DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
2947
4
        !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
2948
2
      Tok.setKind(tok::identifier);
2949
183M
2950
183M
    SourceLocation Loc = Tok.getLocation();
2951
183M
2952
183M
    switch (Tok.getKind()) {
2953
40.5M
    default:
2954
69.9M
    DoneWithDeclSpec:
2955
69.9M
      if (!AttrsLastTime)
2956
69.9M
        ProhibitAttributes(attrs);
2957
35
      else {
2958
        // Reject C++11 attributes that appertain to decl specifiers as
2959
        // we don't support any C++11 attributes that appertain to decl
2960
        // specifiers. This also conforms to what g++ 4.8 is doing.
2961
35
        ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
2962
35
2963
35
        DS.takeAttributesFrom(attrs);
2964
35
      }
2965
69.9M
2966
      // If this is not a declaration specifier token, we're done reading decl
2967
      // specifiers.  First verify that DeclSpec's are consistent.
2968
69.9M
      DS.Finish(Actions, Policy);
2969
69.9M
      return;
2970
40.5M
2971
22.9k
    case tok::l_square:
2972
22.9k
    case tok::kw_alignas:
2973
22.9k
      if (!standardAttributesAllowed() || 
!isCXX11AttributeSpecifier()13.6k
)
2974
22.9k
        goto DoneWithDeclSpec;
2975
43
2976
43
      ProhibitAttributes(attrs);
2977
      // FIXME: It would be good to recover by accepting the attributes,
2978
      //        but attempting to do that now would cause serious
2979
      //        madness in terms of diagnostics.
2980
43
      attrs.clear();
2981
43
      attrs.Range = SourceRange();
2982
43
2983
43
      ParseCXX11Attributes(attrs);
2984
43
      AttrsLastTime = true;
2985
43
      continue;
2986
43
2987
45
    case tok::code_completion: {
2988
45
      Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2989
45
      if (DS.hasTypeSpecifier()) {
2990
35
        bool AllowNonIdentifiers
2991
35
          = (getCurScope()->getFlags() & (Scope::ControlScope |
2992
35
                                          Scope::BlockScope |
2993
35
                                          Scope::TemplateParamScope |
2994
35
                                          Scope::FunctionPrototypeScope |
2995
35
                                          Scope::AtCatchScope)) == 0;
2996
35
        bool AllowNestedNameSpecifiers
2997
35
          = DSContext == DeclSpecContext::DSC_top_level ||
2998
24
            (DSContext == DeclSpecContext::DSC_class && 
DS.isFriendSpecified()13
);
2999
35
3000
35
        Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3001
35
                                     AllowNonIdentifiers,
3002
35
                                     AllowNestedNameSpecifiers);
3003
35
        return cutOffParsing();
3004
35
      }
3005
10
3006
10
      if (getCurScope()->getFnParent() || 
getCurScope()->getBlockParent()9
)
3007
1
        CCC = Sema::PCC_LocalDeclarationSpecifiers;
3008
9
      else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3009
0
        CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3010
0
                                                      : Sema::PCC_Template;
3011
9
      else if (DSContext == DeclSpecContext::DSC_class)
3012
8
        CCC = Sema::PCC_Class;
3013
1
      else if (CurParsedObjCImpl)
3014
0
        CCC = Sema::PCC_ObjCImplementation;
3015
10
3016
10
      Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3017
10
      return cutOffParsing();
3018
10
    }
3019
10
3020
568
    case tok::coloncolon: // ::foo::bar
3021
      // C++ scope specifier.  Annotate and loop, or bail out on error.
3022
568
      if (TryAnnotateCXXScopeToken(EnteringContext)) {
3023
0
        if (!DS.hasTypeSpecifier())
3024
0
          DS.SetTypeSpecError();
3025
0
        goto DoneWithDeclSpec;
3026
0
      }
3027
568
      if (Tok.is(tok::coloncolon)) // ::new or ::delete
3028
3
        goto DoneWithDeclSpec;
3029
565
      continue;
3030
565
3031
137k
    case tok::annot_cxxscope: {
3032
137k
      if (DS.hasTypeSpecifier() || 
DS.isTypeAltiVecVector()137k
)
3033
51
        goto DoneWithDeclSpec;
3034
137k
3035
137k
      CXXScopeSpec SS;
3036
137k
      Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3037
137k
                                                   Tok.getAnnotationRange(),
3038
137k
                                                   SS);
3039
137k
3040
      // We are looking for a qualified typename.
3041
137k
      Token Next = NextToken();
3042
137k
3043
137k
      TemplateIdAnnotation *TemplateId = Next.is(tok::annot_template_id)
3044
21.8k
                                             ? takeTemplateIdAnnotation(Next)
3045
115k
                                             : nullptr;
3046
137k
      if (TemplateId && 
TemplateId->hasInvalidName()21.8k
) {
3047
        // We found something like 'T::U<Args> x', but U is not a template.
3048
        // Assume it was supposed to be a type.
3049
1
        DS.SetTypeSpecError();
3050
1
        ConsumeAnnotationToken();
3051
1
        break;
3052
1
      }
3053
137k
3054
137k
      if (TemplateId && 
TemplateId->Kind == TNK_Type_template21.8k
) {
3055
        // We have a qualified template-id, e.g., N::A<int>
3056
21.7k
3057
        // If this would be a valid constructor declaration with template
3058
        // arguments, we will reject the attempt to form an invalid type-id
3059
        // referring to the injected-class-name when we annotate the token,
3060
        // per C++ [class.qual]p2.
3061
        //
3062
        // To improve diagnostics for this case, parse the declaration as a
3063
        // constructor (and reject the extra template arguments later).
3064
21.7k
        if ((DSContext == DeclSpecContext::DSC_top_level ||
3065
17.8k
             DSContext == DeclSpecContext::DSC_class) &&
3066
10.4k
            TemplateId->Name &&
3067
10.4k
            Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3068
25
            isConstructorDeclarator(/*Unqualified=*/false)) {
3069
          // The user meant this to be an out-of-line constructor
3070
          // definition, but template arguments are not allowed
3071
          // there.  Just allow this as a constructor; we'll
3072
          // complain about it later.
3073
16
          goto DoneWithDeclSpec;
3074
16
        }
3075
21.7k
3076
21.7k
        DS.getTypeSpecScope() = SS;
3077
21.7k
        ConsumeAnnotationToken(); // The C++ scope.
3078
21.7k
        assert(Tok.is(tok::annot_template_id) &&
3079
21.7k
               "ParseOptionalCXXScopeSpecifier not working");
3080
21.7k
        AnnotateTemplateIdTokenAsType(SS);
3081
21.7k
        continue;
3082
21.7k
      }
3083
115k
3084
115k
      if (TemplateId && 
TemplateId->Kind == TNK_Concept_template33
&&
3085
25
          GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype)) {
3086
25
        DS.getTypeSpecScope() = SS;
3087
        // This is a qualified placeholder-specifier, e.g., ::C<int> auto ...
3088
        // Consume the scope annotation and continue to consume the template-id
3089
        // as a placeholder-specifier.
3090
25
        ConsumeAnnotationToken();
3091
25
        continue;
3092
25
      }
3093
115k
3094
115k
      if (Next.is(tok::annot_typename)) {
3095
0
        DS.getTypeSpecScope() = SS;
3096
0
        ConsumeAnnotationToken(); // The C++ scope.
3097
0
        TypeResult T = getTypeAnnotation(Tok);
3098
0
        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3099
0
                                       Tok.getAnnotationEndLoc(),
3100
0
                                       PrevSpec, DiagID, T, Policy);
3101
0
        if (isInvalid)
3102
0
          break;
3103
0
        DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3104
0
        ConsumeAnnotationToken(); // The typename
3105
0
      }
3106
115k
3107
115k
      if (Next.isNot(tok::identifier))
3108
4.64k
        goto DoneWithDeclSpec;
3109
110k
3110
      // Check whether this is a constructor declaration. If we're in a
3111
      // context where the identifier could be a class name, and it has the
3112
      // shape of a constructor declaration, process it as one.
3113
110k
      if ((DSContext == DeclSpecContext::DSC_top_level ||
3114
63.9k
           DSContext == DeclSpecContext::DSC_class) &&
3115
66.0k
          Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3116
66.0k
                                     &SS) &&
3117
34.0k
          isConstructorDeclarator(/*Unqualified*/ false))
3118
34.0k
        goto DoneWithDeclSpec;
3119
76.5k
3120
76.5k
      ParsedType TypeRep =
3121
76.5k
          Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3122
76.5k
                              getCurScope(), &SS, false, false, nullptr,
3123
76.5k
                              /*IsCtorOrDtorName=*/false,
3124
76.5k
                              /*WantNontrivialTypeSourceInfo=*/true,
3125
76.5k
                              isClassTemplateDeductionContext(DSContext));
3126
76.5k
3127
      // If the referenced identifier is not a type, then this declspec is
3128
      // erroneous: We already checked about that it has no type specifier, and
3129
      // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
3130
      // typename.
3131
76.5k
      if (!TypeRep) {
3132
456
        if (TryAnnotateTypeConstraint())
3133
0
          goto DoneWithDeclSpec;
3134
456
        if (Tok.isNot(tok::annot_cxxscope) ||
3135
456
            NextToken().isNot(tok::identifier))
3136
9
          continue;
3137
        // Eat the scope spec so the identifier is current.
3138
447
        ConsumeAnnotationToken();
3139
447
        ParsedAttributesWithRange Attrs(AttrFactory);
3140
447
        if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3141
409
          if (!Attrs.empty()) {
3142
0
            AttrsLastTime = true;
3143
0
            attrs.takeAllFrom(Attrs);
3144
0
          }
3145
409
          continue;
3146
409
        }
3147
38
        goto DoneWithDeclSpec;
3148
38
      }
3149
76.0k
3150
76.0k
      DS.getTypeSpecScope() = SS;
3151
76.0k
      ConsumeAnnotationToken(); // The C++ scope.
3152
76.0k
3153
76.0k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3154
76.0k
                                     DiagID, TypeRep, Policy);
3155
76.0k
      if (isInvalid)
3156
0
        break;
3157
76.0k
3158
76.0k
      DS.SetRangeEnd(Tok.getLocation());
3159
76.0k
      ConsumeToken(); // The typename.
3160
76.0k
3161
76.0k
      continue;
3162
76.0k
    }
3163
76.0k
3164
21.4M
    case tok::annot_typename: {
3165
      // If we've previously seen a tag definition, we were almost surely
3166
      // missing a semicolon after it.
3167
21.4M
      if (DS.hasTypeSpecifier() && 
DS.hasTagDefinition()3
)
3168
0
        goto DoneWithDeclSpec;
3169
21.4M
3170
21.4M
      TypeResult T = getTypeAnnotation(Tok);
3171
21.4M
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3172
21.4M
                                     DiagID, T, Policy);
3173
21.4M
      if (isInvalid)
3174
3
        break;
3175
21.4M
3176
21.4M
      DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3177
21.4M
      ConsumeAnnotationToken(); // The typename
3178
21.4M
3179
21.4M
      continue;
3180
21.4M
    }
3181
21.4M
3182
1
    case tok::kw___is_signed:
3183
      // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3184
      // typically treats it as a trait. If we see __is_signed as it appears
3185
      // in libstdc++, e.g.,
3186
      //
3187
      //   static const bool __is_signed;
3188
      //
3189
      // then treat __is_signed as an identifier rather than as a keyword.
3190
1
      if (DS.getTypeSpecType() == TST_bool &&
3191
1
          DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3192
1
          DS.getStorageClassSpec() == DeclSpec::SCS_static)
3193
1
        TryKeywordIdentFallback(true);
3194
1
3195
      // We're done with the declaration-specifiers.
3196
1
      goto DoneWithDeclSpec;
3197
21.4M
3198
      // typedef-name
3199
67.1M
    case tok::kw___super:
3200
67.1M
    case tok::kw_decltype:
3201
67.1M
    case tok::identifier: {
3202
      // This identifier can only be a typedef name if we haven't already seen
3203
      // a type-specifier.  Without this check we misparse:
3204
      //  typedef int X; struct Y { short X; };  as 'short int'.
3205
67.1M
      if (DS.hasTypeSpecifier())
3206
29.1M
        goto DoneWithDeclSpec;
3207
38.0M
3208
      // If the token is an identifier named "__declspec" and Microsoft
3209
      // extensions are not enabled, it is likely that there will be cascading
3210
      // parse errors if this really is a __declspec attribute. Attempt to
3211
      // recognize that scenario and recover gracefully.
3212
38.0M
      if (!getLangOpts().DeclSpecKeyword && 
Tok.is(tok::identifier)37.8M
&&
3213
37.8M
          Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3214
2
        Diag(Loc, diag::err_ms_attributes_not_enabled);
3215
2
3216
        // The next token should be an open paren. If it is, eat the entire
3217
        // attribute declaration and continue.
3218
2
        if (NextToken().is(tok::l_paren)) {
3219
          // Consume the __declspec identifier.
3220
2
          ConsumeToken();
3221
2
3222
          // Eat the parens and everything between them.
3223
2
          BalancedDelimiterTracker T(*this, tok::l_paren);
3224
2
          if (T.consumeOpen()) {
3225
0
            assert(false && "Not a left paren?");
3226
0
            return;
3227
0
          }
3228
2
          T.skipToEnd();
3229
2
          continue;
3230
2
        }
3231
2
      }
3232
38.0M
3233
      // In C++, check to see if this is a scope specifier like foo::bar::, if
3234
      // so handle it as such.  This is important for ctor parsing.
3235
38.0M
      if (getLangOpts().CPlusPlus) {
3236
5.82M
        if (TryAnnotateCXXScopeToken(EnteringContext)) {
3237
24
          DS.SetTypeSpecError();
3238
24
          goto DoneWithDeclSpec;
3239
24
        }
3240
5.82M
        if (!Tok.is(tok::identifier))
3241
695k
          continue;
3242
37.3M
      }
3243
37.3M
3244
      // Check for need to substitute AltiVec keyword tokens.
3245
37.3M
      if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3246
304k
        break;
3247
37.0M
3248
      // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3249
      //                allow the use of a typedef name as a type specifier.
3250
37.0M
      if (DS.isTypeAltiVecVector())
3251
6.67k
        goto DoneWithDeclSpec;
3252
37.0M
3253
37.0M
      if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3254
146k
          isObjCInstancetype()) {
3255
145k
        ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3256
145k
        assert(TypeRep);
3257
145k
        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3258
145k
                                       DiagID, TypeRep, Policy);
3259
145k
        if (isInvalid)
3260
0
          break;
3261
145k
3262
145k
        DS.SetRangeEnd(Loc);
3263
145k
        ConsumeToken();
3264
145k
        continue;
3265
145k
      }
3266
36.9M
3267
      // If we're in a context where the identifier could be a class name,
3268
      // check whether this is a constructor declaration.
3269
36.9M
      if (getLangOpts().CPlusPlus && 
DSContext == DeclSpecContext::DSC_class5.07M
&&
3270
1.34M
          Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3271
322k
          isConstructorDeclarator(/*Unqualified*/true))
3272
219k
        goto DoneWithDeclSpec;
3273
36.6M
3274
36.6M
      ParsedType TypeRep = Actions.getTypeName(
3275
36.6M
          *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3276
36.6M
          false, false, nullptr, false, false,
3277
36.6M
          isClassTemplateDeductionContext(DSContext));
3278
36.6M
3279
      // If this is not a typedef name, don't parse it as part of the declspec,
3280
      // it must be an implicit int or an error.
3281
36.6M
      if (!TypeRep) {
3282
1.15k
        if (TryAnnotateTypeConstraint())
3283
0
          goto DoneWithDeclSpec;
3284
1.15k
        if (Tok.isNot(tok::identifier))
3285
14
          continue;
3286
1.14k
        ParsedAttributesWithRange Attrs(AttrFactory);
3287
1.14k
        if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3288
839
          if (!Attrs.empty()) {
3289
0
            AttrsLastTime = true;
3290
0
            attrs.takeAllFrom(Attrs);
3291
0
          }
3292
839
          continue;
3293
839
        }
3294
302
        goto DoneWithDeclSpec;
3295
302
      }
3296
36.6M
3297
      // Likewise, if this is a context where the identifier could be a template
3298
      // name, check whether this is a deduction guide declaration.
3299
36.6M
      if (getLangOpts().CPlusPlus17 &&
3300
184k
          (DSContext == DeclSpecContext::DSC_class ||
3301
153k
           DSContext == DeclSpecContext::DSC_top_level) &&
3302
75.4k
          Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3303
75.4k
                                       Tok.getLocation()) &&
3304
564
          isConstructorDeclarator(/*Unqualified*/ true,
3305
564
                                  /*DeductionGuide*/ true))
3306
402
        goto DoneWithDeclSpec;
3307
36.6M
3308
36.6M
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3309
36.6M
                                     DiagID, TypeRep, Policy);
3310
36.6M
      if (isInvalid)
3311
0
        break;
3312
36.6M
3313
36.6M
      DS.SetRangeEnd(Tok.getLocation());
3314
36.6M
      ConsumeToken(); // The identifier
3315
36.6M
3316
      // Objective-C supports type arguments and protocol references
3317
      // following an Objective-C object or object pointer
3318
      // type. Handle either one of them.
3319
36.6M
      if (Tok.is(tok::less) && 
getLangOpts().ObjC68.7k
) {
3320
68.7k
        SourceLocation NewEndLoc;
3321
68.7k
        TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3322
68.7k
                                  Loc, TypeRep, /*consumeLastToken=*/true,
3323
68.7k
                                  NewEndLoc);
3324
68.7k
        if (NewTypeRep.isUsable()) {
3325
68.7k
          DS.UpdateTypeRep(NewTypeRep.get());
3326
68.7k
          DS.SetRangeEnd(NewEndLoc);
3327
68.7k
        }
3328
68.7k
      }
3329
36.6M
3330
      // Need to support trailing type qualifiers (e.g. "id<p> const").
3331
      // If a type specifier follows, it will be diagnosed elsewhere.
3332
36.6M
      continue;
3333
36.6M
    }
3334
36.6M
3335
      // type-name or placeholder-specifier
3336
554k
    case tok::annot_template_id: {
3337
554k
      TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3338
554k
3339
554k
      if (TemplateId->hasInvalidName()) {
3340
0
        DS.SetTypeSpecError();
3341
0
        break;
3342
0
      }
3343
554k
3344
554k
      if (TemplateId->Kind == TNK_Concept_template) {
3345
        // If we've already diagnosed that this type-constraint has invalid
3346
        // arguemnts, drop it and just form 'auto' or 'decltype(auto)'.
3347
111
        if (TemplateId->hasInvalidArgs())
3348
0
          TemplateId = nullptr;
3349
111
3350
111
        if (NextToken().is(tok::identifier)) {
3351
1
          Diag(Loc, diag::err_placeholder_expected_auto_or_decltype_auto)
3352
1
              << FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
3353
          // Attempt to continue as if 'auto' was placed here.
3354
1
          isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3355
1
                                         TemplateId, Policy);
3356
1
          break;
3357
1
        }
3358
110
        if (!NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
3359
0
            goto DoneWithDeclSpec;
3360
110
        ConsumeAnnotationToken();
3361
110
        SourceLocation AutoLoc = Tok.getLocation();
3362
110
        if (TryConsumeToken(tok::kw_decltype)) {
3363
9
          BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3364
9
          if (Tracker.consumeOpen()) {
3365
            // Something like `void foo(Iterator decltype i)`
3366
1
            Diag(Tok, diag::err_expected) << tok::l_paren;
3367
8
          } else {
3368
8
            if (!TryConsumeToken(tok::kw_auto)) {
3369
              // Something like `void foo(Iterator decltype(int) i)`
3370
1
              Tracker.skipToEnd();
3371
1
              Diag(Tok, diag::err_placeholder_expected_auto_or_decltype_auto)
3372
1
                << FixItHint::CreateReplacement(SourceRange(AutoLoc,
3373
1
                                                            Tok.getLocation()),
3374
1
                                                "auto");
3375
7
            } else {
3376
7
              Tracker.consumeClose();
3377
7
            }
3378
8
          }
3379
9
          ConsumedEnd = Tok.getLocation();
3380
          // Even if something went wrong above, continue as if we've seen
3381
          // `decltype(auto)`.
3382
9
          isInvalid = DS.SetTypeSpecType(TST_decltype_auto, Loc, PrevSpec,
3383
9
                                         DiagID, TemplateId, Policy);
3384
101
        } else {
3385
101
          isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3386
101
                                         TemplateId, Policy);
3387
101
        }
3388
110
        break;
3389
110
      }
3390
554k
3391
554k
      if (TemplateId->Kind != TNK_Type_template &&
3392
56
          TemplateId->Kind != TNK_Undeclared_template) {
3393
        // This template-id does not refer to a type name, so we're
3394
        // done with the type-specifiers.
3395
10
        goto DoneWithDeclSpec;
3396
10
      }
3397
554k
3398
      // If we're in a context where the template-id could be a
3399
      // constructor name or specialization, check whether this is a
3400
      // constructor declaration.
3401
554k
      if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3402
61.8k
          Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3403
11.1k
          isConstructorDeclarator(/*Unqualified=*/true))
3404
10
        goto DoneWithDeclSpec;
3405
554k
3406
      // Turn the template-id annotation token into a type annotation
3407
      // token, then try again to parse it as a type-specifier.
3408
554k
      CXXScopeSpec SS;
3409
554k
      AnnotateTemplateIdTokenAsType(SS);
3410
554k
      continue;
3411
554k
    }
3412
554k
3413
    // GNU attributes support.
3414
11.6M
    case tok::kw___attribute:
3415
11.6M
      ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3416
11.6M
      continue;
3417
554k
3418
    // Microsoft declspec support.
3419
6.19k
    case tok::kw___declspec:
3420
6.19k
      ParseMicrosoftDeclSpecs(DS.getAttributes());
3421
6.19k
      continue;
3422
554k
3423
    // Microsoft single token adornments.
3424
14
    case tok::kw___forceinline: {
3425
14
      isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3426
14
      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3427
14
      SourceLocation AttrNameLoc = Tok.getLocation();
3428
14
      DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3429
14
                                nullptr, 0, ParsedAttr::AS_Keyword);
3430
14
      break;
3431
554k
    }
3432
554k
3433
117
    case tok::kw___unaligned:
3434
117
      isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3435
117
                                 getLangOpts());
3436
117
      break;
3437
554k
3438
734
    case tok::kw___sptr:
3439
734
    case tok::kw___uptr:
3440
734
    case tok::kw___ptr64:
3441
734
    case tok::kw___ptr32:
3442
734
    case tok::kw___w64:
3443
734
    case tok::kw___cdecl:
3444
734
    case tok::kw___stdcall:
3445
734
    case tok::kw___fastcall:
3446
734
    case tok::kw___thiscall:
3447
734
    case tok::kw___regcall:
3448
734
    case tok::kw___vectorcall:
3449
734
      ParseMicrosoftTypeAttributes(DS.getAttributes());
3450
734
      continue;
3451
734
3452
    // Borland single token adornments.
3453
14
    case tok::kw___pascal:
3454
14
      ParseBorlandTypeAttributes(DS.getAttributes());
3455
14
      continue;
3456
734
3457
    // OpenCL single token adornments.
3458
834
    case tok::kw___kernel:
3459
834
      ParseOpenCLKernelAttributes(DS.getAttributes());
3460
834
      continue;
3461
734
3462
    // Nullability type specifiers.
3463
486k
    case tok::kw__Nonnull:
3464
486k
    case tok::kw__Nullable:
3465
486k
    case tok::kw__Null_unspecified:
3466
486k
      ParseNullabilityTypeSpecifiers(DS.getAttributes());
3467
486k
      continue;
3468
486k
3469
    // Objective-C 'kindof' types.
3470
1.51k
    case tok::kw___kindof:
3471
1.51k
      DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3472
1.51k
                                nullptr, 0, ParsedAttr::AS_Keyword);
3473
1.51k
      (void)ConsumeToken();
3474
1.51k
      continue;
3475
486k
3476
    // storage-class-specifier
3477
2.20M
    case tok::kw_typedef:
3478
2.20M
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3479
2.20M
                                         PrevSpec, DiagID, Policy);
3480
2.20M
      isStorageClass = true;
3481
2.20M
      break;
3482
2.55M
    case tok::kw_extern:
3483
2.55M
      if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3484
2
        Diag(Tok, diag::ext_thread_before) << "extern";
3485
2.55M
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3486
2.55M
                                         PrevSpec, DiagID, Policy);
3487
2.55M
      isStorageClass = true;
3488
2.55M
      break;
3489
66
    case tok::kw___private_extern__:
3490
66
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3491
66
                                         Loc, PrevSpec, DiagID, Policy);
3492
66
      isStorageClass = true;
3493
66
      break;
3494
9.75M
    case tok::kw_static:
3495
9.75M
      if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3496
11
        Diag(Tok, diag::ext_thread_before) << "static";
3497
9.75M
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3498
9.75M
                                         PrevSpec, DiagID, Policy);
3499
9.75M
      isStorageClass = true;
3500
9.75M
      break;
3501
29.5k
    case tok::kw_auto:
3502
29.5k
      if (getLangOpts().CPlusPlus11) {
3503
29.4k
        if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3504
27
          isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3505
27
                                             PrevSpec, DiagID, Policy);
3506
27
          if (!isInvalid)
3507
27
            Diag(Tok, diag::ext_auto_storage_class)
3508
27
              << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3509
27
        } else
3510
29.3k
          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3511
29.3k
                                         DiagID, Policy);
3512
29.4k
      } else
3513
136
        isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3514
136
                                           PrevSpec, DiagID, Policy);
3515
29.5k
      isStorageClass = true;
3516
29.5k
      break;
3517
35
    case tok::kw___auto_type:
3518
35
      Diag(Tok, diag::ext_auto_type);
3519
35
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3520
35
                                     DiagID, Policy);
3521
35
      break;
3522
678
    case tok::kw_register:
3523
678
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3524
678
                                         PrevSpec, DiagID, Policy);
3525
678
      isStorageClass = true;
3526
678
      break;
3527
2.84k
    case tok::kw_mutable:
3528
2.84k
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3529
2.84k
                                         PrevSpec, DiagID, Policy);
3530
2.84k
      isStorageClass = true;
3531
2.84k
      break;
3532
284
    case tok::kw___thread:
3533
284
      isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3534
284
                                               PrevSpec, DiagID);
3535
284
      isStorageClass = true;
3536
284
      break;
3537
524
    case tok::kw_thread_local:
3538
524
      isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3539
524
                                               PrevSpec, DiagID);
3540
524
      isStorageClass = true;
3541
524
      break;
3542
98
    case tok::kw__Thread_local:
3543
98
      if (!getLangOpts().C11)
3544
77
        Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3545
98
      isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3546
98
                                               Loc, PrevSpec, DiagID);
3547
98
      isStorageClass = true;
3548
98
      break;
3549
486k
3550
    // function-specifier
3551
9.82M
    case tok::kw_inline:
3552
9.82M
      isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3553
9.82M
      break;
3554
50.4k
    case tok::kw_virtual:
3555
      // C++ for OpenCL does not allow virtual function qualifier, to avoid
3556
      // function pointers restricted in OpenCL v2.0 s6.9.a.
3557
50.4k
      if (getLangOpts().OpenCLCPlusPlus) {
3558
3
        DiagID = diag::err_openclcxx_virtual_function;
3559
3
        PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3560
3
        isInvalid = true;
3561
3
      }
3562
50.4k
      else {
3563
50.4k
        isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3564
50.4k
      }
3565
50.4k
      break;
3566
58.7k
    case tok::kw_explicit: {
3567
58.7k
      SourceLocation ExplicitLoc = Loc;
3568
58.7k
      SourceLocation CloseParenLoc;
3569
58.7k
      ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
3570
58.7k
      ConsumedEnd = ExplicitLoc;
3571
58.7k
      ConsumeToken(); // kw_explicit
3572
58.7k
      if (Tok.is(tok::l_paren)) {
3573
125
        if (getLangOpts().CPlusPlus20 || 
isExplicitBool() == TPResult::True37
) {
3574
119
          Diag(Tok.getLocation(), getLangOpts().CPlusPlus20
3575
88
                                      ? diag::warn_cxx17_compat_explicit_bool
3576
31
                                      : diag::ext_explicit_bool);
3577
119
3578
119
          ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
3579
119
          BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3580
119
          Tracker.consumeOpen();
3581
119
          ExplicitExpr = ParseConstantExpression();
3582
119
          ConsumedEnd = Tok.getLocation();
3583
119
          if (ExplicitExpr.isUsable()) {
3584
110
            CloseParenLoc = Tok.getLocation();
3585
110
            Tracker.consumeClose();
3586
110
            ExplicitSpec =
3587
110
                Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
3588
110
          } else
3589
9
            Tracker.skipToEnd();
3590
6
        } else {
3591
6
          Diag(Tok.getLocation(), diag::warn_cxx20_compat_explicit_bool);
3592
6
        }
3593
125
      }
3594
58.7k
      isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
3595
58.7k
                                             ExplicitSpec, CloseParenLoc);
3596
58.7k
      break;
3597
486k
    }
3598
66
    case tok::kw__Noreturn:
3599
66
      if (!getLangOpts().C11)
3600
40
        Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3601
66
      isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3602
66
      break;
3603
486k
3604
    // alignment-specifier
3605
1.18k
    case tok::kw__Alignas:
3606
1.18k
      if (!getLangOpts().C11)
3607
1.14k
        Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3608
1.18k
      ParseAlignmentSpecifier(DS.getAttributes());
3609
1.18k
      continue;
3610
486k
3611
    // friend
3612
49.2k
    case tok::kw_friend:
3613
49.2k
      if (DSContext == DeclSpecContext::DSC_class)
3614
49.2k
        isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3615
15
      else {
3616
15
        PrevSpec = ""; // not actually used by the diagnostic
3617
15
        DiagID = diag::err_friend_invalid_in_context;
3618
15
        isInvalid = true;
3619
15
      }
3620
49.2k
      break;
3621
486k
3622
    // Modules
3623
52
    case tok::kw___module_private__:
3624
52
      isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3625
52
      break;
3626
486k
3627
    // constexpr, consteval, constinit specifiers
3628
287k
    case tok::kw_constexpr:
3629
287k
      isInvalid = DS.SetConstexprSpec(CSK_constexpr, Loc, PrevSpec, DiagID);
3630
287k
      break;
3631
115
    case tok::kw_consteval:
3632
115
      isInvalid = DS.SetConstexprSpec(CSK_consteval, Loc, PrevSpec, DiagID);
3633
115
      break;
3634
72
    case tok::kw_constinit:
3635
72
      isInvalid = DS.SetConstexprSpec(CSK_constinit, Loc, PrevSpec, DiagID);
3636
72
      break;
3637
486k
3638
    // type-specifier
3639
347k
    case tok::kw_short:
3640
347k
      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3641
347k
                                      DiagID, Policy);
3642
347k
      break;
3643
836k
    case tok::kw_long:
3644
836k
      if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
3645
602k
        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3646
602k
                                        DiagID, Policy);
3647
233k
      else
3648
233k
        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3649
233k
                                        DiagID, Policy);
3650
836k
      break;
3651
2.68k
    case tok::kw___int64:
3652
2.68k
        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3653
2.68k
                                        DiagID, Policy);
3654
2.68k
      break;
3655
144k
    case tok::kw_signed:
3656
144k
      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3657
144k
                                     DiagID);
3658
144k
      break;
3659
848k
    case tok::kw_unsigned:
3660
848k
      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3661
848k
                                     DiagID);
3662
848k
      break;
3663
7.76k
    case tok::kw__Complex:
3664
7.76k
      if (!getLangOpts().C99)
3665
2.16k
        Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3666
7.76k
      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3667
7.76k
                                        DiagID);
3668
7.76k
      break;
3669
4
    case tok::kw__Imaginary:
3670
4
      if (!getLangOpts().C99)
3671
2
        Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3672
4
      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3673
4
                                        DiagID);
3674
4
      break;
3675
2.73M
    case tok::kw_void:
3676
2.73M
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3677
2.73M
                                     DiagID, Policy);
3678
2.73M
      break;
3679
1.11M
    case tok::kw_char:
3680
1.11M
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3681
1.11M
                                     DiagID, Policy);
3682
1.11M
      break;
3683
2.36M
    case tok::kw_int:
3684
2.36M
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3685
2.36M
                                     DiagID, Policy);
3686
2.36M
      break;
3687
905
    case tok::kw__ExtInt: {
3688
905
      ExprResult ER = ParseExtIntegerArgument();
3689
905
      if (ER.isInvalid())
3690
3
        continue;
3691
902
      isInvalid = DS.SetExtIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
3692
902
      ConsumedEnd = PrevTokLocation;
3693
902
      break;
3694
902
    }
3695
6.17k
    case tok::kw___int128:
3696
6.17k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3697
6.17k
                                     DiagID, Policy);
3698
6.17k
      break;
3699
21.6k
    case tok::kw_half:
3700
21.6k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3701
21.6k
                                     DiagID, Policy);
3702
21.6k
      break;
3703
451
    case tok::kw___bf16:
3704
451
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec,
3705
451
                                     DiagID, Policy);
3706
451
      break;
3707
248k
    case tok::kw_float:
3708
248k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3709
248k
                                     DiagID, Policy);
3710
248k
      break;
3711
334k
    case tok::kw_double:
3712
334k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3713
334k
                                     DiagID, Policy);
3714
334k
      break;
3715
264
    case tok::kw__Float16:
3716
264
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3717
264
                                     DiagID, Policy);
3718
264
      break;
3719
1.03k
    case tok::kw__Accum:
3720
1.03k
      if (!getLangOpts().FixedPoint) {
3721
9
        SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3722
1.02k
      } else {
3723
1.02k
        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3724
1.02k
                                       DiagID, Policy);
3725
1.02k
      }
3726
1.03k
      break;
3727
540
    case tok::kw__Fract:
3728
540
      if (!getLangOpts().FixedPoint) {
3729
0
        SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3730
540
      } else {
3731
540
        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3732
540
                                       DiagID, Policy);
3733
540
      }
3734
540
      break;
3735
557
    case tok::kw__Sat:
3736
557
      if (!getLangOpts().FixedPoint) {
3737
0
        SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3738
557
      } else {
3739
557
        isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3740
557
      }
3741
557
      break;
3742
411
    case tok::kw___float128:
3743
411
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3744
411
                                     DiagID, Policy);
3745
411
      break;
3746
124k
    case tok::kw_wchar_t:
3747
124k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3748
124k
                                     DiagID, Policy);
3749
124k
      break;
3750
52
    case tok::kw_char8_t:
3751
52
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3752
52
                                     DiagID, Policy);
3753
52
      break;
3754
9.09k
    case tok::kw_char16_t:
3755
9.09k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3756
9.09k
                                     DiagID, Policy);
3757
9.09k
      break;
3758
9.09k
    case tok::kw_char32_t:
3759
9.09k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3760
9.09k
                                     DiagID, Policy);
3761
9.09k
      break;
3762
580k
    case tok::kw_bool:
3763
580k
    case tok::kw__Bool:
3764
580k
      if (Tok.is(tok::kw__Bool) && 
!getLangOpts().C99111k
)
3765
2
        Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3766
580k
3767
580k
      if (Tok.is(tok::kw_bool) &&
3768
468k
          DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3769
3
          DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3770
3
        PrevSpec = ""; // Not used by the diagnostic.
3771
3
        DiagID = diag::err_bool_redeclaration;
3772
        // For better error recovery.
3773
3
        Tok.setKind(tok::identifier);
3774
3
        isInvalid = true;
3775
580k
      } else {
3776
580k
        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3777
580k
                                       DiagID, Policy);
3778
580k
      }
3779
580k
      break;
3780
5
    case tok::kw__Decimal32:
3781
5
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3782
5
                                     DiagID, Policy);
3783
5
      break;
3784
0
    case tok::kw__Decimal64:
3785
0
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3786
0
                                     DiagID, Policy);
3787
0
      break;
3788
1
    case tok::kw__Decimal128:
3789
1
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3790
1
                                     DiagID, Policy);
3791
1
      break;
3792
329k
    case tok::kw___vector:
3793
329k
      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3794
329k
      break;
3795
12
    case tok::kw___pixel:
3796
12
      isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3797
12
      break;
3798
16.2k
    case tok::kw___bool:
3799
16.2k
      isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3800
16.2k
      break;
3801
120
    case tok::kw_pipe:
3802
120
      if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200 &&
3803
34
                                    !getLangOpts().OpenCLCPlusPlus)) {
3804
        // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3805
        // support the "pipe" word as identifier.
3806
1
        Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3807
1
        goto DoneWithDeclSpec;
3808
1
      }
3809
119
      isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3810
119
      break;
3811
119
#define GENERIC_IMAGE_TYPE(ImgType, Id) \
3812
8.43k
  case tok::kw_##ImgType##_t: \
3813
8.43k
    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3814
8.43k
                                   DiagID, Policy); \
3815
8.43k
    break;
3816
119
#include "clang/Basic/OpenCLImageTypes.def"
3817
62
    case tok::kw___unknown_anytype:
3818
62
      isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3819
62
                                     PrevSpec, DiagID, Policy);
3820
62
      break;
3821
119
3822
    // class-specifier:
3823
1.91M
    case tok::kw_class:
3824
1.91M
    case tok::kw_struct:
3825
1.91M
    case tok::kw___interface:
3826
1.91M
    case tok::kw_union: {
3827
1.91M
      tok::TokenKind Kind = Tok.getKind();
3828
1.91M
      ConsumeToken();
3829
1.91M
3830
      // These are attributes following class specifiers.
3831
      // To produce better diagnostic, we parse them when
3832
      // parsing class specifier.
3833
1.91M
      ParsedAttributesWithRange Attributes(AttrFactory);
3834
1.91M
      ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3835
1.91M
                          EnteringContext, DSContext, Attributes);
3836
1.91M
3837
      // If there are attributes following class specifier,
3838
      // take them over and handle them here.
3839
1.91M
      if (!Attributes.empty()) {
3840
0
        AttrsLastTime = true;
3841
0
        attrs.takeAllFrom(Attributes);
3842
0
      }
3843
1.91M
      continue;
3844
1.91M
    }
3845
1.91M
3846
    // enum-specifier:
3847
700k
    case tok::kw_enum:
3848
700k
      ConsumeToken();
3849
700k
      ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3850
700k
      continue;
3851
1.91M
3852
    // cv-qualifier:
3853
3.65M
    case tok::kw_const:
3854
3.65M
      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3855
3.65M
                                 getLangOpts());
3856
3.65M
      break;
3857
98.8k
    case tok::kw_volatile:
3858
98.8k
      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3859
98.8k
                                 getLangOpts());
3860
98.8k
      break;
3861
288
    case tok::kw_restrict:
3862
288
      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3863
288
                                 getLangOpts());
3864
288
      break;
3865
1.91M
3866
    // C++ typename-specifier:
3867
350k
    case tok::kw_typename:
3868
350k
      if (TryAnnotateTypeOrScopeToken()) {
3869
3
        DS.SetTypeSpecError();
3870
3
        goto DoneWithDeclSpec;
3871
3
      }
3872
350k
      if (!Tok.is(tok::kw_typename))
3873
350k
        continue;
3874
0
      break;
3875
0
3876
    // GNU typeof support.
3877
2.97k
    case tok::kw_typeof:
3878
2.97k
      ParseTypeofSpecifier(DS);
3879
2.97k
      continue;
3880
0
3881
31.4k
    case tok::annot_decltype:
3882
31.4k
      ParseDecltypeSpecifier(DS);
3883
31.4k
      continue;
3884
0
3885
1
    case tok::annot_pragma_pack:
3886
1
      HandlePragmaPack();
3887
1
      continue;
3888
0
3889
0
    case tok::annot_pragma_ms_pragma:
3890
0
      HandlePragmaMSPragma();
3891
0
      continue;
3892
0
3893
0
    case tok::annot_pragma_ms_vtordisp:
3894
0
      HandlePragmaMSVtorDisp();
3895
0
      continue;
3896
0
3897
0
    case tok::annot_pragma_ms_pointers_to_members:
3898
0
      HandlePragmaMSPointersToMembers();
3899
0
      continue;
3900
0
3901
482
    case tok::kw___underlying_type:
3902
482
      ParseUnderlyingTypeSpecifier(DS);
3903
482
      continue;
3904
0
3905
2.27k
    case tok::kw__Atomic:
3906
      // C11 6.7.2.4/4:
3907
      //   If the _Atomic keyword is immediately followed by a left parenthesis,
3908
      //   it is interpreted as a type specifier (with a type name), not as a
3909
      //   type qualifier.
3910
2.27k
      if (!getLangOpts().C11)
3911
1.15k
        Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3912
2.27k
3913
2.27k
      if (NextToken().is(tok::l_paren)) {
3914
2.17k
        ParseAtomicSpecifier(DS);
3915
2.17k
        continue;
3916
2.17k
      }
3917
101
      isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3918
101
                                 getLangOpts());
3919
101
      break;
3920
101
3921
    // OpenCL address space qualifiers:
3922
451
    case tok::kw___generic:
3923
      // generic address space is introduced only in OpenCL v2.0
3924
      // see OpenCL C Spec v2.0 s6.5.5
3925
451
      if (Actions.getLangOpts().OpenCLVersion < 200 &&
3926
78
          !Actions.getLangOpts().OpenCLCPlusPlus) {
3927
10
        DiagID = diag::err_opencl_unknown_type_specifier;
3928
10
        PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3929
10
        isInvalid = true;
3930
10
        break;
3931
10
      }
3932
441
      LLVM_FALLTHROUGH;
3933
462
    case tok::kw_private:
3934
      // It's fine (but redundant) to check this for __generic on the
3935
      // fallthrough path; we only form the __generic token in OpenCL mode.
3936
462
      if (!getLangOpts().OpenCL)
3937
3
        goto DoneWithDeclSpec;
3938
459
      LLVM_FALLTHROUGH;
3939
41.8k
    case tok::kw___private:
3940
41.8k
    case tok::kw___global:
3941
41.8k
    case tok::kw___local:
3942
41.8k
    case tok::kw___constant:
3943
    // OpenCL access qualifiers:
3944
41.8k
    case tok::kw___read_only:
3945
41.8k
    case tok::kw___write_only:
3946
41.8k
    case tok::kw___read_write:
3947
41.8k
      ParseOpenCLQualifiers(DS.getAttributes());
3948
41.8k
      break;
3949
41.8k
3950
19
    case tok::less:
3951
      // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3952
      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
3953
      // but we support it.
3954
19
      if (DS.hasTypeSpecifier() || 
!getLangOpts().ObjC9
)
3955
12
        goto DoneWithDeclSpec;
3956
7
3957
7
      SourceLocation StartLoc = Tok.getLocation();
3958
7
      SourceLocation EndLoc;
3959
7
      TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3960
7
      if (Type.isUsable()) {
3961
7
        if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3962
7
                               PrevSpec, DiagID, Type.get(),
3963
7
                               Actions.getASTContext().getPrintingPolicy()))
3964
0
          Diag(StartLoc, DiagID) << PrevSpec;
3965
7
3966
7
        DS.SetRangeEnd(EndLoc);
3967
0
      } else {
3968
0
        DS.SetTypeSpecError();
3969
0
      }
3970
7
3971
      // Need to support trailing type qualifiers (e.g. "id<p> const").
3972
      // If a type specifier follows, it will be diagnosed elsewhere.
3973
7
      continue;
3974
39.0M
    }
3975
39.0M
3976
39.0M
    DS.SetRangeEnd(ConsumedEnd.isValid() ? 
ConsumedEnd59.6k
:
Tok.getLocation()38.9M
);
3977
39.0M
3978
    // If the specifier wasn't legal, issue a diagnostic.
3979
39.0M
    if (isInvalid) {
3980
157
      assert(PrevSpec && "Method did not return previous specifier!");
3981
157
      assert(DiagID);
3982
157
3983
157
      if (DiagID == diag::ext_duplicate_declspec ||
3984
157
          DiagID == diag::ext_warn_duplicate_declspec ||
3985
114
          DiagID == diag::err_duplicate_declspec)
3986
45
        Diag(Loc, DiagID) << PrevSpec
3987
45
                          << FixItHint::CreateRemoval(
3988
45
                                 SourceRange(Loc, DS.getEndLoc()));
3989
112
      else if (DiagID == diag::err_opencl_unknown_type_specifier) {
3990
16
        Diag(Loc, DiagID) << getLangOpts().OpenCLCPlusPlus
3991
16
                          << getLangOpts().getOpenCLVersionTuple().getAsString()
3992
16
                          << PrevSpec << isStorageClass;
3993
16
      } else
3994
96
        Diag(Loc, DiagID) << PrevSpec;
3995
157
    }
3996
39.0M
3997
39.0M
    if (DiagID != diag::err_bool_redeclaration && 
ConsumedEnd.isInvalid()39.0M
)
3998
      // After an error the next token can be an annotation token.
3999
38.9M
      ConsumeAnyToken();
4000
39.0M
4001
39.0M
    AttrsLastTime = false;
4002
39.0M
  }
4003
69.9M
}
4004
4005
/// ParseStructDeclaration - Parse a struct declaration without the terminating
4006
/// semicolon.
4007
///
4008
/// Note that a struct declaration refers to a declaration in a struct,
4009
/// not to the declaration of a struct.
4010
///
4011
///       struct-declaration:
4012
/// [C2x]   attributes-specifier-seq[opt]
4013
///           specifier-qualifier-list struct-declarator-list
4014
/// [GNU]   __extension__ struct-declaration
4015
/// [GNU]   specifier-qualifier-list
4016
///       struct-declarator-list:
4017
///         struct-declarator
4018
///         struct-declarator-list ',' struct-declarator
4019
/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
4020
///       struct-declarator:
4021
///         declarator
4022
/// [GNU]   declarator attributes[opt]
4023
///         declarator[opt] ':' constant-expression
4024
/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
4025
///
4026
void Parser::ParseStructDeclaration(
4027
    ParsingDeclSpec &DS,
4028
3.00M
    llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4029
3.00M
4030
3.00M
  if (Tok.is(tok::kw___extension__)) {
4031
    // __extension__ silences extension warnings in the subexpression.
4032
2
    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
4033
2
    ConsumeToken();
4034
2
    return ParseStructDeclaration(DS, FieldsCallback);
4035
2
  }
4036
3.00M
4037
  // Parse leading attributes.
4038
3.00M
  ParsedAttributesWithRange Attrs(AttrFactory);
4039
3.00M
  MaybeParseCXX11Attributes(Attrs);
4040
3.00M
  DS.takeAttributesFrom(Attrs);
4041
3.00M
4042
  // Parse the common specifier-qualifiers-list piece.
4043
3.00M
  ParseSpecifierQualifierList(DS);
4044
3.00M
4045
  // If there are no declarators, this is a free-standing declaration
4046
  // specifier. Let the actions module cope with it.
4047
3.00M
  if (Tok.is(tok::semi)) {
4048
313
    RecordDecl *AnonRecord = nullptr;
4049
313
    Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
4050
313
                                                       DS, AnonRecord);
4051
313
    assert(!AnonRecord && "Did not expect anonymous struct or union here");
4052
313
    DS.complete(TheDecl);
4053
313
    return;
4054
313
  }
4055
3.00M
4056
  // Read struct-declarators until we find the semicolon.
4057
3.00M
  bool FirstDeclarator = true;
4058
3.00M
  SourceLocation CommaLoc;
4059
3.02M
  while (1) {
4060
3.02M
    ParsingFieldDeclarator DeclaratorInfo(*this, DS);
4061
3.02M
    DeclaratorInfo.D.setCommaLoc(CommaLoc);
4062
3.02M
4063
    // Attributes are only allowed here on successive declarators.
4064
3.02M
    if (!FirstDeclarator)
4065
15.8k
      MaybeParseGNUAttributes(DeclaratorInfo.D);
4066
3.02M
4067
    /// struct-declarator: declarator
4068
    /// struct-declarator: declarator[opt] ':' constant-expression
4069
3.02M
    if (Tok.isNot(tok::colon)) {
4070
      // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4071
3.02M
      ColonProtectionRAIIObject X(*this);
4072
3.02M
      ParseDeclarator(DeclaratorInfo.D);
4073
3.02M
    } else
4074
1.80k
      DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4075
3.02M
4076
3.02M
    if (TryConsumeToken(tok::colon)) {
4077
37.8k
      ExprResult Res(ParseConstantExpression());
4078
37.8k
      if (Res.isInvalid())
4079
1
        SkipUntil(tok::semi, StopBeforeMatch);
4080
37.8k
      else
4081
37.8k
        DeclaratorInfo.BitfieldSize = Res.get();
4082
37.8k
    }
4083
3.02M
4084
    // If attributes exist after the declarator, parse them.
4085
3.02M
    MaybeParseGNUAttributes(DeclaratorInfo.D);
4086
3.02M
4087
    // We're done with this declarator;  invoke the callback.
4088
3.02M
    FieldsCallback(DeclaratorInfo);
4089
3.02M
4090
    // If we don't have a comma, it is either the end of the list (a ';')
4091
    // or an error, bail out.
4092
3.02M
    if (!TryConsumeToken(tok::comma, CommaLoc))
4093
3.00M
      return;
4094
15.8k
4095
15.8k
    FirstDeclarator = false;
4096
15.8k
  }
4097
3.00M
}
4098
4099
/// ParseStructUnionBody
4100
///       struct-contents:
4101
///         struct-declaration-list
4102
/// [EXT]   empty
4103
/// [GNU]   "struct-declaration-list" without terminatoring ';'
4104
///       struct-declaration-list:
4105
///         struct-declaration
4106
///         struct-declaration-list struct-declaration
4107
/// [OBC]   '@' 'defs' '(' class-name ')'
4108
///
4109
void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4110
507k
                                  DeclSpec::TST TagType, RecordDecl *TagDecl) {
4111
507k
  PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4112
507k
                                      "parsing struct/union body");
4113
507k
  assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4114
507k
4115
507k
  BalancedDelimiterTracker T(*this, tok::l_brace);
4116
507k
  if (T.consumeOpen())
4117
0
    return;
4118
507k
4119
507k
  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4120
507k
  Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
4121
507k
4122
  // While we still have something to read, read the declarations in the struct.
4123
2.87M
  while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4124
2.37M
         Tok.isNot(tok::eof)) {
4125
    // Each iteration of this loop reads one struct-declaration.
4126
2.37M
4127
    // Check for extraneous top-level semicolon.
4128
2.37M
    if (Tok.is(tok::semi)) {
4129
5
      ConsumeExtraSemi(InsideStruct, TagType);
4130
5
      continue;
4131
5
    }
4132
2.37M
4133
    // Parse _Static_assert declaration.
4134
2.37M
    if (Tok.is(tok::kw__Static_assert)) {
4135
28
      SourceLocation DeclEnd;
4136
28
      ParseStaticAssertDeclaration(DeclEnd);
4137
28
      continue;
4138
28
    }
4139
2.37M
4140
2.37M
    if (Tok.is(tok::annot_pragma_pack)) {
4141
6
      HandlePragmaPack();
4142
6
      continue;
4143
6
    }
4144
2.37M
4145
2.37M
    if (Tok.is(tok::annot_pragma_align)) {
4146
2
      HandlePragmaAlign();
4147
2
      continue;
4148
2
    }
4149
2.37M
4150
2.37M
    if (Tok.is(tok::annot_pragma_openmp)) {
4151
      // Result can be ignored, because it must be always empty.
4152
21
      AccessSpecifier AS = AS_none;
4153
21
      ParsedAttributesWithRange Attrs(AttrFactory);
4154
21
      (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4155
21
      continue;
4156
21
    }
4157
2.37M
4158
2.37M
    if (tok::isPragmaAnnotation(Tok.getKind())) {
4159
2
      Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4160
2
          << DeclSpec::getSpecifierName(
4161
2
                 TagType, Actions.getASTContext().getPrintingPolicy());
4162
2
      ConsumeAnnotationToken();
4163
2
      continue;
4164
2
    }
4165
2.37M
4166
2.37M
    if (!Tok.is(tok::at)) {
4167
2.38M
      auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4168
        // Install the declarator into the current TagDecl.
4169
2.38M
        Decl *Field =
4170
2.38M
            Actions.ActOnField(getCurScope(), TagDecl,
4171
2.38M
                               FD.D.getDeclSpec().getSourceRange().getBegin(),
4172
2.38M
                               FD.D, FD.BitfieldSize);
4173
2.38M
        FD.complete(Field);
4174
2.38M
      };
4175
2.37M
4176
      // Parse all the comma separated declarators.
4177
2.37M
      ParsingDeclSpec DS(*this);
4178
2.37M
      ParseStructDeclaration(DS, CFieldCallback);
4179
8
    } else { // Handle @defs
4180
8
      ConsumeToken();
4181
8
      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4182
4
        Diag(Tok, diag::err_unexpected_at);
4183
4
        SkipUntil(tok::semi);
4184
4
        continue;
4185
4
      }
4186
4
      ConsumeToken();
4187
4
      ExpectAndConsume(tok::l_paren);
4188
4
      if (!Tok.is(tok::identifier)) {
4189
0
        Diag(Tok, diag::err_expected) << tok::identifier;
4190
0
        SkipUntil(tok::semi);
4191
0
        continue;
4192
0
      }
4193
4
      SmallVector<Decl *, 16> Fields;
4194
4
      Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4195
4
                        Tok.getIdentifierInfo(), Fields);
4196
4
      ConsumeToken();
4197
4
      ExpectAndConsume(tok::r_paren);
4198
4
    }
4199
2.37M
4200
2.37M
    if (TryConsumeToken(tok::semi))
4201
2.37M
      continue;
4202
20
4203
20
    if (Tok.is(tok::r_brace)) {
4204
8
      ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4205
8
      break;
4206
8
    }
4207
12
4208
12
    ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4209
    // Skip to end of block or statement to avoid ext-warning on extra ';'.
4210
12
    SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4211
    // If we stopped at a ';', eat it.
4212
12
    TryConsumeToken(tok::semi);
4213
12
  }
4214
507k
4215
507k
  T.consumeClose();
4216
507k
4217
507k
  ParsedAttributes attrs(AttrFactory);
4218
  // If attributes exist after struct contents, parse them.
4219
507k
  MaybeParseGNUAttributes(attrs);
4220
507k
4221
507k
  SmallVector<Decl *, 32> FieldDecls(TagDecl->field_begin(),
4222
507k
                                     TagDecl->field_end());
4223
507k
4224
507k
  Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4225
507k
                      T.getOpenLocation(), T.getCloseLocation(), attrs);
4226
507k
  StructScope.Exit();
4227
507k
  Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4228
507k
}
4229
4230
/// ParseEnumSpecifier
4231
///       enum-specifier: [C99 6.7.2.2]
4232
///         'enum' identifier[opt] '{' enumerator-list '}'
4233
///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4234
/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4235
///                                                 '}' attributes[opt]
4236
/// [MS]    'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4237
///                                                 '}'
4238
///         'enum' identifier
4239
/// [GNU]   'enum' attributes[opt] identifier
4240
///
4241
/// [C++11] enum-head '{' enumerator-list[opt] '}'
4242
/// [C++11] enum-head '{' enumerator-list ','  '}'
4243
///
4244
///       enum-head: [C++11]
4245
///         enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4246
///         enum-key attribute-specifier-seq[opt] nested-name-specifier
4247
///             identifier enum-base[opt]
4248
///
4249
///       enum-key: [C++11]
4250
///         'enum'
4251
///         'enum' 'class'
4252
///         'enum' 'struct'
4253
///
4254
///       enum-base: [C++11]
4255
///         ':' type-specifier-seq
4256
///
4257
/// [C++] elaborated-type-specifier:
4258
/// [C++]   'enum' nested-name-specifier[opt] identifier
4259
///
4260
void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4261
                                const ParsedTemplateInfo &TemplateInfo,
4262
700k
                                AccessSpecifier AS, DeclSpecContext DSC) {
4263
  // Parse the tag portion of this.
4264
700k
  if (Tok.is(tok::code_completion)) {
4265
    // Code completion for an enum name.
4266
2
    Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
4267
2
    return cutOffParsing();
4268
2
  }
4269
700k
4270
  // If attributes exist after tag, parse them.
4271
700k
  ParsedAttributesWithRange attrs(AttrFactory);
4272
700k
  MaybeParseGNUAttributes(attrs);
4273
700k
  MaybeParseCXX11Attributes(attrs);
4274
700k
  MaybeParseMicrosoftDeclSpecs(attrs);
4275
700k
4276
700k
  SourceLocation ScopedEnumKWLoc;
4277
700k
  bool IsScopedUsingClassTag = false;
4278
700k
4279
  // In C++11, recognize 'enum class' and 'enum struct'.
4280
700k
  if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4281
2.12k
    Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4282
69
                                        : diag::ext_scoped_enum);
4283
2.19k
    IsScopedUsingClassTag = Tok.is(tok::kw_class);
4284
2.19k
    ScopedEnumKWLoc = ConsumeToken();
4285
2.19k
4286
    // Attributes are not allowed between these keywords.  Diagnose,
4287
    // but then just treat them like they appeared in the right place.
4288
2.19k
    ProhibitAttributes(attrs);
4289
2.19k
4290
    // They are allowed afterwards, though.
4291
2.19k
    MaybeParseGNUAttributes(attrs);
4292
2.19k
    MaybeParseCXX11Attributes(attrs);
4293
2.19k
    MaybeParseMicrosoftDeclSpecs(attrs);
4294
2.19k
  }
4295
700k
4296
  // C++11 [temp.explicit]p12:
4297
  //   The usual access controls do not apply to names used to specify
4298
  //   explicit instantiations.
4299
  // We extend this to also cover explicit specializations.  Note that
4300
  // we don't suppress if this turns out to be an elaborated type
4301
  // specifier.
4302
700k
  bool shouldDelayDiagsInTag =
4303
700k
    (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4304
700k
     TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4305
700k
  SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4306
700k
4307
  // Determine whether this declaration is permitted to have an enum-base.
4308
700k
  AllowDefiningTypeSpec AllowEnumSpecifier =
4309
700k
      isDefiningTypeSpecifierContext(DSC);
4310
700k
  bool CanBeOpaqueEnumDeclaration =
4311
700k
      DS.isEmpty() && 
isOpaqueEnumDeclarationContext(DSC)589k
;
4312
700k
  bool CanHaveEnumBase = (getLangOpts().CPlusPlus11 || 
getLangOpts().ObjC607k
||
4313
6.15k
                          getLangOpts().MicrosoftExt) &&
4314
694k
                         (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes ||
4315
46
                          CanBeOpaqueEnumDeclaration);
4316
700k
4317
700k
  CXXScopeSpec &SS = DS.getTypeSpecScope();
4318
700k
  if (getLangOpts().CPlusPlus) {
4319
    // "enum foo : bar;" is not a potential typo for "enum foo::bar;".
4320
93.5k
    ColonProtectionRAIIObject X(*this);
4321
93.5k
4322
93.5k
    CXXScopeSpec Spec;
4323
93.5k
    if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
4324
93.5k
                                       /*ObjectHadErrors=*/false,
4325
93.5k
                                       /*EnteringContext=*/true))
4326
0
      return;
4327
93.5k
4328
93.5k
    if (Spec.isSet() && 
Tok.isNot(tok::identifier)176
) {
4329
6
      Diag(Tok, diag::err_expected) << tok::identifier;
4330
6
      if (Tok.isNot(tok::l_brace)) {
4331
        // Has no name and is not a definition.
4332
        // Skip the rest of this declarator, up until the comma or semicolon.
4333
6
        SkipUntil(tok::comma, StopAtSemi);
4334
6
        return;
4335
6
      }
4336
93.5k
    }
4337
93.5k
4338
93.5k
    SS = Spec;
4339
93.5k
  }
4340
700k
4341
  // Must have either 'enum name' or 'enum {...}' or (rarely) 'enum : T { ... }'.
4342
700k
  if (Tok.isNot(tok::identifier) && 
Tok.isNot(tok::l_brace)492k
&&
4343
39.2k
      Tok.isNot(tok::colon)) {
4344
3
    Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4345
3
4346
    // Skip the rest of this declarator, up until the comma or semicolon.
4347
3
    SkipUntil(tok::comma, StopAtSemi);
4348
3
    return;
4349
3
  }
4350
700k
4351
  // If an identifier is present, consume and remember it.
4352
700k
  IdentifierInfo *Name = nullptr;
4353
700k
  SourceLocation NameLoc;
4354
700k
  if (Tok.is(tok::identifier)) {
4355
207k
    Name = Tok.getIdentifierInfo();
4356
207k
    NameLoc = ConsumeToken();
4357
207k
  }
4358
700k
4359
700k
  if (!Name && 
ScopedEnumKWLoc.isValid()492k
) {
4360
    // C++0x 7.2p2: The optional identifier shall not be omitted in the
4361
    // declaration of a scoped enumeration.
4362
8
    Diag(Tok, diag::err_scoped_enum_missing_identifier);
4363
8
    ScopedEnumKWLoc = SourceLocation();
4364
8
    IsScopedUsingClassTag = false;
4365
8
  }
4366
700k
4367
  // Okay, end the suppression area.  We'll decide whether to emit the
4368
  // diagnostics in a second.
4369
700k
  if (shouldDelayDiagsInTag)
4370
66
    diagsFromTag.done();
4371
700k
4372
700k
  TypeResult BaseType;
4373
700k
  SourceRange BaseRange;
4374
700k
4375
700k
  bool CanBeBitfield = (getCurScope()->getFlags() & Scope::ClassScope) &&
4376
11.9k
                       ScopedEnumKWLoc.isInvalid() && 
Name11.7k
;
4377
700k
4378
  // Parse the fixed underlying type.
4379
700k
  if (Tok.is(tok::colon)) {
4380
    // This might be an enum-base or part of some unrelated enclosing context.
4381
    //
4382
    // 'enum E : base' is permitted in two circumstances:
4383
    //
4384
    // 1) As a defining-type-specifier, when followed by '{'.
4385
    // 2) As the sole constituent of a complete declaration -- when DS is empty
4386
    //    and the next token is ';'.
4387
    //
4388
    // The restriction to defining-type-specifiers is important to allow parsing
4389
    //   a ? new enum E : int{}
4390
    //   _Generic(a, enum E : int{})
4391
    // properly.
4392
    //
4393
    // One additional consideration applies:
4394
    //
4395
    // C++ [dcl.enum]p1:
4396
    //   A ':' following "enum nested-name-specifier[opt] identifier" within
4397
    //   the decl-specifier-seq of a member-declaration is parsed as part of
4398
    //   an enum-base.
4399
    //
4400
    // Other language modes supporting enumerations with fixed underlying types
4401
    // do not have clear rules on this, so we disambiguate to determine whether
4402
    // the tokens form a bit-field width or an enum-base.
4403
225k
4404
225k
    if (CanBeBitfield && 
!isEnumBase(CanBeOpaqueEnumDeclaration)144
) {
4405
      // Outside C++11, do not interpret the tokens as an enum-base if they do
4406
      // not make sense as one. In C++11, it's an error if this happens.
4407
19
      if (getLangOpts().CPlusPlus11)
4408
13
        Diag(Tok.getLocation(), diag::err_anonymous_enum_bitfield);
4409
225k
    } else if (CanHaveEnumBase || 
!ColonIsSacred69
) {
4410
225k
      SourceLocation ColonLoc = ConsumeToken();
4411
225k
4412
      // Parse a type-specifier-seq as a type. We can't just ParseTypeName here,
4413
      // because under -fms-extensions,
4414
      //   enum E : int *p;
4415
      // declares 'enum E : int; E *p;' not 'enum E : int*; E p;'.
4416
225k
      DeclSpec DS(AttrFactory);
4417
225k
      ParseSpecifierQualifierList(DS, AS, DeclSpecContext::DSC_type_specifier);
4418
225k
      Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
4419
225k
      BaseType = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
4420
225k
4421
225k
      BaseRange = SourceRange(ColonLoc, DeclaratorInfo.getSourceRange().getEnd());
4422
225k
4423
225k
      if (!getLangOpts().ObjC) {
4424
3.56k
        if (getLangOpts().CPlusPlus11)
4425
3.51k
          Diag(ColonLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type)
4426
3.51k
              << BaseRange;
4427
54
        else if (getLangOpts().CPlusPlus)
4428
12
          Diag(ColonLoc, diag::ext_cxx11_enum_fixed_underlying_type)
4429
12
              << BaseRange;
4430
42
        else if (getLangOpts().MicrosoftExt)
4431
7
          Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
4432
7
              << BaseRange;
4433
35
        else
4434
35
          Diag(ColonLoc, diag::ext_clang_c_enum_fixed_underlying_type)
4435
35
              << BaseRange;
4436
3.56k
      }
4437
225k
    }
4438
225k
  }
4439
700k
4440
  // There are four options here.  If we have 'friend enum foo;' then this is a
4441
  // friend declaration, and cannot have an accompanying definition. If we have
4442
  // 'enum foo;', then this is a forward declaration.  If we have
4443
  // 'enum foo {...' then this is a definition. Otherwise we have something
4444
  // like 'enum foo xyz', a reference.
4445
  //
4446
  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4447
  // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
4448
  // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
4449
  //
4450
700k
  Sema::TagUseKind TUK;
4451
700k
  if (AllowEnumSpecifier == AllowDefiningTypeSpec::No)
4452
10
    TUK = Sema::TUK_Reference;
4453
700k
  else if (Tok.is(tok::l_brace)) {
4454
601k
    if (DS.isFriendSpecified()) {
4455
4
      Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4456
4
        << SourceRange(DS.getFriendSpecLoc());
4457
4
      ConsumeBrace();
4458
4
      SkipUntil(tok::r_brace, StopAtSemi);
4459
      // Discard any other definition-only pieces.
4460
4
      attrs.clear();
4461
4
      ScopedEnumKWLoc = SourceLocation();
4462
4
      IsScopedUsingClassTag = false;
4463
4
      BaseType = TypeResult();
4464
4
      TUK = Sema::TUK_Friend;
4465
601k
    } else {
4466
601k
      TUK = Sema::TUK_Definition;
4467
601k
    }
4468
98.8k
  } else if (!isTypeSpecifier(DSC) &&
4469
98.8k
             (Tok.is(tok::semi) ||
4470
98.4k
              (Tok.isAtStartOfLine() &&
4471
412
               
!isValidAfterTypeSpecifier(CanBeBitfield)33
))) {
4472
    // An opaque-enum-declaration is required to be standalone (no preceding or
4473
    // following tokens in the declaration). Sema enforces this separately by
4474
    // diagnosing anything else in the DeclSpec.
4475
392
    TUK = DS.isFriendSpecified() ? 
Sema::TUK_Friend20
: Sema::TUK_Declaration;
4476
412
    if (Tok.isNot(tok::semi)) {
4477
      // A semicolon was missing after this declaration. Diagnose and recover.
4478
2
      ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4479
2
      PP.EnterToken(Tok, /*IsReinject=*/true);
4480
2
      Tok.setKind(tok::semi);
4481
2
    }
4482
98.4k
  } else {
4483
98.4k
    TUK = Sema::TUK_Reference;
4484
98.4k
  }
4485
700k
4486
700k
  bool IsElaboratedTypeSpecifier =
4487
700k
      TUK == Sema::TUK_Reference || 
TUK == Sema::TUK_Friend602k
;
4488
700k
4489
  // If this is an elaborated type specifier nested in a larger declaration,
4490
  // and we delayed diagnostics before, just merge them into the current pool.
4491
700k
  if (TUK == Sema::TUK_Reference && 
shouldDelayDiagsInTag98.4k
) {
4492
0
    diagsFromTag.redelay();
4493
0
  }
4494
700k
4495
700k
  MultiTemplateParamsArg TParams;
4496
700k
  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4497
99
      TUK != Sema::TUK_Reference) {
4498
98
    if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4499
      // Skip the rest of this declarator, up until the comma or semicolon.
4500
1
      Diag(Tok, diag::err_enum_template);
4501
1
      SkipUntil(tok::comma, StopAtSemi);
4502
1
      return;
4503
1
    }
4504
97
4505
97
    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4506
      // Enumerations can't be explicitly instantiated.
4507
5
      DS.SetTypeSpecError();
4508
5
      Diag(StartLoc, diag::err_explicit_instantiation_enum);
4509
5
      return;
4510
5
    }
4511
92
4512
92
    assert(TemplateInfo.TemplateParams && "no template parameters");
4513
92
    TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4514
92
                                     TemplateInfo.TemplateParams->size());
4515
92
  }
4516
700k
4517
700k
  if (!Name && 
TUK != Sema::TUK_Definition492k
) {
4518
2
    Diag(Tok, diag::err_enumerator_unnamed_no_def);
4519
2
4520
    // Skip the rest of this declarator, up until the comma or semicolon.
4521
2
    SkipUntil(tok::comma, StopAtSemi);
4522
2
    return;
4523
2
  }
4524
700k
4525
  // An elaborated-type-specifier has a much more constrained grammar:
4526
  //
4527
  //   'enum' nested-name-specifier[opt] identifier
4528
  //
4529
  // If we parsed any other bits, reject them now.
4530
  //
4531
  // MSVC and (for now at least) Objective-C permit a full enum-specifier
4532
  // or opaque-enum-declaration anywhere.
4533
700k
  if (IsElaboratedTypeSpecifier && 
!getLangOpts().MicrosoftExt98.5k
&&
4534
98.4k
      !getLangOpts().ObjC) {
4535
2.31k
    ProhibitAttributes(attrs);
4536
2.31k
    if (BaseType.isUsable())
4537
440
      Diag(BaseRange.getBegin(), diag::ext_enum_base_in_type_specifier)
4538
440
          << (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes) << BaseRange;
4539
1.87k
    else if (ScopedEnumKWLoc.isValid())
4540
21
      Diag(ScopedEnumKWLoc, diag::ext_elaborated_enum_class)
4541
21
        << FixItHint::CreateRemoval(ScopedEnumKWLoc) << IsScopedUsingClassTag;
4542
2.31k
  }
4543
700k
4544
700k
  stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4545
700k
4546
700k
  Sema::SkipBodyInfo SkipBody;
4547
700k
  if (!Name && 
TUK == Sema::TUK_Definition492k
&&
Tok.is(tok::l_brace)492k
&&
4548
492k
      NextToken().is(tok::identifier))
4549
492k
    SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4550
492k
                                              NextToken().getIdentifierInfo(),
4551
492k
                                              NextToken().getLocation());
4552
700k
4553
700k
  bool Owned = false;
4554
700k
  bool IsDependent = false;
4555
700k
  const char *PrevSpec = nullptr;
4556
700k
  unsigned DiagID;
4557
700k
  Decl *TagDecl = Actions.ActOnTag(
4558
700k
      getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
4559
700k
      attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4560
700k
      ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
4561
700k
      DSC == DeclSpecContext::DSC_type_specifier,
4562
700k
      DSC == DeclSpecContext::DSC_template_param ||
4563
700k
          DSC == DeclSpecContext::DSC_template_type_arg,
4564
700k
      &SkipBody);
4565
700k
4566
700k
  if (SkipBody.ShouldSkip) {
4567
18
    assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4568
18
4569
18
    BalancedDelimiterTracker T(*this, tok::l_brace);
4570
18
    T.consumeOpen();
4571
18
    T.skipToEnd();
4572
18
4573
18
    if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4574
13
                           NameLoc.isValid() ? NameLoc : 
StartLoc5
,
4575
18
                           PrevSpec, DiagID, TagDecl, Owned,
4576
18
                           Actions.getASTContext().getPrintingPolicy()))
4577
0
      Diag(StartLoc, DiagID) << PrevSpec;
4578
18
    return;
4579
18
  }
4580
700k
4581
700k
  if (IsDependent) {
4582
    // This enum has a dependent nested-name-specifier. Handle it as a
4583
    // dependent tag.
4584
11
    if (!Name) {
4585
0
      DS.SetTypeSpecError();
4586
0
      Diag(Tok, diag::err_expected_type_name_after_typename);
4587
0
      return;
4588
0
    }
4589
11
4590
11
    TypeResult Type = Actions.ActOnDependentTag(
4591
11
        getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4592
11
    if (Type.isInvalid()) {
4593
0
      DS.SetTypeSpecError();
4594
0
      return;
4595
0
    }
4596
11
4597
11
    if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4598
11
                           NameLoc.isValid() ? NameLoc : 
StartLoc0
,
4599
11
                           PrevSpec, DiagID, Type.get(),
4600
11
                           Actions.getASTContext().getPrintingPolicy()))
4601
0
      Diag(StartLoc, DiagID) << PrevSpec;
4602
11
4603
11
    return;
4604
11
  }
4605
700k
4606
700k
  if (!TagDecl) {
4607
    // The action failed to produce an enumeration tag. If this is a
4608
    // definition, consume the entire definition.
4609
68
    if (Tok.is(tok::l_brace) && 
TUK != Sema::TUK_Reference46
) {
4610
46
      ConsumeBrace();
4611
46
      SkipUntil(tok::r_brace, StopAtSemi);
4612
46
    }
4613
68
4614
68
    DS.SetTypeSpecError();
4615
68
    return;
4616
68
  }
4617
700k
4618
700k
  if (Tok.is(tok::l_brace) && 
TUK == Sema::TUK_Definition601k
) {
4619
601k
    Decl *D = SkipBody.CheckSameAsPrevious ? 
SkipBody.New4
: TagDecl;
4620
601k
    ParseEnumBody(StartLoc, D);
4621
601k
    if (SkipBody.CheckSameAsPrevious &&
4622
4
        !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4623
2
      DS.SetTypeSpecError();
4624
2
      return;
4625
2
    }
4626
700k
  }
4627
700k
4628
700k
  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4629
492k
                         NameLoc.isValid() ? 
NameLoc207k
: StartLoc,
4630
700k
                         PrevSpec, DiagID, TagDecl, Owned,
4631
700k
                         Actions.getASTContext().getPrintingPolicy()))
4632
0
    Diag(StartLoc, DiagID) << PrevSpec;
4633
700k
}
4634
4635
/// ParseEnumBody - Parse a {} enclosed enumerator-list.
4636
///       enumerator-list:
4637
///         enumerator
4638
///         enumerator-list ',' enumerator
4639
///       enumerator:
4640
///         enumeration-constant attributes[opt]
4641
///         enumeration-constant attributes[opt] '=' constant-expression
4642
///       enumeration-constant:
4643
///         identifier
4644
///
4645
601k
void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4646
  // Enter the scope of the enum body and start the definition.
4647
601k
  ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4648
601k
  Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4649
601k
4650
601k
  BalancedDelimiterTracker T(*this, tok::l_brace);
4651
601k
  T.consumeOpen();
4652
601k
4653
  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4654
601k
  if (Tok.is(tok::r_brace) && 
!getLangOpts().CPlusPlus1.42k
)
4655
1
    Diag(Tok, diag::err_empty_enum);
4656
601k
4657
601k
  SmallVector<Decl *, 32> EnumConstantDecls;
4658
601k
  SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4659
601k
4660
601k
  Decl *LastEnumConstDecl = nullptr;
4661
601k
4662
  // Parse the enumerator-list.
4663
5.47M
  while (Tok.isNot(tok::r_brace)) {
4664
    // Parse enumerator. If failed, try skipping till the start of the next
4665
    // enumerator definition.
4666
4.92M
    if (Tok.isNot(tok::identifier)) {
4667
9
      Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4668
9
      if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4669
9
          TryConsumeToken(tok::comma))
4670
2
        continue;
4671
7
      break;
4672
7
    }
4673
4.92M
    IdentifierInfo *Ident = Tok.getIdentifierInfo();
4674
4.92M
    SourceLocation IdentLoc = ConsumeToken();
4675
4.92M
4676
    // If attributes exist after the enumerator, parse them.
4677
4.92M
    ParsedAttributesWithRange attrs(AttrFactory);
4678
4.92M
    MaybeParseGNUAttributes(attrs);
4679
4.92M
    ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4680
4.92M
    if (standardAttributesAllowed() && 
isCXX11AttributeSpecifier()613k
) {
4681
16
      if (getLangOpts().CPlusPlus)
4682
9
        Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4683
7
                                    ? diag::warn_cxx14_compat_ns_enum_attribute
4684
2
                                    : diag::ext_ns_enum_attribute)
4685
9
            << 1 /*enumerator*/;
4686
16
      ParseCXX11Attributes(attrs);
4687
16
    }
4688
4.92M
4689
4.92M
    SourceLocation EqualLoc;
4690
4.92M
    ExprResult AssignedVal;
4691
4.92M
    EnumAvailabilityDiags.emplace_back(*this);
4692
4.92M
4693
4.92M
    EnterExpressionEvaluationContext ConstantEvaluated(
4694
4.92M
        Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4695
4.92M
    if (TryConsumeToken(tok::equal, EqualLoc)) {
4696
4.70M
      AssignedVal = ParseConstantExpressionInExprEvalContext();
4697
4.70M
      if (AssignedVal.isInvalid())
4698
7
        SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4699
4.70M
    }
4700
4.92M
4701
    // Install the enumerator constant into EnumDecl.
4702
4.92M
    Decl *EnumConstDecl = Actions.ActOnEnumConstant(
4703
4.92M
        getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4704
4.92M
        EqualLoc, AssignedVal.get());
4705
4.92M
    EnumAvailabilityDiags.back().done();
4706
4.92M
4707
4.92M
    EnumConstantDecls.push_back(EnumConstDecl);
4708
4.92M
    LastEnumConstDecl = EnumConstDecl;
4709
4.92M
4710
4.92M
    if (Tok.is(tok::identifier)) {
4711
      // We're missing a comma between enumerators.
4712
4
      SourceLocation Loc = getEndOfPreviousToken();
4713
4
      Diag(Loc, diag::err_enumerator_list_missing_comma)
4714
4
        << FixItHint::CreateInsertion(Loc, ", ");
4715
4
      continue;
4716
4
    }
4717
4.92M
4718
    // Emumerator definition must be finished, only comma or r_brace are
4719
    // allowed here.
4720
4.92M
    SourceLocation CommaLoc;
4721
4.92M
    if (Tok.isNot(tok::r_brace) && 
!TryConsumeToken(tok::comma, CommaLoc)4.38M
) {
4722
7
      if (EqualLoc.isValid())
4723
5
        Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4724
5
                                                           << tok::comma;
4725
2
      else
4726
2
        Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4727
7
      if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4728
7
        if (TryConsumeToken(tok::comma, CommaLoc))
4729
2
          continue;
4730
0
      } else {
4731
0
        break;
4732
0
      }
4733
4.92M
    }
4734
4.92M
4735
    // If comma is followed by r_brace, emit appropriate warning.
4736
4.92M
    if (Tok.is(tok::r_brace) && 
CommaLoc.isValid()600k
) {
4737
55.2k
      if (!getLangOpts().C99 && 
!getLangOpts().CPlusPlus117.99k
)
4738
8
        Diag(CommaLoc, getLangOpts().CPlusPlus ?
4739
7
               diag::ext_enumerator_list_comma_cxx :
4740
1
               diag::ext_enumerator_list_comma_c)
4741
8
          << FixItHint::CreateRemoval(CommaLoc);
4742
55.2k
      else if (getLangOpts().CPlusPlus11)
4743
7.98k
        Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4744
7.98k
          << FixItHint::CreateRemoval(CommaLoc);
4745
55.2k
      break;
4746
55.2k
    }
4747
4.92M
  }
4748
601k
4749
  // Eat the }.
4750
601k
  T.consumeClose();
4751
601k
4752
  // If attributes exist after the identifier list, parse them.
4753
601k
  ParsedAttributes attrs(AttrFactory);
4754
601k
  MaybeParseGNUAttributes(attrs);
4755
601k
4756
601k
  Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4757
601k
                        getCurScope(), attrs);
4758
601k
4759
  // Now handle enum constant availability diagnostics.
4760
601k
  assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4761
5.52M
  for (size_t i = 0, e = EnumConstantDecls.size(); i != e; 
++i4.92M
) {
4762
4.92M
    ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4763
4.92M
    EnumAvailabilityDiags[i].redelay();
4764
4.92M
    PD.complete(EnumConstantDecls[i]);
4765
4.92M
  }
4766
601k
4767
601k
  EnumScope.Exit();
4768
601k
  Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4769
601k
4770
  // The next token must be valid after an enum definition. If not, a ';'
4771
  // was probably forgotten.
4772
601k
  bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4773
601k
  if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4774
6
    ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4775
    // Push this token back into the preprocessor and change our current token
4776
    // to ';' so that the rest of the code recovers as though there were an
4777
    // ';' after the definition.
4778
6
    PP.EnterToken(Tok, /*IsReinject=*/true);
4779
6
    Tok.setKind(tok::semi);
4780
6
  }
4781
601k
}
4782
4783
/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4784
/// is definitely a type-specifier.  Return false if it isn't part of a type
4785
/// specifier or if we're not sure.
4786
83.1k
bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4787
83.1k
  switch (Tok.getKind()) {
4788
83.1k
  default: return false;
4789
    // type-specifiers
4790
30
  case tok::kw_short:
4791
30
  case tok::kw_long:
4792
30
  case tok::kw___int64:
4793
30
  case tok::kw___int128:
4794
30
  case tok::kw_signed:
4795
30
  case tok::kw_unsigned:
4796
30
  case tok::kw__Complex:
4797
30
  case tok::kw__Imaginary:
4798
30
  case tok::kw_void:
4799
30
  case tok::kw_char:
4800
30
  case tok::kw_wchar_t:
4801
30
  case tok::kw_char8_t:
4802
30
  case tok::kw_char16_t:
4803
30
  case tok::kw_char32_t:
4804
30
  case tok::kw_int:
4805
30
  case tok::kw__ExtInt:
4806
30
  case tok::kw___bf16:
4807
30
  case tok::kw_half:
4808
30
  case tok::kw_float:
4809
30
  case tok::kw_double:
4810
30
  case tok::kw__Accum:
4811
30
  case tok::kw__Fract:
4812
30
  case tok::kw__Float16:
4813
30
  case tok::kw___float128:
4814
30
  case tok::kw_bool:
4815
30
  case tok::kw__Bool:
4816
30
  case tok::kw__Decimal32:
4817
30
  case tok::kw__Decimal64:
4818
30
  case tok::kw__Decimal128:
4819
30
  case tok::kw___vector:
4820
360
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4821
360
#include 
"clang/Basic/OpenCLImageTypes.def"30
4822
360
4823
    // struct-or-union-specifier (C99) or class-specifier (C++)
4824
30
  case tok::kw_class:
4825
30
  case tok::kw_struct:
4826
30
  case tok::kw___interface:
4827
30
  case tok::kw_union:
4828
    // enum-specifier
4829
30
  case tok::kw_enum:
4830
30
4831
    // typedef-name
4832
30
  case tok::annot_typename:
4833
30
    return true;
4834
83.1k
  }
4835
83.1k
}
4836
4837
/// isTypeSpecifierQualifier - Return true if the current token could be the
4838
/// start of a specifier-qualifier-list.
4839
11.6M
bool Parser::isTypeSpecifierQualifier() {
4840
11.6M
  switch (Tok.getKind()) {
4841
403k
  default: return false;
4842
0
4843
5.56M
  case tok::identifier:   // foo::bar
4844
5.56M
    if (TryAltiVecVectorToken())
4845
113k
      return true;
4846
5.45M
    LLVM_FALLTHROUGH;
4847
5.45M
  case tok::kw_typename:  // typename T::type
4848
    // Annotate typenames and C++ scope specifiers.  If we get one, just
4849
    // recurse to handle whatever we get.
4850
5.45M
    if (TryAnnotateTypeOrScopeToken())
4851
0
      return true;
4852
5.45M
    if (Tok.is(tok::identifier))
4853
406k
      return false;
4854
5.04M
    return isTypeSpecifierQualifier();
4855
5.04M
4856
0
  case tok::coloncolon:   // ::foo::bar
4857
0
    if (NextToken().is(tok::kw_new) ||    // ::new
4858
0
        NextToken().is(tok::kw_delete))   // ::delete
4859
0
      return false;
4860
0
4861
0
    if (TryAnnotateTypeOrScopeToken())
4862
0
      return true;
4863
0
    return isTypeSpecifierQualifier();
4864
0
4865
    // GNU attributes support.
4866
5.64M
  case tok::kw___attribute:
4867
    // GNU typeof support.
4868
5.64M
  case tok::kw_typeof:
4869
5.64M
4870
    // type-specifiers
4871
5.64M
  case tok::kw_short:
4872
5.64M
  case tok::kw_long:
4873
5.64M
  case tok::kw___int64:
4874
5.64M
  case tok::kw___int128:
4875
5.64M
  case tok::kw_signed:
4876
5.64M
  case tok::kw_unsigned:
4877
5.64M
  case tok::kw__Complex:
4878
5.64M
  case tok::kw__Imaginary:
4879
5.64M
  case tok::kw_void:
4880
5.64M
  case tok::kw_char:
4881
5.64M
  case tok::kw_wchar_t:
4882
5.64M
  case tok::kw_char8_t:
4883
5.64M
  case tok::kw_char16_t:
4884
5.64M
  case tok::kw_char32_t:
4885
5.64M
  case tok::kw_int:
4886
5.64M
  case tok::kw__ExtInt:
4887
5.64M
  case tok::kw_half:
4888
5.64M
  case tok::kw___bf16:
4889
5.64M
  case tok::kw_float:
4890
5.64M
  case tok::kw_double:
4891
5.64M
  case tok::kw__Accum:
4892
5.64M
  case tok::kw__Fract:
4893
5.64M
  case tok::kw__Float16:
4894
5.64M
  case tok::kw___float128:
4895
5.64M
  case tok::kw_bool:
4896
5.64M
  case tok::kw__Bool:
4897
5.64M
  case tok::kw__Decimal32:
4898
5.64M
  case tok::kw__Decimal64:
4899
5.64M
  case tok::kw__Decimal128:
4900
5.64M
  case tok::kw___vector:
4901
67.7M
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4902
67.7M
#include 
"clang/Basic/OpenCLImageTypes.def"5.64M
4903
67.7M
4904
    // struct-or-union-specifier (C99) or class-specifier (C++)
4905
5.64M
  case tok::kw_class:
4906
5.64M
  case tok::kw_struct:
4907
5.64M
  case tok::kw___interface:
4908
5.64M
  case tok::kw_union:
4909
    // enum-specifier
4910
5.64M
  case tok::kw_enum:
4911
5.64M
4912
    // type-qualifier
4913
5.64M
  case tok::kw_const:
4914
5.64M
  case tok::kw_volatile:
4915
5.64M
  case tok::kw_restrict:
4916
5.64M
  case tok::kw__Sat:
4917
5.64M
4918
    // Debugger support.
4919
5.64M
  case tok::kw___unknown_anytype:
4920
5.64M
4921
    // typedef-name
4922
5.64M
  case tok::annot_typename:
4923
5.64M
    return true;
4924
5.64M
4925
    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4926
3
  case tok::less:
4927
3
    return getLangOpts().ObjC;
4928
5.64M
4929
886
  case tok::kw___cdecl:
4930
886
  case tok::kw___stdcall:
4931
886
  case tok::kw___fastcall:
4932
886
  case tok::kw___thiscall:
4933
886
  case tok::kw___regcall:
4934
886
  case tok::kw___vectorcall:
4935
886
  case tok::kw___w64:
4936
886
  case tok::kw___ptr64:
4937
886
  case tok::kw___ptr32:
4938
886
  case tok::kw___pascal:
4939
886
  case tok::kw___unaligned:
4940
886
4941
886
  case tok::kw__Nonnull:
4942
886
  case tok::kw__Nullable:
4943
886
  case tok::kw__Null_unspecified:
4944
886
4945
886
  case tok::kw___kindof:
4946
886
4947
886
  case tok::kw___private:
4948
886
  case tok::kw___local:
4949
886
  case tok::kw___global:
4950
886
  case tok::kw___constant:
4951
886
  case tok::kw___generic:
4952
886
  case tok::kw___read_only:
4953
886
  case tok::kw___read_write:
4954
886
  case tok::kw___write_only:
4955
886
    return true;
4956
886
4957
0
  case tok::kw_private:
4958
0
    return getLangOpts().OpenCL;
4959
886
4960
  // C11 _Atomic
4961
69
  case tok::kw__Atomic:
4962
69
    return true;
4963
11.6M
  }
4964
11.6M
}
4965
4966
/// isDeclarationSpecifier() - Return true if the current token is part of a
4967
/// declaration specifier.
4968
///
4969
/// \param DisambiguatingWithExpression True to indicate that the purpose of
4970
/// this check is to disambiguate between an expression and a declaration.
4971
1.67M
bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4972
1.67M
  switch (Tok.getKind()) {
4973
679k
  default: return false;
4974
0
4975
3
  case tok::kw_pipe:
4976
3
    return (getLangOpts().OpenCL && getLangOpts().OpenCLVersion >= 200) ||
4977
0
           getLangOpts().OpenCLCPlusPlus;
4978
0
4979
180k
  case tok::identifier:   // foo::bar
4980
    // Unfortunate hack to support "Class.factoryMethod" notation.
4981
180k
    if (getLangOpts().ObjC && 
NextToken().is(tok::period)5.06k
)
4982
82
      return false;
4983
180k
    if (TryAltiVecVectorToken())
4984
5.61k
      return true;
4985
174k
    LLVM_FALLTHROUGH;
4986
175k
  case tok::kw_decltype: // decltype(T())::type
4987
175k
  case tok::kw_typename: // typename T::type
4988
    // Annotate typenames and C++ scope specifiers.  If we get one, just
4989
    // recurse to handle whatever we get.
4990
175k
    if (TryAnnotateTypeOrScopeToken())
4991
1
      return true;
4992
175k
    if (TryAnnotateTypeConstraint())
4993
0
      return true;
4994
175k
    if (Tok.is(tok::identifier))
4995
7.73k
      return false;
4996
167k
4997
    // If we're in Objective-C and we have an Objective-C class type followed
4998
    // by an identifier and then either ':' or ']', in a place where an
4999
    // expression is permitted, then this is probably a class message send
5000
    // missing the initial '['. In this case, we won't consider this to be
5001
    // the start of a declaration.
5002
167k
    if (DisambiguatingWithExpression &&
5003
213
        isStartOfObjCClassMessageMissingOpenBracket())
5004
0
      return false;
5005
167k
5006
167k
    return isDeclarationSpecifier();
5007
167k
5008
1
  case tok::coloncolon:   // ::foo::bar
5009
1
    if (NextToken().is(tok::kw_new) ||    // ::new
5010
1
        NextToken().is(tok::kw_delete))   // ::delete
5011
0
      return false;
5012
1
5013
    // Annotate typenames and C++ scope specifiers.  If we get one, just
5014
    // recurse to handle whatever we get.
5015
1
    if (TryAnnotateTypeOrScopeToken())
5016
0
      return true;
5017
1
    return isDeclarationSpecifier();
5018
1
5019
    // storage-class-specifier
5020
157k
  case tok::kw_typedef:
5021
157k
  case tok::kw_extern:
5022
157k
  case tok::kw___private_extern__:
5023
157k
  case tok::kw_static:
5024
157k
  case tok::kw_auto:
5025
157k
  case tok::kw___auto_type:
5026
157k
  case tok::kw_register:
5027
157k
  case tok::kw___thread:
5028
157k
  case tok::kw_thread_local:
5029
157k
  case tok::kw__Thread_local:
5030
157k
5031
    // Modules
5032
157k
  case tok::kw___module_private__:
5033
157k
5034
    // Debugger support
5035
157k
  case tok::kw___unknown_anytype:
5036
157k
5037
    // type-specifiers
5038
157k
  case tok::kw_short:
5039
157k
  case tok::kw_long:
5040
157k
  case tok::kw___int64:
5041
157k
  case tok::kw___int128:
5042
157k
  case tok::kw_signed:
5043
157k
  case tok::kw_unsigned:
5044
157k
  case tok::kw__Complex:
5045
157k
  case tok::kw__Imaginary:
5046
157k
  case tok::kw_void:
5047
157k
  case tok::kw_char:
5048
157k
  case tok::kw_wchar_t:
5049
157k
  case tok::kw_char8_t:
5050
157k
  case tok::kw_char16_t:
5051
157k
  case tok::kw_char32_t:
5052
157k
5053
157k
  case tok::kw_int:
5054
157k
  case tok::kw__ExtInt:
5055
157k
  case tok::kw_half:
5056
157k
  case tok::kw___bf16:
5057
157k
  case tok::kw_float:
5058
157k
  case tok::kw_double:
5059
157k
  case tok::kw__Accum:
5060
157k
  case tok::kw__Fract:
5061
157k
  case tok::kw__Float16:
5062
157k
  case tok::kw___float128:
5063
157k
  case tok::kw_bool:
5064
157k
  case tok::kw__Bool:
5065
157k
  case tok::kw__Decimal32:
5066
157k
  case tok::kw__Decimal64:
5067
157k
  case tok::kw__Decimal128:
5068
157k
  case tok::kw___vector:
5069
157k
5070
    // struct-or-union-specifier (C99) or class-specifier (C++)
5071
157k
  case tok::kw_class:
5072
157k
  case tok::kw_struct:
5073
157k
  case tok::kw_union:
5074
157k
  case tok::kw___interface:
5075
    // enum-specifier
5076
157k
  case tok::kw_enum:
5077
157k
5078
    // type-qualifier
5079
157k
  case tok::kw_const:
5080
157k
  case tok::kw_volatile:
5081
157k
  case tok::kw_restrict:
5082
157k
  case tok::kw__Sat:
5083
157k
5084
    // function-specifier
5085
157k
  case tok::kw_inline:
5086
157k
  case tok::kw_virtual:
5087
157k
  case tok::kw_explicit:
5088
157k
  case tok::kw__Noreturn:
5089
157k
5090
    // alignment-specifier
5091
157k
  case tok::kw__Alignas:
5092
157k
5093
    // friend keyword.
5094
157k
  case tok::kw_friend:
5095
157k
5096
    // static_assert-declaration
5097
157k
  case tok::kw__Static_assert:
5098
157k
5099
    // GNU typeof support.
5100
157k
  case tok::kw_typeof:
5101
157k
5102
    // GNU attributes.
5103
157k
  case tok::kw___attribute:
5104
157k
5105
    // C++11 decltype and constexpr.
5106
157k
  case tok::annot_decltype:
5107
157k
  case tok::kw_constexpr:
5108
157k
5109
    // C++20 consteval and constinit.
5110
157k
  case tok::kw_consteval:
5111
157k
  case tok::kw_constinit:
5112
157k
5113
    // C11 _Atomic
5114
157k
  case tok::kw__Atomic:
5115
157k
    return true;
5116
157k
5117
    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5118
5
  case tok::less:
5119
5
    return getLangOpts().ObjC;
5120
157k
5121
    // typedef-name
5122
616k
  case tok::annot_typename:
5123
616k
    return !DisambiguatingWithExpression ||
5124
446k
           !isStartOfObjCClassMessageMissingOpenBracket();
5125
157k
5126
    // placeholder-type-specifier
5127
9
  case tok::annot_template_id: {
5128
9
    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
5129
9
    if (TemplateId->hasInvalidName())
5130
0
      return true;
5131
    // FIXME: What about type templates that have only been annotated as
5132
    // annot_template_id, not as annot_typename?
5133
9
    return isTypeConstraintAnnotation() &&
5134
5
           (NextToken().is(tok::kw_auto) || 
NextToken().is(tok::kw_decltype)0
);
5135
9
  }
5136
9
5137
40.5k
  case tok::annot_cxxscope: {
5138
40.5k
    TemplateIdAnnotation *TemplateId =
5139
40.5k
        NextToken().is(tok::annot_template_id)
5140
2
            ? takeTemplateIdAnnotation(NextToken())
5141
40.5k
            : nullptr;
5142
40.5k
    if (TemplateId && 
TemplateId->hasInvalidName()2
)
5143
0
      return true;
5144
    // FIXME: What about type templates that have only been annotated as
5145
    // annot_template_id, not as annot_typename?
5146
40.5k
    if (NextToken().is(tok::identifier) && 
TryAnnotateTypeConstraint()27
)
5147
0
      return true;
5148
40.5k
    return isTypeConstraintAnnotation() &&
5149
2
        GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype);
5150
40.5k
  }
5151
40.5k
5152
649
  case tok::kw___declspec:
5153
649
  case tok::kw___cdecl:
5154
649
  case tok::kw___stdcall:
5155
649
  case tok::kw___fastcall:
5156
649
  case tok::kw___thiscall:
5157
649
  case tok::kw___regcall:
5158
649
  case tok::kw___vectorcall:
5159
649
  case tok::kw___w64:
5160
649
  case tok::kw___sptr:
5161
649
  case tok::kw___uptr:
5162
649
  case tok::kw___ptr64:
5163
649
  case tok::kw___ptr32:
5164
649
  case tok::kw___forceinline:
5165
649
  case tok::kw___pascal:
5166
649
  case tok::kw___unaligned:
5167
649
5168
649
  case tok::kw__Nonnull:
5169
649
  case tok::kw__Nullable:
5170
649
  case tok::kw__Null_unspecified:
5171
649
5172
649
  case tok::kw___kindof:
5173
649
5174
649
  case tok::kw___private:
5175
649
  case tok::kw___local:
5176
649
  case tok::kw___global:
5177
649
  case tok::kw___constant:
5178
649
  case tok::kw___generic:
5179
649
  case tok::kw___read_only:
5180
649
  case tok::kw___read_write:
5181
649
  case tok::kw___write_only:
5182
7.78k
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5183
649
#include "clang/Basic/OpenCLImageTypes.def"
5184
649
5185
649
    return true;
5186
7.13k
5187
0
  case tok::kw_private:
5188
0
    return getLangOpts().OpenCL;
5189
1.67M
  }
5190
1.67M
}
5191
5192
368k
bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
5193
368k
  TentativeParsingAction TPA(*this);
5194
368k
5195
  // Parse the C++ scope specifier.
5196
368k
  CXXScopeSpec SS;
5197
368k
  if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
5198
368k
                                     /*ObjectHadErrors=*/false,
5199
0
                                     /*EnteringContext=*/true)) {
5200
0
    TPA.Revert();
5201
0
    return false;
5202
0
  }
5203
368k
5204
  // Parse the constructor name.
5205
368k
  if (Tok.is(tok::identifier)) {
5206
    // We already know that we have a constructor name; just consume
5207
    // the token.
5208
357k
    ConsumeToken();
5209
11.1k
  } else if (Tok.is(tok::annot_template_id)) {
5210
11.1k
    ConsumeAnnotationToken();
5211
0
  } else {
5212
0
    TPA.Revert();
5213
0
    return false;
5214
0
  }
5215
368k
5216
  // There may be attributes here, appertaining to the constructor name or type
5217
  // we just stepped past.
5218
368k
  SkipCXX11Attributes();
5219
368k
5220
  // Current class name must be followed by a left parenthesis.