Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Parse/ParseDeclCXX.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ParseDeclCXX.cpp - C++ 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 C++ Declaration portions of the Parser interfaces.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Parse/Parser.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/DeclTemplate.h"
16
#include "clang/AST/PrettyDeclStackTrace.h"
17
#include "clang/Basic/Attributes.h"
18
#include "clang/Basic/CharInfo.h"
19
#include "clang/Basic/OperatorKinds.h"
20
#include "clang/Basic/TargetInfo.h"
21
#include "clang/Parse/ParseDiagnostic.h"
22
#include "clang/Parse/RAIIObjectsForParser.h"
23
#include "clang/Sema/DeclSpec.h"
24
#include "clang/Sema/ParsedTemplate.h"
25
#include "clang/Sema/Scope.h"
26
#include "llvm/ADT/SmallString.h"
27
#include "llvm/Support/TimeProfiler.h"
28
29
using namespace clang;
30
31
/// ParseNamespace - We know that the current token is a namespace keyword. This
32
/// may either be a top level namespace or a block-level namespace alias. If
33
/// there was an inline keyword, it has already been parsed.
34
///
35
///       namespace-definition: [C++: namespace.def]
36
///         named-namespace-definition
37
///         unnamed-namespace-definition
38
///         nested-namespace-definition
39
///
40
///       named-namespace-definition:
41
///         'inline'[opt] 'namespace' attributes[opt] identifier '{'
42
///         namespace-body '}'
43
///
44
///       unnamed-namespace-definition:
45
///         'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
46
///
47
///       nested-namespace-definition:
48
///         'namespace' enclosing-namespace-specifier '::' 'inline'[opt]
49
///         identifier '{' namespace-body '}'
50
///
51
///       enclosing-namespace-specifier:
52
///         identifier
53
///         enclosing-namespace-specifier '::' 'inline'[opt] identifier
54
///
55
///       namespace-alias-definition:  [C++ 7.3.2: namespace.alias]
56
///         'namespace' identifier '=' qualified-namespace-specifier ';'
57
///
58
Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context,
59
                                              SourceLocation &DeclEnd,
60
121k
                                              SourceLocation InlineLoc) {
61
121k
  assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
62
121k
  SourceLocation NamespaceLoc = ConsumeToken();  // eat the 'namespace'.
63
121k
  ObjCDeclContextSwitch ObjCDC(*this);
64
121k
65
121k
  if (Tok.is(tok::code_completion)) {
66
1
    Actions.CodeCompleteNamespaceDecl(getCurScope());
67
1
    cutOffParsing();
68
1
    return nullptr;
69
1
  }
70
121k
71
121k
  SourceLocation IdentLoc;
72
121k
  IdentifierInfo *Ident = nullptr;
73
121k
  InnerNamespaceInfoList ExtraNSs;
74
121k
  SourceLocation FirstNestedInlineLoc;
75
121k
76
121k
  ParsedAttributesWithRange attrs(AttrFactory);
77
121k
  SourceLocation attrLoc;
78
121k
  if (getLangOpts().CPlusPlus11 && 
isCXX11AttributeSpecifier()117k
) {
79
10
    Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
80
10
                                ? 
diag::warn_cxx14_compat_ns_enum_attribute9
81
10
                                : 
diag::ext_ns_enum_attribute1
)
82
10
      << 0 /*namespace*/;
83
10
    attrLoc = Tok.getLocation();
84
10
    ParseCXX11Attributes(attrs);
85
10
  }
86
121k
87
121k
  if (Tok.is(tok::identifier)) {
88
120k
    Ident = Tok.getIdentifierInfo();
89
120k
    IdentLoc = ConsumeToken();  // eat the identifier.
90
120k
    while (Tok.is(tok::coloncolon) &&
91
120k
           
(88
NextToken().is(tok::identifier)88
||
92
88
            
(13
NextToken().is(tok::kw_inline)13
&&
93
88
             
GetLookAheadToken(2).is(tok::identifier)13
))) {
94
88
95
88
      InnerNamespaceInfo Info;
96
88
      Info.NamespaceLoc = ConsumeToken();
97
88
98
88
      if (Tok.is(tok::kw_inline)) {
99
13
        Info.InlineLoc = ConsumeToken();
100
13
        if (FirstNestedInlineLoc.isInvalid())
101
7
          FirstNestedInlineLoc = Info.InlineLoc;
102
13
      }
103
88
104
88
      Info.Ident = Tok.getIdentifierInfo();
105
88
      Info.IdentLoc = ConsumeToken();
106
88
107
88
      ExtraNSs.push_back(Info);
108
88
    }
109
120k
  }
110
121k
111
121k
  // A nested namespace definition cannot have attributes.
112
121k
  if (!ExtraNSs.empty() && 
attrLoc.isValid()55
)
113
1
    Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
114
121k
115
121k
  // Read label attributes, if present.
116
121k
  if (Tok.is(tok::kw___attribute)) {
117
37
    attrLoc = Tok.getLocation();
118
37
    ParseGNUAttributes(attrs);
119
37
  }
120
121k
121
121k
  if (Tok.is(tok::equal)) {
122
269
    if (!Ident) {
123
1
      Diag(Tok, diag::err_expected) << tok::identifier;
124
1
      // Skip to end of the definition and eat the ';'.
125
1
      SkipUntil(tok::semi);
126
1
      return nullptr;
127
1
    }
128
268
    if (attrLoc.isValid())
129
2
      Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
130
268
    if (InlineLoc.isValid())
131
0
      Diag(InlineLoc, diag::err_inline_namespace_alias)
132
0
          << FixItHint::CreateRemoval(InlineLoc);
133
268
    Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
134
268
    return Actions.ConvertDeclToDeclGroup(NSAlias);
135
268
}
136
121k
137
121k
  BalancedDelimiterTracker T(*this, tok::l_brace);
138
121k
  if (T.consumeOpen()) {
139
7
    if (Ident)
140
0
      Diag(Tok, diag::err_expected) << tok::l_brace;
141
7
    else
142
7
      Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
143
7
    return nullptr;
144
7
  }
145
121k
146
121k
  if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
147
121k
      getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
148
121k
      getCurScope()->getFnParent()) {
149
1
    Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
150
1
    SkipUntil(tok::r_brace);
151
1
    return nullptr;
152
1
  }
153
121k
154
121k
  if (ExtraNSs.empty()) {
155
121k
    // Normal namespace definition, not a nested-namespace-definition.
156
121k
  } else 
if (55
InlineLoc.isValid()55
) {
157
5
    Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
158
50
  } else if (getLangOpts().CPlusPlus2a) {
159
21
    Diag(ExtraNSs[0].NamespaceLoc,
160
21
         diag::warn_cxx14_compat_nested_namespace_definition);
161
21
    if (FirstNestedInlineLoc.isValid())
162
3
      Diag(FirstNestedInlineLoc,
163
3
           diag::warn_cxx17_compat_inline_nested_namespace_definition);
164
29
  } else if (getLangOpts().CPlusPlus17) {
165
18
    Diag(ExtraNSs[0].NamespaceLoc,
166
18
         diag::warn_cxx14_compat_nested_namespace_definition);
167
18
    if (FirstNestedInlineLoc.isValid())
168
2
      Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
169
18
  } else {
170
11
    TentativeParsingAction TPA(*this);
171
11
    SkipUntil(tok::r_brace, StopBeforeMatch);
172
11
    Token rBraceToken = Tok;
173
11
    TPA.Revert();
174
11
175
11
    if (!rBraceToken.is(tok::r_brace)) {
176
0
      Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
177
0
          << SourceRange(ExtraNSs.front().NamespaceLoc,
178
0
                         ExtraNSs.back().IdentLoc);
179
11
    } else {
180
11
      std::string NamespaceFix;
181
22
      for (const auto &ExtraNS : ExtraNSs) {
182
22
        NamespaceFix += " { ";
183
22
        if (ExtraNS.InlineLoc.isValid())
184
4
          NamespaceFix += "inline ";
185
22
        NamespaceFix += "namespace ";
186
22
        NamespaceFix += ExtraNS.Ident->getName();
187
22
      }
188
11
189
11
      std::string RBraces;
190
33
      for (unsigned i = 0, e = ExtraNSs.size(); i != e; 
++i22
)
191
22
        RBraces +=  "} ";
192
11
193
11
      Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
194
11
          << FixItHint::CreateReplacement(
195
11
                 SourceRange(ExtraNSs.front().NamespaceLoc,
196
11
                             ExtraNSs.back().IdentLoc),
197
11
                 NamespaceFix)
198
11
          << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
199
11
    }
200
11
201
11
    // Warn about nested inline namespaces.
202
11
    if (FirstNestedInlineLoc.isValid())
203
2
      Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
204
11
  }
205
121k
206
121k
  // If we're still good, complain about inline namespaces in non-C++0x now.
207
121k
  if (InlineLoc.isValid())
208
18.1k
    Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
209
17.3k
         diag::warn_cxx98_compat_inline_namespace : 
diag::ext_inline_namespace818
);
210
121k
211
121k
  // Enter a scope for the namespace.
212
121k
  ParseScope NamespaceScope(this, Scope::DeclScope);
213
121k
214
121k
  UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
215
121k
  Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
216
121k
      getCurScope(), InlineLoc, NamespaceLoc, IdentLoc, Ident,
217
121k
      T.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
218
121k
219
121k
  PrettyDeclStackTraceEntry CrashInfo(Actions.Context, NamespcDecl,
220
121k
                                      NamespaceLoc, "parsing namespace");
221
121k
222
121k
  // Parse the contents of the namespace.  This includes parsing recovery on
223
121k
  // any improperly nested namespaces.
224
121k
  ParseInnerNamespace(ExtraNSs, 0, InlineLoc, attrs, T);
225
121k
226
121k
  // Leave the namespace scope.
227
121k
  NamespaceScope.Exit();
228
121k
229
121k
  DeclEnd = T.getCloseLocation();
230
121k
  Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
231
121k
232
121k
  return Actions.ConvertDeclToDeclGroup(NamespcDecl,
233
121k
                                        ImplicitUsingDirectiveDecl);
234
121k
}
235
236
/// ParseInnerNamespace - Parse the contents of a namespace.
237
void Parser::ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
238
                                 unsigned int index, SourceLocation &InlineLoc,
239
                                 ParsedAttributes &attrs,
240
121k
                                 BalancedDelimiterTracker &Tracker) {
241
121k
  if (index == InnerNSs.size()) {
242
2.39M
    while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
243
2.39M
           
Tok.isNot(tok::eof)2.27M
) {
244
2.27M
      ParsedAttributesWithRange attrs(AttrFactory);
245
2.27M
      MaybeParseCXX11Attributes(attrs);
246
2.27M
      ParseExternalDeclaration(attrs);
247
2.27M
    }
248
121k
249
121k
    // The caller is what called check -- we are simply calling
250
121k
    // the close for it.
251
121k
    Tracker.consumeClose();
252
121k
253
121k
    return;
254
121k
  }
255
88
256
88
  // Handle a nested namespace definition.
257
88
  // FIXME: Preserve the source information through to the AST rather than
258
88
  // desugaring it here.
259
88
  ParseScope NamespaceScope(this, Scope::DeclScope);
260
88
  UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
261
88
  Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
262
88
      getCurScope(), InnerNSs[index].InlineLoc, InnerNSs[index].NamespaceLoc,
263
88
      InnerNSs[index].IdentLoc, InnerNSs[index].Ident,
264
88
      Tracker.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
265
88
  assert(!ImplicitUsingDirectiveDecl &&
266
88
         "nested namespace definition cannot define anonymous namespace");
267
88
268
88
  ParseInnerNamespace(InnerNSs, ++index, InlineLoc, attrs, Tracker);
269
88
270
88
  NamespaceScope.Exit();
271
88
  Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
272
88
}
273
274
/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
275
/// alias definition.
276
///
277
Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
278
                                  SourceLocation AliasLoc,
279
                                  IdentifierInfo *Alias,
280
268
                                  SourceLocation &DeclEnd) {
281
268
  assert(Tok.is(tok::equal) && "Not equal token");
282
268
283
268
  ConsumeToken(); // eat the '='.
284
268
285
268
  if (Tok.is(tok::code_completion)) {
286
1
    Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
287
1
    cutOffParsing();
288
1
    return nullptr;
289
1
  }
290
267
291
267
  CXXScopeSpec SS;
292
267
  // Parse (optional) nested-name-specifier.
293
267
  ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
294
267
                                 /*MayBePseudoDestructor=*/nullptr,
295
267
                                 /*IsTypename=*/false,
296
267
                                 /*LastII=*/nullptr,
297
267
                                 /*OnlyNamespace=*/true);
298
267
299
267
  if (Tok.isNot(tok::identifier)) {
300
2
    Diag(Tok, diag::err_expected_namespace_name);
301
2
    // Skip to end of the definition and eat the ';'.
302
2
    SkipUntil(tok::semi);
303
2
    return nullptr;
304
2
  }
305
265
306
265
  if (SS.isInvalid()) {
307
4
    // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
308
4
    // Skip to end of the definition and eat the ';'.
309
4
    SkipUntil(tok::semi);
310
4
    return nullptr;
311
4
  }
312
261
313
261
  // Parse identifier.
314
261
  IdentifierInfo *Ident = Tok.getIdentifierInfo();
315
261
  SourceLocation IdentLoc = ConsumeToken();
316
261
317
261
  // Eat the ';'.
318
261
  DeclEnd = Tok.getLocation();
319
261
  if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
320
0
    SkipUntil(tok::semi);
321
261
322
261
  return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
323
261
                                        Alias, SS, IdentLoc, Ident);
324
261
}
325
326
/// ParseLinkage - We know that the current token is a string_literal
327
/// and just before that, that extern was seen.
328
///
329
///       linkage-specification: [C++ 7.5p2: dcl.link]
330
///         'extern' string-literal '{' declaration-seq[opt] '}'
331
///         'extern' string-literal declaration
332
///
333
79.3k
Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context) {
334
79.3k
  assert(isTokenStringLiteral() && "Not a string literal!");
335
79.3k
  ExprResult Lang = ParseStringLiteralExpression(false);
336
79.3k
337
79.3k
  ParseScope LinkageScope(this, Scope::DeclScope);
338
79.3k
  Decl *LinkageSpec =
339
79.3k
      Lang.isInvalid()
340
79.3k
          ? 
nullptr1
341
79.3k
          : Actions.ActOnStartLinkageSpecification(
342
79.3k
                getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
343
79.3k
                Tok.is(tok::l_brace) ? 
Tok.getLocation()45.2k
:
SourceLocation()34.1k
);
344
79.3k
345
79.3k
  ParsedAttributesWithRange attrs(AttrFactory);
346
79.3k
  MaybeParseCXX11Attributes(attrs);
347
79.3k
348
79.3k
  if (Tok.isNot(tok::l_brace)) {
349
34.1k
    // Reset the source range in DS, as the leading "extern"
350
34.1k
    // does not really belong to the inner declaration ...
351
34.1k
    DS.SetRangeStart(SourceLocation());
352
34.1k
    DS.SetRangeEnd(SourceLocation());
353
34.1k
    // ... but anyway remember that such an "extern" was seen.
354
34.1k
    DS.setExternInLinkageSpec(true);
355
34.1k
    ParseExternalDeclaration(attrs, &DS);
356
34.1k
    return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
357
34.1k
                             getCurScope(), LinkageSpec, SourceLocation())
358
34.1k
                       : 
nullptr3
;
359
34.1k
  }
360
45.2k
361
45.2k
  DS.abort();
362
45.2k
363
45.2k
  ProhibitAttributes(attrs);
364
45.2k
365
45.2k
  BalancedDelimiterTracker T(*this, tok::l_brace);
366
45.2k
  T.consumeOpen();
367
45.2k
368
45.2k
  unsigned NestedModules = 0;
369
1.01M
  while (true) {
370
1.01M
    switch (Tok.getKind()) {
371
1.01M
    case tok::annot_module_begin:
372
16
      ++NestedModules;
373
16
      ParseTopLevelDecl();
374
16
      continue;
375
1.01M
376
1.01M
    case tok::annot_module_end:
377
18
      if (!NestedModules)
378
2
        break;
379
16
      --NestedModules;
380
16
      ParseTopLevelDecl();
381
16
      continue;
382
16
383
16
    case tok::annot_module_include:
384
13
      ParseTopLevelDecl();
385
13
      continue;
386
16
387
16
    case tok::eof:
388
1
      break;
389
16
390
45.2k
    case tok::r_brace:
391
45.2k
      if (!NestedModules)
392
45.2k
        break;
393
2
      LLVM_FALLTHROUGH;
394
968k
    default:
395
968k
      ParsedAttributesWithRange attrs(AttrFactory);
396
968k
      MaybeParseCXX11Attributes(attrs);
397
968k
      ParseExternalDeclaration(attrs);
398
968k
      continue;
399
45.2k
    }
400
45.2k
401
45.2k
    break;
402
45.2k
  }
403
45.2k
404
45.2k
  T.consumeClose();
405
45.2k
  return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
406
45.2k
                           getCurScope(), LinkageSpec, T.getCloseLocation())
407
45.2k
                     : 
nullptr5
;
408
45.2k
}
409
410
/// Parse a C++ Modules TS export-declaration.
411
///
412
///       export-declaration:
413
///         'export' declaration
414
///         'export' '{' declaration-seq[opt] '}'
415
///
416
103
Decl *Parser::ParseExportDeclaration() {
417
103
  assert(Tok.is(tok::kw_export));
418
103
  SourceLocation ExportLoc = ConsumeToken();
419
103
420
103
  ParseScope ExportScope(this, Scope::DeclScope);
421
103
  Decl *ExportDecl = Actions.ActOnStartExportDecl(
422
103
      getCurScope(), ExportLoc,
423
103
      Tok.is(tok::l_brace) ? 
Tok.getLocation()20
:
SourceLocation()83
);
424
103
425
103
  if (Tok.isNot(tok::l_brace)) {
426
83
    // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
427
83
    ParsedAttributesWithRange Attrs(AttrFactory);
428
83
    MaybeParseCXX11Attributes(Attrs);
429
83
    MaybeParseMicrosoftAttributes(Attrs);
430
83
    ParseExternalDeclaration(Attrs);
431
83
    return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
432
83
                                         SourceLocation());
433
83
  }
434
20
435
20
  BalancedDelimiterTracker T(*this, tok::l_brace);
436
20
  T.consumeOpen();
437
20
438
20
  // The Modules TS draft says "An export-declaration shall declare at least one
439
20
  // entity", but the intent is that it shall contain at least one declaration.
440
20
  if (Tok.is(tok::r_brace) && 
getLangOpts().ModulesTS1
) {
441
1
    Diag(ExportLoc, diag::err_export_empty)
442
1
        << SourceRange(ExportLoc, Tok.getLocation());
443
1
  }
444
20
445
109
  while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
446
109
         
Tok.isNot(tok::eof)89
) {
447
89
    ParsedAttributesWithRange Attrs(AttrFactory);
448
89
    MaybeParseCXX11Attributes(Attrs);
449
89
    MaybeParseMicrosoftAttributes(Attrs);
450
89
    ParseExternalDeclaration(Attrs);
451
89
  }
452
20
453
20
  T.consumeClose();
454
20
  return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
455
20
                                       T.getCloseLocation());
456
20
}
457
458
/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
459
/// using-directive. Assumes that current token is 'using'.
460
Parser::DeclGroupPtrTy
461
Parser::ParseUsingDirectiveOrDeclaration(DeclaratorContext Context,
462
                                         const ParsedTemplateInfo &TemplateInfo,
463
                                         SourceLocation &DeclEnd,
464
167k
                                         ParsedAttributesWithRange &attrs) {
465
167k
  assert(Tok.is(tok::kw_using) && "Not using token");
466
167k
  ObjCDeclContextSwitch ObjCDC(*this);
467
167k
468
167k
  // Eat 'using'.
469
167k
  SourceLocation UsingLoc = ConsumeToken();
470
167k
471
167k
  if (Tok.is(tok::code_completion)) {
472
1
    Actions.CodeCompleteUsing(getCurScope());
473
1
    cutOffParsing();
474
1
    return nullptr;
475
1
  }
476
167k
477
167k
  // Consume unexpected 'template' keywords.
478
167k
  
while (167k
Tok.is(tok::kw_template)) {
479
5
    SourceLocation TemplateLoc = ConsumeToken();
480
5
    Diag(TemplateLoc, diag::err_unexpected_template_after_using)
481
5
        << FixItHint::CreateRemoval(TemplateLoc);
482
5
  }
483
167k
484
167k
  // 'using namespace' means this is a using-directive.
485
167k
  if (Tok.is(tok::kw_namespace)) {
486
20.0k
    // Template parameters are always an error here.
487
20.0k
    if (TemplateInfo.Kind) {
488
1
      SourceRange R = TemplateInfo.getSourceRange();
489
1
      Diag(UsingLoc, diag::err_templated_using_directive_declaration)
490
1
        << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
491
1
    }
492
20.0k
493
20.0k
    Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
494
20.0k
    return Actions.ConvertDeclToDeclGroup(UsingDir);
495
20.0k
  }
496
147k
497
147k
  // Otherwise, it must be a using-declaration or an alias-declaration.
498
147k
499
147k
  // Using declarations can't have attributes.
500
147k
  ProhibitAttributes(attrs);
501
147k
502
147k
  return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
503
147k
                               AS_none);
504
147k
}
505
506
/// ParseUsingDirective - Parse C++ using-directive, assumes
507
/// that current token is 'namespace' and 'using' was already parsed.
508
///
509
///       using-directive: [C++ 7.3.p4: namespace.udir]
510
///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
511
///                 namespace-name ;
512
/// [GNU] using-directive:
513
///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
514
///                 namespace-name attributes[opt] ;
515
///
516
Decl *Parser::ParseUsingDirective(DeclaratorContext Context,
517
                                  SourceLocation UsingLoc,
518
                                  SourceLocation &DeclEnd,
519
20.0k
                                  ParsedAttributes &attrs) {
520
20.0k
  assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
521
20.0k
522
20.0k
  // Eat 'namespace'.
523
20.0k
  SourceLocation NamespcLoc = ConsumeToken();
524
20.0k
525
20.0k
  if (Tok.is(tok::code_completion)) {
526
1
    Actions.CodeCompleteUsingDirective(getCurScope());
527
1
    cutOffParsing();
528
1
    return nullptr;
529
1
  }
530
20.0k
531
20.0k
  CXXScopeSpec SS;
532
20.0k
  // Parse (optional) nested-name-specifier.
533
20.0k
  ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
534
20.0k
                                 /*MayBePseudoDestructor=*/nullptr,
535
20.0k
                                 /*IsTypename=*/false,
536
20.0k
                                 /*LastII=*/nullptr,
537
20.0k
                                 /*OnlyNamespace=*/true);
538
20.0k
539
20.0k
  IdentifierInfo *NamespcName = nullptr;
540
20.0k
  SourceLocation IdentLoc = SourceLocation();
541
20.0k
542
20.0k
  // Parse namespace-name.
543
20.0k
  if (Tok.isNot(tok::identifier)) {
544
1
    Diag(Tok, diag::err_expected_namespace_name);
545
1
    // If there was invalid namespace name, skip to end of decl, and eat ';'.
546
1
    SkipUntil(tok::semi);
547
1
    // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
548
1
    return nullptr;
549
1
  }
550
20.0k
551
20.0k
  if (SS.isInvalid()) {
552
4
    // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
553
4
    // Skip to end of the definition and eat the ';'.
554
4
    SkipUntil(tok::semi);
555
4
    return nullptr;
556
4
  }
557
20.0k
558
20.0k
  // Parse identifier.
559
20.0k
  NamespcName = Tok.getIdentifierInfo();
560
20.0k
  IdentLoc = ConsumeToken();
561
20.0k
562
20.0k
  // Parse (optional) attributes (most likely GNU strong-using extension).
563
20.0k
  bool GNUAttr = false;
564
20.0k
  if (Tok.is(tok::kw___attribute)) {
565
0
    GNUAttr = true;
566
0
    ParseGNUAttributes(attrs);
567
0
  }
568
20.0k
569
20.0k
  // Eat ';'.
570
20.0k
  DeclEnd = Tok.getLocation();
571
20.0k
  if (ExpectAndConsume(tok::semi,
572
20.0k
                       GNUAttr ? 
diag::err_expected_semi_after_attribute_list0
573
20.0k
                               : diag::err_expected_semi_after_namespace_name))
574
1
    SkipUntil(tok::semi);
575
20.0k
576
20.0k
  return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
577
20.0k
                                     IdentLoc, NamespcName, attrs);
578
20.0k
}
579
580
/// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
581
///
582
///     using-declarator:
583
///       'typename'[opt] nested-name-specifier unqualified-id
584
///
585
bool Parser::ParseUsingDeclarator(DeclaratorContext Context,
586
184k
                                  UsingDeclarator &D) {
587
184k
  D.clear();
588
184k
589
184k
  // Ignore optional 'typename'.
590
184k
  // FIXME: This is wrong; we should parse this as a typename-specifier.
591
184k
  TryConsumeToken(tok::kw_typename, D.TypenameLoc);
592
184k
593
184k
  if (Tok.is(tok::kw___super)) {
594
1
    Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
595
1
    return true;
596
1
  }
597
184k
598
184k
  // Parse nested-name-specifier.
599
184k
  IdentifierInfo *LastII = nullptr;
600
184k
  if (ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
601
184k
                                     /*MayBePseudoDtor=*/nullptr,
602
184k
                                     /*IsTypename=*/false,
603
184k
                                     /*LastII=*/&LastII))
604
0
    return true;
605
184k
  if (D.SS.isInvalid())
606
4
    return true;
607
184k
608
184k
  // Parse the unqualified-id. We allow parsing of both constructor and
609
184k
  // destructor names and allow the action module to diagnose any semantic
610
184k
  // errors.
611
184k
  //
612
184k
  // C++11 [class.qual]p2:
613
184k
  //   [...] in a using-declaration that is a member-declaration, if the name
614
184k
  //   specified after the nested-name-specifier is the same as the identifier
615
184k
  //   or the simple-template-id's template-name in the last component of the
616
184k
  //   nested-name-specifier, the name is [...] considered to name the
617
184k
  //   constructor.
618
184k
  if (getLangOpts().CPlusPlus11 &&
619
184k
      
Context == DeclaratorContext::MemberContext176k
&&
620
184k
      
Tok.is(tok::identifier)35.6k
&&
621
184k
      
(35.5k
NextToken().is(tok::semi)35.5k
||
NextToken().is(tok::comma)34.5k
||
622
35.5k
       
NextToken().is(tok::ellipsis)34.5k
) &&
623
184k
      
D.SS.isNotEmpty()952
&&
LastII == Tok.getIdentifierInfo()952
&&
624
184k
      
!D.SS.getScopeRep()->getAsNamespace()287
&&
625
184k
      
!D.SS.getScopeRep()->getAsNamespaceAlias()286
) {
626
286
    SourceLocation IdLoc = ConsumeToken();
627
286
    ParsedType Type =
628
286
        Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
629
286
    D.Name.setConstructorName(Type, IdLoc, IdLoc);
630
184k
  } else {
631
184k
    if (ParseUnqualifiedId(
632
184k
            D.SS, /*EnteringContext=*/false,
633
184k
            /*AllowDestructorName=*/true,
634
184k
            /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
635
184k
                                       
NextToken().is(tok::equal)184k
),
636
184k
            /*AllowDeductionGuide=*/false,
637
184k
            nullptr, nullptr, D.Name))
638
2
      return true;
639
184k
  }
640
184k
641
184k
  if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
642
16
    Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
643
16
         diag::warn_cxx17_compat_using_declaration_pack :
644
16
         
diag::ext_using_declaration_pack0
);
645
184k
646
184k
  return false;
647
184k
}
648
649
/// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
650
/// Assumes that 'using' was already seen.
651
///
652
///     using-declaration: [C++ 7.3.p3: namespace.udecl]
653
///       'using' using-declarator-list[opt] ;
654
///
655
///     using-declarator-list: [C++1z]
656
///       using-declarator '...'[opt]
657
///       using-declarator-list ',' using-declarator '...'[opt]
658
///
659
///     using-declarator-list: [C++98-14]
660
///       using-declarator
661
///
662
///     alias-declaration: C++11 [dcl.dcl]p1
663
///       'using' identifier attribute-specifier-seq[opt] = type-id ;
664
///
665
Parser::DeclGroupPtrTy
666
Parser::ParseUsingDeclaration(DeclaratorContext Context,
667
                              const ParsedTemplateInfo &TemplateInfo,
668
                              SourceLocation UsingLoc, SourceLocation &DeclEnd,
669
184k
                              AccessSpecifier AS) {
670
184k
  // Check for misplaced attributes before the identifier in an
671
184k
  // alias-declaration.
672
184k
  ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
673
184k
  MaybeParseCXX11Attributes(MisplacedAttrs);
674
184k
675
184k
  UsingDeclarator D;
676
184k
  bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
677
184k
678
184k
  ParsedAttributesWithRange Attrs(AttrFactory);
679
184k
  MaybeParseGNUAttributes(Attrs);
680
184k
  MaybeParseCXX11Attributes(Attrs);
681
184k
682
184k
  // Maybe this is an alias-declaration.
683
184k
  if (Tok.is(tok::equal)) {
684
72.0k
    if (InvalidDeclarator) {
685
0
      SkipUntil(tok::semi);
686
0
      return nullptr;
687
0
    }
688
72.0k
689
72.0k
    // If we had any misplaced attributes from earlier, this is where they
690
72.0k
    // should have been written.
691
72.0k
    if (MisplacedAttrs.Range.isValid()) {
692
2
      Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
693
2
        << FixItHint::CreateInsertionFromRange(
694
2
               Tok.getLocation(),
695
2
               CharSourceRange::getTokenRange(MisplacedAttrs.Range))
696
2
        << FixItHint::CreateRemoval(MisplacedAttrs.Range);
697
2
      Attrs.takeAllFrom(MisplacedAttrs);
698
2
    }
699
72.0k
700
72.0k
    Decl *DeclFromDeclSpec = nullptr;
701
72.0k
    Decl *AD = ParseAliasDeclarationAfterDeclarator(
702
72.0k
        TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
703
72.0k
    return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
704
72.0k
  }
705
112k
706
112k
  // C++11 attributes are not allowed on a using-declaration, but GNU ones
707
112k
  // are.
708
112k
  ProhibitAttributes(MisplacedAttrs);
709
112k
  ProhibitAttributes(Attrs);
710
112k
711
112k
  // Diagnose an attempt to declare a templated using-declaration.
712
112k
  // In C++11, alias-declarations can be templates:
713
112k
  //   template <...> using id = type;
714
112k
  if (TemplateInfo.Kind) {
715
4
    SourceRange R = TemplateInfo.getSourceRange();
716
4
    Diag(UsingLoc, diag::err_templated_using_directive_declaration)
717
4
      << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
718
4
719
4
    // Unfortunately, we have to bail out instead of recovering by
720
4
    // ignoring the parameters, just in case the nested name specifier
721
4
    // depends on the parameters.
722
4
    return nullptr;
723
4
  }
724
112k
725
112k
  SmallVector<Decl *, 8> DeclsInGroup;
726
112k
  while (true) {
727
112k
    // Parse (optional) attributes (most likely GNU strong-using extension).
728
112k
    MaybeParseGNUAttributes(Attrs);
729
112k
730
112k
    if (InvalidDeclarator)
731
7
      SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
732
112k
    else {
733
112k
      // "typename" keyword is allowed for identifiers only,
734
112k
      // because it may be a type definition.
735
112k
      if (D.TypenameLoc.isValid() &&
736
112k
          
D.Name.getKind() != UnqualifiedIdKind::IK_Identifier187
) {
737
6
        Diag(D.Name.getSourceRange().getBegin(),
738
6
             diag::err_typename_identifiers_only)
739
6
            << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
740
6
        // Proceed parsing, but discard the typename keyword.
741
6
        D.TypenameLoc = SourceLocation();
742
6
      }
743
112k
744
112k
      Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
745
112k
                                               D.TypenameLoc, D.SS, D.Name,
746
112k
                                               D.EllipsisLoc, Attrs);
747
112k
      if (UD)
748
112k
        DeclsInGroup.push_back(UD);
749
112k
    }
750
112k
751
112k
    if (!TryConsumeToken(tok::comma))
752
112k
      break;
753
8
754
8
    // Parse another using-declarator.
755
8
    Attrs.clear();
756
8
    InvalidDeclarator = ParseUsingDeclarator(Context, D);
757
8
  }
758
112k
759
112k
  if (DeclsInGroup.size() > 1)
760
2
    Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
761
2
         diag::warn_cxx17_compat_multi_using_declaration :
762
2
         
diag::ext_multi_using_declaration0
);
763
112k
764
112k
  // Eat ';'.
765
112k
  DeclEnd = Tok.getLocation();
766
112k
  if (ExpectAndConsume(tok::semi, diag::err_expected_after,
767
112k
                       !Attrs.empty() ? 
"attributes list"0
768
112k
                                      : "using declaration"))
769
3
    SkipUntil(tok::semi);
770
112k
771
112k
  return Actions.BuildDeclaratorGroup(DeclsInGroup);
772
112k
}
773
774
Decl *Parser::ParseAliasDeclarationAfterDeclarator(
775
    const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
776
    UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
777
72.0k
    ParsedAttributes &Attrs, Decl **OwnedType) {
778
72.0k
  if (ExpectAndConsume(tok::equal)) {
779
0
    SkipUntil(tok::semi);
780
0
    return nullptr;
781
0
  }
782
72.0k
783
72.0k
  Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
784
69.3k
       diag::warn_cxx98_compat_alias_declaration :
785
72.0k
       
diag::ext_alias_declaration2.70k
);
786
72.0k
787
72.0k
  // Type alias templates cannot be specialized.
788
72.0k
  int SpecKind = -1;
789
72.0k
  if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
790
72.0k
      
D.Name.getKind() == UnqualifiedIdKind::IK_TemplateId51.1k
)
791
1
    SpecKind = 0;
792
72.0k
  if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
793
1
    SpecKind = 1;
794
72.0k
  if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
795
1
    SpecKind = 2;
796
72.0k
  if (SpecKind != -1) {
797
3
    SourceRange Range;
798
3
    if (SpecKind == 0)
799
1
      Range = SourceRange(D.Name.TemplateId->LAngleLoc,
800
1
                          D.Name.TemplateId->RAngleLoc);
801
2
    else
802
2
      Range = TemplateInfo.getSourceRange();
803
3
    Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
804
3
      << SpecKind << Range;
805
3
    SkipUntil(tok::semi);
806
3
    return nullptr;
807
3
  }
808
72.0k
809
72.0k
  // Name must be an identifier.
810
72.0k
  if (D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
811
5
    Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
812
5
    // No removal fixit: can't recover from this.
813
5
    SkipUntil(tok::semi);
814
5
    return nullptr;
815
72.0k
  } else if (D.TypenameLoc.isValid())
816
8
    Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
817
8
        << FixItHint::CreateRemoval(SourceRange(
818
8
               D.TypenameLoc,
819
8
               D.SS.isNotEmpty() ? 
D.SS.getEndLoc()4
:
D.TypenameLoc4
));
820
72.0k
  else if (D.SS.isNotEmpty())
821
4
    Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
822
4
      << FixItHint::CreateRemoval(D.SS.getRange());
823
72.0k
  
if (72.0k
D.EllipsisLoc.isValid()72.0k
)
824
0
    Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
825
0
      << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
826
72.0k
827
72.0k
  Decl *DeclFromDeclSpec = nullptr;
828
72.0k
  TypeResult TypeAlias = ParseTypeName(
829
72.0k
      nullptr,
830
72.0k
      TemplateInfo.Kind ? 
DeclaratorContext::AliasTemplateContext51.1k
831
72.0k
                        : 
DeclaratorContext::AliasDeclContext20.9k
,
832
72.0k
      AS, &DeclFromDeclSpec, &Attrs);
833
72.0k
  if (OwnedType)
834
72.0k
    *OwnedType = DeclFromDeclSpec;
835
72.0k
836
72.0k
  // Eat ';'.
837
72.0k
  DeclEnd = Tok.getLocation();
838
72.0k
  if (ExpectAndConsume(tok::semi, diag::err_expected_after,
839
72.0k
                       !Attrs.empty() ? 
"attributes list"25.5k
840
72.0k
                                      : 
"alias declaration"46.5k
))
841
11
    SkipUntil(tok::semi);
842
72.0k
843
72.0k
  TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
844
72.0k
  MultiTemplateParamsArg TemplateParamsArg(
845
72.0k
    TemplateParams ? 
TemplateParams->data()51.1k
:
nullptr20.9k
,
846
72.0k
    TemplateParams ? 
TemplateParams->size()51.1k
:
020.9k
);
847
72.0k
  return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
848
72.0k
                                       UsingLoc, D.Name, Attrs, TypeAlias,
849
72.0k
                                       DeclFromDeclSpec);
850
72.0k
}
851
852
/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
853
///
854
/// [C++0x] static_assert-declaration:
855
///           static_assert ( constant-expression  ,  string-literal  ) ;
856
///
857
/// [C11]   static_assert-declaration:
858
///           _Static_assert ( constant-expression  ,  string-literal  ) ;
859
///
860
43.7k
Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
861
43.7k
  assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
862
43.7k
         "Not a static_assert declaration");
863
43.7k
864
43.7k
  if (Tok.is(tok::kw__Static_assert) && 
!getLangOpts().C112.83k
)
865
2.54k
    Diag(Tok, diag::ext_c11_static_assert);
866
43.7k
  if (Tok.is(tok::kw_static_assert))
867
40.8k
    Diag(Tok, diag::warn_cxx98_compat_static_assert);
868
43.7k
869
43.7k
  SourceLocation StaticAssertLoc = ConsumeToken();
870
43.7k
871
43.7k
  BalancedDelimiterTracker T(*this, tok::l_paren);
872
43.7k
  if (T.consumeOpen()) {
873
0
    Diag(Tok, diag::err_expected) << tok::l_paren;
874
0
    SkipMalformedDecl();
875
0
    return nullptr;
876
0
  }
877
43.7k
878
43.7k
  EnterExpressionEvaluationContext ConstantEvaluated(
879
43.7k
      Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
880
43.7k
  ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
881
43.7k
  if (AssertExpr.isInvalid()) {
882
61
    SkipMalformedDecl();
883
61
    return nullptr;
884
61
  }
885
43.6k
886
43.6k
  ExprResult AssertMessage;
887
43.6k
  if (Tok.is(tok::r_paren)) {
888
3.09k
    Diag(Tok, getLangOpts().CPlusPlus17
889
3.09k
                  ? 
diag::warn_cxx14_compat_static_assert_no_message3.08k
890
3.09k
                  : 
diag::ext_static_assert_no_message11
)
891
3.09k
      << (getLangOpts().CPlusPlus17
892
3.09k
              ? 
FixItHint()3.08k
893
3.09k
              : 
FixItHint::CreateInsertion(Tok.getLocation(), ", \"\"")11
);
894
40.5k
  } else {
895
40.5k
    if (ExpectAndConsume(tok::comma)) {
896
0
      SkipUntil(tok::semi);
897
0
      return nullptr;
898
0
    }
899
40.5k
900
40.5k
    if (!isTokenStringLiteral()) {
901
2
      Diag(Tok, diag::err_expected_string_literal)
902
2
        << /*Source='static_assert'*/1;
903
2
      SkipMalformedDecl();
904
2
      return nullptr;
905
2
    }
906
40.5k
907
40.5k
    AssertMessage = ParseStringLiteralExpression();
908
40.5k
    if (AssertMessage.isInvalid()) {
909
1
      SkipMalformedDecl();
910
1
      return nullptr;
911
1
    }
912
43.6k
  }
913
43.6k
914
43.6k
  T.consumeClose();
915
43.6k
916
43.6k
  DeclEnd = Tok.getLocation();
917
43.6k
  ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
918
43.6k
919
43.6k
  return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
920
43.6k
                                              AssertExpr.get(),
921
43.6k
                                              AssertMessage.get(),
922
43.6k
                                              T.getCloseLocation());
923
43.6k
}
924
925
/// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
926
///
927
/// 'decltype' ( expression )
928
/// 'decltype' ( 'auto' )      [C++1y]
929
///
930
86.2k
SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
931
86.2k
  assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
932
86.2k
           && "Not a decltype specifier");
933
86.2k
934
86.2k
  ExprResult Result;
935
86.2k
  SourceLocation StartLoc = Tok.getLocation();
936
86.2k
  SourceLocation EndLoc;
937
86.2k
938
86.2k
  if (Tok.is(tok::annot_decltype)) {
939
42.3k
    Result = getExprAnnotation(Tok);
940
42.3k
    EndLoc = Tok.getAnnotationEndLoc();
941
42.3k
    ConsumeAnnotationToken();
942
42.3k
    if (Result.isInvalid()) {
943
48
      DS.SetTypeSpecError();
944
48
      return EndLoc;
945
48
    }
946
43.8k
  } else {
947
43.8k
    if (Tok.getIdentifierInfo()->isStr("decltype"))
948
41.3k
      Diag(Tok, diag::warn_cxx98_compat_decltype);
949
43.8k
950
43.8k
    ConsumeToken();
951
43.8k
952
43.8k
    BalancedDelimiterTracker T(*this, tok::l_paren);
953
43.8k
    if (T.expectAndConsume(diag::err_expected_lparen_after,
954
43.8k
                           "decltype", tok::r_paren)) {
955
1
      DS.SetTypeSpecError();
956
1
      return T.getOpenLocation() == Tok.getLocation() ?
957
1
             StartLoc : 
T.getOpenLocation()0
;
958
1
    }
959
43.8k
960
43.8k
    // Check for C++1y 'decltype(auto)'.
961
43.8k
    if (Tok.is(tok::kw_auto)) {
962
181
      // No need to disambiguate here: an expression can't start with 'auto',
963
181
      // because the typename-specifier in a function-style cast operation can't
964
181
      // be 'auto'.
965
181
      Diag(Tok.getLocation(),
966
181
           getLangOpts().CPlusPlus14
967
181
             ? 
diag::warn_cxx11_compat_decltype_auto_type_specifier164
968
181
             : 
diag::ext_decltype_auto_type_specifier17
);
969
181
      ConsumeToken();
970
43.6k
    } else {
971
43.6k
      // Parse the expression
972
43.6k
973
43.6k
      // C++11 [dcl.type.simple]p4:
974
43.6k
      //   The operand of the decltype specifier is an unevaluated operand.
975
43.6k
      EnterExpressionEvaluationContext Unevaluated(
976
43.6k
          Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
977
43.6k
          Sema::ExpressionEvaluationContextRecord::EK_Decltype);
978
43.6k
      Result =
979
43.6k
          Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
980
7
            return E->hasPlaceholderType() ? 
ExprError()1
:
E6
;
981
7
          });
982
43.6k
      if (Result.isInvalid()) {
983
42
        DS.SetTypeSpecError();
984
42
        if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
985
39
          EndLoc = ConsumeParen();
986
39
        } else {
987
3
          if (PP.isBacktrackEnabled() && 
Tok.is(tok::semi)1
) {
988
1
            // Backtrack to get the location of the last token before the semi.
989
1
            PP.RevertCachedTokens(2);
990
1
            ConsumeToken(); // the semi.
991
1
            EndLoc = ConsumeAnyToken();
992
1
            assert(Tok.is(tok::semi));
993
2
          } else {
994
2
            EndLoc = Tok.getLocation();
995
2
          }
996
3
        }
997
42
        return EndLoc;
998
42
      }
999
43.5k
1000
43.5k
      Result = Actions.ActOnDecltypeExpression(Result.get());
1001
43.5k
    }
1002
43.8k
1003
43.8k
    // Match the ')'
1004
43.8k
    T.consumeClose();
1005
43.7k
    if (T.getCloseLocation().isInvalid()) {
1006
0
      DS.SetTypeSpecError();
1007
0
      // FIXME: this should return the location of the last token
1008
0
      //        that was consumed (by "consumeClose()")
1009
0
      return T.getCloseLocation();
1010
0
    }
1011
43.7k
1012
43.7k
    if (Result.isInvalid()) {
1013
9
      DS.SetTypeSpecError();
1014
9
      return T.getCloseLocation();
1015
9
    }
1016
43.7k
1017
43.7k
    EndLoc = T.getCloseLocation();
1018
43.7k
  }
1019
86.2k
  assert(!Result.isInvalid());
1020
86.1k
1021
86.1k
  const char *PrevSpec = nullptr;
1022
86.1k
  unsigned DiagID;
1023
86.1k
  const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1024
86.1k
  // Check for duplicate type specifiers (e.g. "int decltype(a)").
1025
86.1k
  if (Result.get()
1026
86.1k
        ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
1027
85.7k
                             DiagID, Result.get(), Policy)
1028
86.1k
        : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
1029
360
                             DiagID, Policy)) {
1030
0
    Diag(StartLoc, DiagID) << PrevSpec;
1031
0
    DS.SetTypeSpecError();
1032
0
  }
1033
86.1k
  return EndLoc;
1034
86.2k
}
1035
1036
void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
1037
                                               SourceLocation StartLoc,
1038
42.3k
                                               SourceLocation EndLoc) {
1039
42.3k
  // make sure we have a token we can turn into an annotation token
1040
42.3k
  if (PP.isBacktrackEnabled())
1041
106
    PP.RevertCachedTokens(1);
1042
42.2k
  else
1043
42.2k
    PP.EnterToken(Tok, /*IsReinject*/true);
1044
42.3k
1045
42.3k
  Tok.setKind(tok::annot_decltype);
1046
42.3k
  setExprAnnotation(Tok,
1047
42.3k
                    DS.getTypeSpecType() == TST_decltype ? 
DS.getRepAsExpr()42.1k
:
1048
42.3k
                    
DS.getTypeSpecType() == TST_decltype_auto 228
?
ExprResult()179
:
1049
228
                    
ExprError()49
);
1050
42.3k
  Tok.setAnnotationEndLoc(EndLoc);
1051
42.3k
  Tok.setLocation(StartLoc);
1052
42.3k
  PP.AnnotateCachedTokens(Tok);
1053
42.3k
}
1054
1055
822
void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1056
822
  assert(Tok.is(tok::kw___underlying_type) &&
1057
822
         "Not an underlying type specifier");
1058
822
1059
822
  SourceLocation StartLoc = ConsumeToken();
1060
822
  BalancedDelimiterTracker T(*this, tok::l_paren);
1061
822
  if (T.expectAndConsume(diag::err_expected_lparen_after,
1062
822
                       "__underlying_type", tok::r_paren)) {
1063
0
    return;
1064
0
  }
1065
822
1066
822
  TypeResult Result = ParseTypeName();
1067
822
  if (Result.isInvalid()) {
1068
0
    SkipUntil(tok::r_paren, StopAtSemi);
1069
0
    return;
1070
0
  }
1071
822
1072
822
  // Match the ')'
1073
822
  T.consumeClose();
1074
822
  if (T.getCloseLocation().isInvalid())
1075
0
    return;
1076
822
1077
822
  const char *PrevSpec = nullptr;
1078
822
  unsigned DiagID;
1079
822
  if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
1080
822
                         DiagID, Result.get(),
1081
822
                         Actions.getASTContext().getPrintingPolicy()))
1082
0
    Diag(StartLoc, DiagID) << PrevSpec;
1083
822
  DS.setTypeofParensRange(T.getRange());
1084
822
}
1085
1086
/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
1087
/// class name or decltype-specifier. Note that we only check that the result
1088
/// names a type; semantic analysis will need to verify that the type names a
1089
/// class. The result is either a type or null, depending on whether a type
1090
/// name was found.
1091
///
1092
///       base-type-specifier: [C++11 class.derived]
1093
///         class-or-decltype
1094
///       class-or-decltype: [C++11 class.derived]
1095
///         nested-name-specifier[opt] class-name
1096
///         decltype-specifier
1097
///       class-name: [C++ class.name]
1098
///         identifier
1099
///         simple-template-id
1100
///
1101
/// In C++98, instead of base-type-specifier, we have:
1102
///
1103
///         ::[opt] nested-name-specifier[opt] class-name
1104
TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1105
266k
                                          SourceLocation &EndLocation) {
1106
266k
  // Ignore attempts to use typename
1107
266k
  if (Tok.is(tok::kw_typename)) {
1108
1
    Diag(Tok, diag::err_expected_class_name_not_template)
1109
1
      << FixItHint::CreateRemoval(Tok.getLocation());
1110
1
    ConsumeToken();
1111
1
  }
1112
266k
1113
266k
  // Parse optional nested-name-specifier
1114
266k
  CXXScopeSpec SS;
1115
266k
  if (ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false))
1116
32
    return true;
1117
266k
1118
266k
  BaseLoc = Tok.getLocation();
1119
266k
1120
266k
  // Parse decltype-specifier
1121
266k
  // tok == kw_decltype is just error recovery, it can only happen when SS
1122
266k
  // isn't empty
1123
266k
  if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
1124
791
    if (SS.isNotEmpty())
1125
2
      Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1126
2
        << FixItHint::CreateRemoval(SS.getRange());
1127
791
    // Fake up a Declarator to use with ActOnTypeName.
1128
791
    DeclSpec DS(AttrFactory);
1129
791
1130
791
    EndLocation = ParseDecltypeSpecifier(DS);
1131
791
1132
791
    Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1133
791
    return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1134
791
  }
1135
265k
1136
265k
  // Check whether we have a template-id that names a type.
1137
265k
  if (Tok.is(tok::annot_template_id)) {
1138
142k
    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1139
142k
    if (TemplateId->Kind == TNK_Type_template ||
1140
142k
        
TemplateId->Kind == TNK_Dependent_template_name98
||
1141
142k
        
TemplateId->Kind == TNK_Undeclared_template70
) {
1142
142k
      AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
1143
142k
1144
142k
      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
1145
142k
      ParsedType Type = getTypeAnnotation(Tok);
1146
142k
      EndLocation = Tok.getAnnotationEndLoc();
1147
142k
      ConsumeAnnotationToken();
1148
142k
1149
142k
      if (Type)
1150
142k
        return Type;
1151
194
      return true;
1152
194
    }
1153
142k
1154
142k
    // Fall through to produce an error below.
1155
142k
  }
1156
123k
1157
123k
  if (Tok.isNot(tok::identifier)) {
1158
7
    Diag(Tok, diag::err_expected_class_name);
1159
7
    return true;
1160
7
  }
1161
123k
1162
123k
  IdentifierInfo *Id = Tok.getIdentifierInfo();
1163
123k
  SourceLocation IdLoc = ConsumeToken();
1164
123k
1165
123k
  if (Tok.is(tok::less)) {
1166
2
    // It looks the user intended to write a template-id here, but the
1167
2
    // template-name was wrong. Try to fix that.
1168
2
    TemplateNameKind TNK = TNK_Type_template;
1169
2
    TemplateTy Template;
1170
2
    if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
1171
2
                                             &SS, Template, TNK)) {
1172
2
      Diag(IdLoc, diag::err_unknown_template_name)
1173
2
        << Id;
1174
2
    }
1175
2
1176
2
    if (!Template) {
1177
2
      TemplateArgList TemplateArgs;
1178
2
      SourceLocation LAngleLoc, RAngleLoc;
1179
2
      ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1180
2
                                       RAngleLoc);
1181
2
      return true;
1182
2
    }
1183
0
1184
0
    // Form the template name
1185
0
    UnqualifiedId TemplateName;
1186
0
    TemplateName.setIdentifier(Id, IdLoc);
1187
0
1188
0
    // Parse the full template-id, then turn it into a type.
1189
0
    if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1190
0
                                TemplateName))
1191
0
      return true;
1192
0
    if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
1193
0
      AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
1194
0
1195
0
    // If we didn't end up with a typename token, there's nothing more we
1196
0
    // can do.
1197
0
    if (Tok.isNot(tok::annot_typename))
1198
0
      return true;
1199
0
1200
0
    // Retrieve the type from the annotation token, consume that token, and
1201
0
    // return.
1202
0
    EndLocation = Tok.getAnnotationEndLoc();
1203
0
    ParsedType Type = getTypeAnnotation(Tok);
1204
0
    ConsumeAnnotationToken();
1205
0
    return Type;
1206
0
  }
1207
123k
1208
123k
  // We have an identifier; check whether it is actually a type.
1209
123k
  IdentifierInfo *CorrectedII = nullptr;
1210
123k
  ParsedType Type = Actions.getTypeName(
1211
123k
      *Id, IdLoc, getCurScope(), &SS, /*isClassName=*/true, false, nullptr,
1212
123k
      /*IsCtorOrDtorName=*/false,
1213
123k
      /*WantNontrivialTypeSourceInfo=*/true,
1214
123k
      /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
1215
123k
  if (!Type) {
1216
13
    Diag(IdLoc, diag::err_expected_class_name);
1217
13
    return true;
1218
13
  }
1219
123k
1220
123k
  // Consume the identifier.
1221
123k
  EndLocation = IdLoc;
1222
123k
1223
123k
  // Fake up a Declarator to use with ActOnTypeName.
1224
123k
  DeclSpec DS(AttrFactory);
1225
123k
  DS.SetRangeStart(IdLoc);
1226
123k
  DS.SetRangeEnd(EndLocation);
1227
123k
  DS.getTypeSpecScope() = SS;
1228
123k
1229
123k
  const char *PrevSpec = nullptr;
1230
123k
  unsigned DiagID;
1231
123k
  DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1232
123k
                     Actions.getASTContext().getPrintingPolicy());
1233
123k
1234
123k
  Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1235
123k
  return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1236
123k
}
1237
1238
58
void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
1239
116
  while (Tok.isOneOf(tok::kw___single_inheritance,
1240
116
                     tok::kw___multiple_inheritance,
1241
116
                     tok::kw___virtual_inheritance)) {
1242
58
    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1243
58
    SourceLocation AttrNameLoc = ConsumeToken();
1244
58
    attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1245
58
                 ParsedAttr::AS_Keyword);
1246
58
  }
1247
58
}
1248
1249
/// Determine whether the following tokens are valid after a type-specifier
1250
/// which could be a standalone declaration. This will conservatively return
1251
/// true if there's any doubt, and is appropriate for insert-';' fixits.
1252
582k
bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
1253
582k
  // This switch enumerates the valid "follow" set for type-specifiers.
1254
582k
  switch (Tok.getKind()) {
1255
582k
  
default: break140
;
1256
582k
  case tok::semi:               // struct foo {...} ;
1257
581k
  case tok::star:               // struct foo {...} *         P;
1258
581k
  case tok::amp:                // struct foo {...} &         R = ...
1259
581k
  case tok::ampamp:             // struct foo {...} &&        R = ...
1260
581k
  case tok::identifier:         // struct foo {...} V         ;
1261
581k
  case tok::r_paren:            //(struct foo {...} )         {4}
1262
581k
  case tok::coloncolon:         // struct foo {...} ::        a::b;
1263
581k
  case tok::annot_cxxscope:     // struct foo {...} a::       b;
1264
581k
  case tok::annot_typename:     // struct foo {...} a         ::b;
1265
581k
  case tok::annot_template_id:  // struct foo {...} a<int>    ::b;
1266
581k
  case tok::kw_decltype:        // struct foo {...} decltype  (a)::b;
1267
581k
  case tok::l_paren:            // struct foo {...} (         x);
1268
581k
  case tok::comma:              // __builtin_offsetof(struct foo{...} ,
1269
581k
  case tok::kw_operator:        // struct foo       operator  ++() {...}
1270
581k
  case tok::kw___declspec:      // struct foo {...} __declspec(...)
1271
581k
  case tok::l_square:           // void f(struct f  [         3])
1272
581k
  case tok::ellipsis:           // void f(struct f  ...       [Ns])
1273
581k
  // FIXME: we should emit semantic diagnostic when declaration
1274
581k
  // attribute is in type attribute position.
1275
581k
  case tok::kw___attribute:     // struct foo __attribute__((used)) x;
1276
581k
  case tok::annot_pragma_pack:  // struct foo {...} _Pragma(pack(pop));
1277
581k
  // struct foo {...} _Pragma(section(...));
1278
581k
  case tok::annot_pragma_ms_pragma:
1279
581k
  // struct foo {...} _Pragma(vtordisp(pop));
1280
581k
  case tok::annot_pragma_ms_vtordisp:
1281
581k
  // struct foo {...} _Pragma(pointers_to_members(...));
1282
581k
  case tok::annot_pragma_ms_pointers_to_members:
1283
581k
    return true;
1284
581k
  case tok::colon:
1285
3
    return CouldBeBitfield;     // enum E { ... }   :         2;
1286
581k
  // Microsoft compatibility
1287
581k
  case tok::kw___cdecl:         // struct foo {...} __cdecl      x;
1288
1
  case tok::kw___fastcall:      // struct foo {...} __fastcall   x;
1289
1
  case tok::kw___stdcall:       // struct foo {...} __stdcall    x;
1290
1
  case tok::kw___thiscall:      // struct foo {...} __thiscall   x;
1291
1
  case tok::kw___vectorcall:    // struct foo {...} __vectorcall x;
1292
1
    // We will diagnose these calling-convention specifiers on non-function
1293
1
    // declarations later, so claim they are valid after a type specifier.
1294
1
    return getLangOpts().MicrosoftExt;
1295
1
  // Type qualifiers
1296
173
  case tok::kw_const:           // struct foo {...} const     x;
1297
173
  case tok::kw_volatile:        // struct foo {...} volatile  x;
1298
173
  case tok::kw_restrict:        // struct foo {...} restrict  x;
1299
173
  case tok::kw__Atomic:         // struct foo {...} _Atomic   x;
1300
173
  case tok::kw___unaligned:     // struct foo {...} __unaligned *x;
1301
173
  // Function specifiers
1302
173
  // Note, no 'explicit'. An explicit function must be either a conversion
1303
173
  // operator or a constructor. Either way, it can't have a return type.
1304
173
  case tok::kw_inline:          // struct foo       inline    f();
1305
173
  case tok::kw_virtual:         // struct foo       virtual   f();
1306
173
  case tok::kw_friend:          // struct foo       friend    f();
1307
173
  // Storage-class specifiers
1308
173
  case tok::kw_static:          // struct foo {...} static    x;
1309
173
  case tok::kw_extern:          // struct foo {...} extern    x;
1310
173
  case tok::kw_typedef:         // struct foo {...} typedef   x;
1311
173
  case tok::kw_register:        // struct foo {...} register  x;
1312
173
  case tok::kw_auto:            // struct foo {...} auto      x;
1313
173
  case tok::kw_mutable:         // struct foo {...} mutable   x;
1314
173
  case tok::kw_thread_local:    // struct foo {...} thread_local x;
1315
173
  case tok::kw_constexpr:       // struct foo {...} constexpr x;
1316
173
    // As shown above, type qualifiers and storage class specifiers absolutely
1317
173
    // can occur after class specifiers according to the grammar.  However,
1318
173
    // almost no one actually writes code like this.  If we see one of these,
1319
173
    // it is much more likely that someone missed a semi colon and the
1320
173
    // type/storage class specifier we're seeing is part of the *next*
1321
173
    // intended declaration, as in:
1322
173
    //
1323
173
    //   struct foo { ... }
1324
173
    //   typedef int X;
1325
173
    //
1326
173
    // We'd really like to emit a missing semicolon error instead of emitting
1327
173
    // an error on the 'int' saying that you can't have two type specifiers in
1328
173
    // the same declaration of X.  Because of this, we look ahead past this
1329
173
    // token to see if it's a type specifier.  If so, we know the code is
1330
173
    // otherwise invalid, so we can produce the expected semi error.
1331
173
    if (!isKnownToBeTypeSpecifier(NextToken()))
1332
171
      return true;
1333
2
    break;
1334
6
  case tok::r_brace:  // struct bar { struct foo {...} }
1335
6
    // Missing ';' at end of struct is accepted as an extension in C mode.
1336
6
    if (!getLangOpts().CPlusPlus)
1337
2
      return true;
1338
4
    break;
1339
4
  case tok::greater:
1340
3
    // template<class T = class X>
1341
3
    return getLangOpts().CPlusPlus;
1342
146
  }
1343
146
  return false;
1344
146
}
1345
1346
/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1347
/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1348
/// until we reach the start of a definition or see a token that
1349
/// cannot start a definition.
1350
///
1351
///       class-specifier: [C++ class]
1352
///         class-head '{' member-specification[opt] '}'
1353
///         class-head '{' member-specification[opt] '}' attributes[opt]
1354
///       class-head:
1355
///         class-key identifier[opt] base-clause[opt]
1356
///         class-key nested-name-specifier identifier base-clause[opt]
1357
///         class-key nested-name-specifier[opt] simple-template-id
1358
///                          base-clause[opt]
1359
/// [GNU]   class-key attributes[opt] identifier[opt] base-clause[opt]
1360
/// [GNU]   class-key attributes[opt] nested-name-specifier
1361
///                          identifier base-clause[opt]
1362
/// [GNU]   class-key attributes[opt] nested-name-specifier[opt]
1363
///                          simple-template-id base-clause[opt]
1364
///       class-key:
1365
///         'class'
1366
///         'struct'
1367
///         'union'
1368
///
1369
///       elaborated-type-specifier: [C++ dcl.type.elab]
1370
///         class-key ::[opt] nested-name-specifier[opt] identifier
1371
///         class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1372
///                          simple-template-id
1373
///
1374
///  Note that the C++ class-specifier and elaborated-type-specifier,
1375
///  together, subsume the C99 struct-or-union-specifier:
1376
///
1377
///       struct-or-union-specifier: [C99 6.7.2.1]
1378
///         struct-or-union identifier[opt] '{' struct-contents '}'
1379
///         struct-or-union identifier
1380
/// [GNU]   struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1381
///                                                         '}' attributes[opt]
1382
/// [GNU]   struct-or-union attributes[opt] identifier
1383
///       struct-or-union:
1384
///         'struct'
1385
///         'union'
1386
void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1387
                                 SourceLocation StartLoc, DeclSpec &DS,
1388
                                 const ParsedTemplateInfo &TemplateInfo,
1389
                                 AccessSpecifier AS,
1390
                                 bool EnteringContext, DeclSpecContext DSC,
1391
1.45M
                                 ParsedAttributesWithRange &Attributes) {
1392
1.45M
  DeclSpec::TST TagType;
1393
1.45M
  if (TagTokKind == tok::kw_struct)
1394
1.18M
    TagType = DeclSpec::TST_struct;
1395
274k
  else if (TagTokKind == tok::kw___interface)
1396
32
    TagType = DeclSpec::TST_interface;
1397
274k
  else if (TagTokKind == tok::kw_class)
1398
212k
    TagType = DeclSpec::TST_class;
1399
62.0k
  else {
1400
62.0k
    assert(TagTokKind == tok::kw_union && "Not a class specifier");
1401
62.0k
    TagType = DeclSpec::TST_union;
1402
62.0k
  }
1403
1.45M
1404
1.45M
  if (Tok.is(tok::code_completion)) {
1405
11
    // Code completion for a struct, class, or union name.
1406
11
    Actions.CodeCompleteTag(getCurScope(), TagType);
1407
11
    return cutOffParsing();
1408
11
  }
1409
1.45M
1410
1.45M
  // C++03 [temp.explicit] 14.7.2/8:
1411
1.45M
  //   The usual access checking rules do not apply to names used to specify
1412
1.45M
  //   explicit instantiations.
1413
1.45M
  //
1414
1.45M
  // As an extension we do not perform access checking on the names used to
1415
1.45M
  // specify explicit specializations either. This is important to allow
1416
1.45M
  // specializing traits classes for private types.
1417
1.45M
  //
1418
1.45M
  // Note that we don't suppress if this turns out to be an elaborated
1419
1.45M
  // type specifier.
1420
1.45M
  bool shouldDelayDiagsInTag =
1421
1.45M
    (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1422
1.45M
     
TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization1.44M
);
1423
1.45M
  SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1424
1.45M
1425
1.45M
  ParsedAttributesWithRange attrs(AttrFactory);
1426
1.45M
  // If attributes exist after tag, parse them.
1427
1.45M
  MaybeParseGNUAttributes(attrs);
1428
1.45M
  MaybeParseMicrosoftDeclSpecs(attrs);
1429
1.45M
1430
1.45M
  // Parse inheritance specifiers.
1431
1.45M
  if (Tok.isOneOf(tok::kw___single_inheritance,
1432
1.45M
                  tok::kw___multiple_inheritance,
1433
1.45M
                  tok::kw___virtual_inheritance))
1434
58
    ParseMicrosoftInheritanceClassAttributes(attrs);
1435
1.45M
1436
1.45M
  // If C++0x attributes exist here, parse them.
1437
1.45M
  // FIXME: Are we consistent with the ordering of parsing of different
1438
1.45M
  // styles of attributes?
1439
1.45M
  MaybeParseCXX11Attributes(attrs);
1440
1.45M
1441
1.45M
  // Source location used by FIXIT to insert misplaced
1442
1.45M
  // C++11 attributes
1443
1.45M
  SourceLocation AttrFixitLoc = Tok.getLocation();
1444
1.45M
1445
1.45M
  if (TagType == DeclSpec::TST_struct &&
1446
1.45M
      
Tok.isNot(tok::identifier)1.18M
&&
1447
1.45M
      
!Tok.isAnnotation()79.6k
&&
1448
1.45M
      
Tok.getIdentifierInfo()79.6k
&&
1449
1.45M
      Tok.isOneOf(tok::kw___is_abstract,
1450
108
                  tok::kw___is_aggregate,
1451
108
                  tok::kw___is_arithmetic,
1452
108
                  tok::kw___is_array,
1453
108
                  tok::kw___is_assignable,
1454
108
                  tok::kw___is_base_of,
1455
108
                  tok::kw___is_class,
1456
108
                  tok::kw___is_complete_type,
1457
108
                  tok::kw___is_compound,
1458
108
                  tok::kw___is_const,
1459
108
                  tok::kw___is_constructible,
1460
108
                  tok::kw___is_convertible,
1461
108
                  tok::kw___is_convertible_to,
1462
108
                  tok::kw___is_destructible,
1463
108
                  tok::kw___is_empty,
1464
108
                  tok::kw___is_enum,
1465
108
                  tok::kw___is_floating_point,
1466
108
                  tok::kw___is_final,
1467
108
                  tok::kw___is_function,
1468
108
                  tok::kw___is_fundamental,
1469
108
                  tok::kw___is_integral,
1470
108
                  tok::kw___is_interface_class,
1471
108
                  tok::kw___is_literal,
1472
108
                  tok::kw___is_lvalue_expr,
1473
108
                  tok::kw___is_lvalue_reference,
1474
108
                  tok::kw___is_member_function_pointer,
1475
108
                  tok::kw___is_member_object_pointer,
1476
108
                  tok::kw___is_member_pointer,
1477
108
                  tok::kw___is_nothrow_assignable,
1478
108
                  tok::kw___is_nothrow_constructible,
1479
108
                  tok::kw___is_nothrow_destructible,
1480
108
                  tok::kw___is_object,
1481
108
                  tok::kw___is_pod,
1482
108
                  tok::kw___is_pointer,
1483
108
                  tok::kw___is_polymorphic,
1484
108
                  tok::kw___is_reference,
1485
108
                  tok::kw___is_rvalue_expr,
1486
108
                  tok::kw___is_rvalue_reference,
1487
108
                  tok::kw___is_same,
1488
108
                  tok::kw___is_scalar,
1489
108
                  tok::kw___is_sealed,
1490
108
                  tok::kw___is_signed,
1491
108
                  tok::kw___is_standard_layout,
1492
108
                  tok::kw___is_trivial,
1493
108
                  tok::kw___is_trivially_assignable,
1494
108
                  tok::kw___is_trivially_constructible,
1495
108
                  tok::kw___is_trivially_copyable,
1496
108
                  tok::kw___is_union,
1497
108
                  tok::kw___is_unsigned,
1498
108
                  tok::kw___is_void,
1499
108
                  tok::kw___is_volatile))
1500
106
    // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1501
106
    // name of struct templates, but some are keywords in GCC >= 4.3
1502
106
    // and Clang. Therefore, when we see the token sequence "struct
1503
106
    // X", make X into a normal identifier rather than a keyword, to
1504
106
    // allow libstdc++ 4.2 and libc++ to work properly.
1505
106
    TryKeywordIdentFallback(true);
1506
1.45M
1507
1.45M
  struct PreserveAtomicIdentifierInfoRAII {
1508
1.45M
    PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1509
1.45M
        : AtomicII(nullptr) {
1510
1.45M
      if (!Enabled)
1511
1.45M
        return;
1512
2
      assert(Tok.is(tok::kw__Atomic));
1513
2
      AtomicII = Tok.getIdentifierInfo();
1514
2
      AtomicII->revertTokenIDToIdentifier();
1515
2
      Tok.setKind(tok::identifier);
1516
2
    }
1517
1.45M
    ~PreserveAtomicIdentifierInfoRAII() {
1518
1.45M
      if (!AtomicII)
1519
1.45M
        return;
1520
2
      AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1521
2
    }
1522
1.45M
    IdentifierInfo *AtomicII;
1523
1.45M
  };
1524
1.45M
1525
1.45M
  // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1526
1.45M
  // implementation for VS2013 uses _Atomic as an identifier for one of the
1527
1.45M
  // classes in <atomic>.  When we are parsing 'struct _Atomic', don't consider
1528
1.45M
  // '_Atomic' to be a keyword.  We are careful to undo this so that clang can
1529
1.45M
  // use '_Atomic' in its own header files.
1530
1.45M
  bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1531
1.45M
                                        
Tok.is(tok::kw__Atomic)3.16k
&&
1532
1.45M
                                        
TagType == DeclSpec::TST_struct2
;
1533
1.45M
  PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1534
1.45M
      Tok, ShouldChangeAtomicToIdentifier);
1535
1.45M
1536
1.45M
  // Parse the (optional) nested-name-specifier.
1537
1.45M
  CXXScopeSpec &SS = DS.getTypeSpecScope();
1538
1.45M
  if (getLangOpts().CPlusPlus) {
1539
1.12M
    // "FOO : BAR" is not a potential typo for "FOO::BAR".  In this context it
1540
1.12M
    // is a base-specifier-list.
1541
1.12M
    ColonProtectionRAIIObject X(*this);
1542
1.12M
1543
1.12M
    CXXScopeSpec Spec;
1544
1.12M
    bool HasValidSpec = true;
1545
1.12M
    if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
1546
16
      DS.SetTypeSpecError();
1547
16
      HasValidSpec = false;
1548
16
    }
1549
1.12M
    if (Spec.isSet())
1550
2.69k
      if (Tok.isNot(tok::identifier) && 
Tok.isNot(tok::annot_template_id)403
) {
1551
17
        Diag(Tok, diag::err_expected) << tok::identifier;
1552
17
        HasValidSpec = false;
1553
17
      }
1554
1.12M
    if (HasValidSpec)
1555
1.12M
      SS = Spec;
1556
1.12M
  }
1557
1.45M
1558
1.45M
  TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1559
1.45M
1560
1.45M
  auto RecoverFromUndeclaredTemplateName = [&](IdentifierInfo *Name,
1561
1.45M
                                               SourceLocation NameLoc,
1562
1.45M
                                               SourceRange TemplateArgRange,
1563
1.45M
                                               bool KnownUndeclared) {
1564
21
    Diag(NameLoc, diag::err_explicit_spec_non_template)
1565
21
        << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1566
21
        << TagTokKind << Name << TemplateArgRange << KnownUndeclared;
1567
21
1568
21
    // Strip off the last template parameter list if it was empty, since
1569
21
    // we've removed its template argument list.
1570
21
    if (TemplateParams && 
TemplateInfo.LastParameterListWasEmpty13
) {
1571
12
      if (TemplateParams->size() > 1) {
1572
0
        TemplateParams->pop_back();
1573
12
      } else {
1574
12
        TemplateParams = nullptr;
1575
12
        const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
1576
12
            ParsedTemplateInfo::NonTemplate;
1577
12
      }
1578
12
    } else 
if (9
TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation9
) {
1579
6
      // Pretend this is just a forward declaration.
1580
6
      TemplateParams = nullptr;
1581
6
      const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
1582
6
          ParsedTemplateInfo::NonTemplate;
1583
6
      const_cast<ParsedTemplateInfo &>(TemplateInfo).TemplateLoc =
1584
6
          SourceLocation();
1585
6
      const_cast<ParsedTemplateInfo &>(TemplateInfo).ExternLoc =
1586
6
          SourceLocation();
1587
6
    }
1588
21
  };
1589
1.45M
1590
1.45M
  // Parse the (optional) class name or simple-template-id.
1591
1.45M
  IdentifierInfo *Name = nullptr;
1592
1.45M
  SourceLocation NameLoc;
1593
1.45M
  TemplateIdAnnotation *TemplateId = nullptr;
1594
1.45M
  if (Tok.is(tok::identifier)) {
1595
1.08M
    Name = Tok.getIdentifierInfo();
1596
1.08M
    NameLoc = ConsumeToken();
1597
1.08M
1598
1.08M
    if (Tok.is(tok::less) && 
getLangOpts().CPlusPlus10
) {
1599
9
      // The name was supposed to refer to a template, but didn't.
1600
9
      // Eat the template argument list and try to continue parsing this as
1601
9
      // a class (or template thereof).
1602
9
      TemplateArgList TemplateArgs;
1603
9
      SourceLocation LAngleLoc, RAngleLoc;
1604
9
      if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1605
9
                                           RAngleLoc)) {
1606
0
        // We couldn't parse the template argument list at all, so don't
1607
0
        // try to give any location information for the list.
1608
0
        LAngleLoc = RAngleLoc = SourceLocation();
1609
0
      }
1610
9
      RecoverFromUndeclaredTemplateName(
1611
9
          Name, NameLoc, SourceRange(LAngleLoc, RAngleLoc), false);
1612
9
    }
1613
1.08M
  } else 
if (373k
Tok.is(tok::annot_template_id)373k
) {
1614
260k
    TemplateId = takeTemplateIdAnnotation(Tok);
1615
260k
    NameLoc = ConsumeAnnotationToken();
1616
260k
1617
260k
    if (TemplateId->Kind == TNK_Undeclared_template) {
1618
15
      // Try to resolve the template name to a type template.
1619
15
      Actions.ActOnUndeclaredTypeTemplateName(getCurScope(), TemplateId->Template,
1620
15
                                              TemplateId->Kind, NameLoc, Name);
1621
15
      if (TemplateId->Kind == TNK_Undeclared_template) {
1622
12
        RecoverFromUndeclaredTemplateName(
1623
12
            Name, NameLoc,
1624
12
            SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc), true);
1625
12
        TemplateId = nullptr;
1626
12
      }
1627
15
    }
1628
260k
1629
260k
    if (TemplateId && 
TemplateId->Kind != TNK_Type_template260k
&&
1630
260k
        
TemplateId->Kind != TNK_Dependent_template_name15
) {
1631
10
      // The template-name in the simple-template-id refers to
1632
10
      // something other than a class template. Give an appropriate
1633
10
      // error message and skip to the ';'.
1634
10
      SourceRange Range(NameLoc);
1635
10
      if (SS.isNotEmpty())
1636
5
        Range.setBegin(SS.getBeginLoc());
1637
10
1638
10
      // FIXME: Name may be null here.
1639
10
      Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1640
10
          << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
1641
10
1642
10
      DS.SetTypeSpecError();
1643
10
      SkipUntil(tok::semi, StopBeforeMatch);
1644
10
      return;
1645
10
    }
1646
1.45M
  }
1647
1.45M
1648
1.45M
  // There are four options here.
1649
1.45M
  //  - If we are in a trailing return type, this is always just a reference,
1650
1.45M
  //    and we must not try to parse a definition. For instance,
1651
1.45M
  //      [] () -> struct S { };
1652
1.45M
  //    does not define a type.
1653
1.45M
  //  - If we have 'struct foo {...', 'struct foo :...',
1654
1.45M
  //    'struct foo final :' or 'struct foo final {', then this is a definition.
1655
1.45M
  //  - If we have 'struct foo;', then this is either a forward declaration
1656
1.45M
  //    or a friend declaration, which have to be treated differently.
1657
1.45M
  //  - Otherwise we have something like 'struct foo xyz', a reference.
1658
1.45M
  //
1659
1.45M
  //  We also detect these erroneous cases to provide better diagnostic for
1660
1.45M
  //  C++11 attributes parsing.
1661
1.45M
  //  - attributes follow class name:
1662
1.45M
  //    struct foo [[]] {};
1663
1.45M
  //  - attributes appear before or after 'final':
1664
1.45M
  //    struct foo [[]] final [[]] {};
1665
1.45M
  //
1666
1.45M
  // However, in type-specifier-seq's, things look like declarations but are
1667
1.45M
  // just references, e.g.
1668
1.45M
  //   new struct s;
1669
1.45M
  // or
1670
1.45M
  //   &T::operator struct s;
1671
1.45M
  // For these, DSC is DeclSpecContext::DSC_type_specifier or
1672
1.45M
  // DeclSpecContext::DSC_alias_declaration.
1673
1.45M
1674
1.45M
  // If there are attributes after class name, parse them.
1675
1.45M
  MaybeParseCXX11Attributes(Attributes);
1676
1.45M
1677
1.45M
  const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1678
1.45M
  Sema::TagUseKind TUK;
1679
1.45M
  if (DSC == DeclSpecContext::DSC_trailing)
1680
4
    TUK = Sema::TUK_Reference;
1681
1.45M
  else if (Tok.is(tok::l_brace) ||
1682
1.45M
           
(696k
getLangOpts().CPlusPlus696k
&&
Tok.is(tok::colon)541k
) ||
1683
1.45M
           
(438k
isCXX11FinalKeyword()438k
&&
1684
1.01M
            
(709
NextToken().is(tok::l_brace)709
||
NextToken().is(tok::colon)59
))) {
1685
1.01M
    if (DS.isFriendSpecified()) {
1686
4
      // C++ [class.friend]p2:
1687
4
      //   A class shall not be defined in a friend declaration.
1688
4
      Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1689
4
        << SourceRange(DS.getFriendSpecLoc());
1690
4
1691
4
      // Skip everything up to the semicolon, so that this looks like a proper
1692
4
      // friend class (or template thereof) declaration.
1693
4
      SkipUntil(tok::semi, StopBeforeMatch);
1694
4
      TUK = Sema::TUK_Friend;
1695
1.01M
    } else {
1696
1.01M
      // Okay, this is a class definition.
1697
1.01M
      TUK = Sema::TUK_Definition;
1698
1.01M
    }
1699
1.01M
  } else 
if (438k
isCXX11FinalKeyword()438k
&&
(16
NextToken().is(tok::l_square)16
||
1700
16
                                       
NextToken().is(tok::kw_alignas)9
)) {
1701
12
    // We can't tell if this is a definition or reference
1702
12
    // until we skipped the 'final' and C++11 attribute specifiers.
1703
12
    TentativeParsingAction PA(*this);
1704
12
1705
12
    // Skip the 'final' keyword.
1706
12
    ConsumeToken();
1707
12
1708
12
    // Skip C++11 attribute specifiers.
1709
47
    while (true) {
1710
47
      if (Tok.is(tok::l_square) && 
NextToken().is(tok::l_square)23
) {
1711
22
        ConsumeBracket();
1712
22
        if (!SkipUntil(tok::r_square, StopAtSemi))
1713
0
          break;
1714
25
      } else if (Tok.is(tok::kw_alignas) && 
NextToken().is(tok::l_paren)13
) {
1715
13
        ConsumeToken();
1716
13
        ConsumeParen();
1717
13
        if (!SkipUntil(tok::r_paren, StopAtSemi))
1718
0
          break;
1719
12
      } else {
1720
12
        break;
1721
12
      }
1722
47
    }
1723
12
1724
12
    if (Tok.isOneOf(tok::l_brace, tok::colon))
1725
10
      TUK = Sema::TUK_Definition;
1726
2
    else
1727
2
      TUK = Sema::TUK_Reference;
1728
12
1729
12
    PA.Revert();
1730
438k
  } else if (!isTypeSpecifier(DSC) &&
1731
438k
             
(437k
Tok.is(tok::semi)437k
||
1732
437k
              
(322k
Tok.isAtStartOfLine()322k
&&
!isValidAfterTypeSpecifier(false)231
))) {
1733
114k
    TUK = DS.isFriendSpecified() ? 
Sema::TUK_Friend23.6k
:
Sema::TUK_Declaration91.1k
;
1734
114k
    if (Tok.isNot(tok::semi)) {
1735
14
      const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1736
14
      // A semicolon was missing after this declaration. Diagnose and recover.
1737
14
      ExpectAndConsume(tok::semi, diag::err_expected_after,
1738
14
                       DeclSpec::getSpecifierName(TagType, PPol));
1739
14
      PP.EnterToken(Tok, /*IsReinject*/true);
1740
14
      Tok.setKind(tok::semi);
1741
14
    }
1742
114k
  } else
1743
323k
    TUK = Sema::TUK_Reference;
1744
1.45M
1745
1.45M
  // Forbid misplaced attributes. In cases of a reference, we pass attributes
1746
1.45M
  // to caller to handle.
1747
1.45M
  if (TUK != Sema::TUK_Reference) {
1748
1.13M
    // If this is not a reference, then the only possible
1749
1.13M
    // valid place for C++11 attributes to appear here
1750
1.13M
    // is between class-key and class-name. If there are
1751
1.13M
    // any attributes after class-name, we try a fixit to move
1752
1.13M
    // them to the right place.
1753
1.13M
    SourceRange AttrRange = Attributes.Range;
1754
1.13M
    if (AttrRange.isValid()) {
1755
20
      Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1756
20
        << AttrRange
1757
20
        << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1758
20
                                               CharSourceRange(AttrRange, true))
1759
20
        << FixItHint::CreateRemoval(AttrRange);
1760
20
1761
20
      // Recover by adding misplaced attributes to the attribute list
1762
20
      // of the class so they can be applied on the class later.
1763
20
      attrs.takeAllFrom(Attributes);
1764
20
    }
1765
1.13M
  }
1766
1.45M
1767
1.45M
  // If this is an elaborated type specifier, and we delayed
1768
1.45M
  // diagnostics before, just merge them into the current pool.
1769
1.45M
  if (shouldDelayDiagsInTag) {
1770
79.9k
    diagsFromTag.done();
1771
79.9k
    if (TUK == Sema::TUK_Reference)
1772
4
      diagsFromTag.redelay();
1773
79.9k
  }
1774
1.45M
1775
1.45M
  if (!Name && 
!TemplateId373k
&&
(113k
DS.getTypeSpecType() == DeclSpec::TST_error113k
||
1776
113k
                               
TUK != Sema::TUK_Definition113k
)) {
1777
41
    if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1778
23
      // We have a declaration or reference to an anonymous class.
1779
23
      Diag(StartLoc, diag::err_anon_type_definition)
1780
23
        << DeclSpec::getSpecifierName(TagType, Policy);
1781
23
    }
1782
41
1783
41
    // If we are parsing a definition and stop at a base-clause, continue on
1784
41
    // until the semicolon.  Continuing from the comma will just trick us into
1785
41
    // thinking we are seeing a variable declaration.
1786
41
    if (TUK == Sema::TUK_Definition && 
Tok.is(tok::colon)10
)
1787
2
      SkipUntil(tok::semi, StopBeforeMatch);
1788
39
    else
1789
39
      SkipUntil(tok::comma, StopAtSemi);
1790
41
    return;
1791
41
  }
1792
1.45M
1793
1.45M
  // Create the tag portion of the class or class template.
1794
1.45M
  DeclResult TagOrTempResult = true; // invalid
1795
1.45M
  TypeResult TypeResult = true; // invalid
1796
1.45M
1797
1.45M
  bool Owned = false;
1798
1.45M
  Sema::SkipBodyInfo SkipBody;
1799
1.45M
  if (TemplateId) {
1800
260k
    // Explicit specialization, class template partial specialization,
1801
260k
    // or explicit instantiation.
1802
260k
    ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1803
260k
                                       TemplateId->NumArgs);
1804
260k
    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1805
260k
        
TUK == Sema::TUK_Declaration13.6k
) {
1806
13.6k
      // This is an explicit instantiation of a class template.
1807
13.6k
      ProhibitAttributes(attrs);
1808
13.6k
1809
13.6k
      TagOrTempResult = Actions.ActOnExplicitInstantiation(
1810
13.6k
          getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1811
13.6k
          TagType, StartLoc, SS, TemplateId->Template,
1812
13.6k
          TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
1813
13.6k
          TemplateId->RAngleLoc, attrs);
1814
13.6k
1815
13.6k
      // Friend template-ids are treated as references unless
1816
13.6k
      // they have template headers, in which case they're ill-formed
1817
13.6k
      // (FIXME: "template <class T> friend class A<T>::B<int>;").
1818
13.6k
      // We diagnose this error in ActOnClassTemplateSpecialization.
1819
246k
    } else if (TUK == Sema::TUK_Reference ||
1820
246k
               
(246k
TUK == Sema::TUK_Friend246k
&&
1821
246k
                
TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate6.40k
)) {
1822
6.45k
      ProhibitAttributes(attrs);
1823
6.45k
      TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1824
6.45k
                                                  TemplateId->SS,
1825
6.45k
                                                  TemplateId->TemplateKWLoc,
1826
6.45k
                                                  TemplateId->Template,
1827
6.45k
                                                  TemplateId->TemplateNameLoc,
1828
6.45k
                                                  TemplateId->LAngleLoc,
1829
6.45k
                                                  TemplateArgsPtr,
1830
6.45k
                                                  TemplateId->RAngleLoc);
1831
239k
    } else {
1832
239k
      // This is an explicit specialization or a class template
1833
239k
      // partial specialization.
1834
239k
      TemplateParameterLists FakedParamLists;
1835
239k
      if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1836
10
        // This looks like an explicit instantiation, because we have
1837
10
        // something like
1838
10
        //
1839
10
        //   template class Foo<X>
1840
10
        //
1841
10
        // but it actually has a definition. Most likely, this was
1842
10
        // meant to be an explicit specialization, but the user forgot
1843
10
        // the '<>' after 'template'.
1844
10
        // It this is friend declaration however, since it cannot have a
1845
10
        // template header, it is most likely that the user meant to
1846
10
        // remove the 'template' keyword.
1847
10
        assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1848
10
               "Expected a definition here");
1849
10
1850
10
        if (TUK == Sema::TUK_Friend) {
1851
0
          Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1852
0
          TemplateParams = nullptr;
1853
10
        } else {
1854
10
          SourceLocation LAngleLoc =
1855
10
              PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1856
10
          Diag(TemplateId->TemplateNameLoc,
1857
10
               diag::err_explicit_instantiation_with_definition)
1858
10
              << SourceRange(TemplateInfo.TemplateLoc)
1859
10
              << FixItHint::CreateInsertion(LAngleLoc, "<>");
1860
10
1861
10
          // Create a fake template parameter list that contains only
1862
10
          // "template<>", so that we treat this construct as a class
1863
10
          // template specialization.
1864
10
          FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1865
10
              0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
1866
10
              LAngleLoc, nullptr));
1867
10
          TemplateParams = &FakedParamLists;
1868
10
        }
1869
10
      }
1870
239k
1871
239k
      // Build the class template specialization.
1872
239k
      TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1873
239k
          getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1874
239k
          *TemplateId, attrs,
1875
239k
          MultiTemplateParamsArg(TemplateParams ? 
&(*TemplateParams)[0]239k
1876
239k
                                                : 
nullptr14
,
1877
239k
                                 TemplateParams ? 
TemplateParams->size()239k
:
014
),
1878
239k
          &SkipBody);
1879
239k
    }
1880
1.19M
  } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1881
1.19M
             
TUK == Sema::TUK_Declaration45
) {
1882
41
    // Explicit instantiation of a member of a class template
1883
41
    // specialization, e.g.,
1884
41
    //
1885
41
    //   template struct Outer<int>::Inner;
1886
41
    //
1887
41
    ProhibitAttributes(attrs);
1888
41
1889
41
    TagOrTempResult = Actions.ActOnExplicitInstantiation(
1890
41
        getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1891
41
        TagType, StartLoc, SS, Name, NameLoc, attrs);
1892
1.19M
  } else if (TUK == Sema::TUK_Friend &&
1893
1.19M
             
TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate17.2k
) {
1894
9.63k
    ProhibitAttributes(attrs);
1895
9.63k
1896
9.63k
    TagOrTempResult = Actions.ActOnTemplatedFriendTag(
1897
9.63k
        getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
1898
9.63k
        NameLoc, attrs,
1899
9.63k
        MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : 
nullptr0
,
1900
9.63k
                               TemplateParams ? TemplateParams->size() : 
00
));
1901
1.18M
  } else {
1902
1.18M
    if (TUK != Sema::TUK_Declaration && 
TUK != Sema::TUK_Definition1.11M
)
1903
330k
      ProhibitAttributes(attrs);
1904
1.18M
1905
1.18M
    if (TUK == Sema::TUK_Definition &&
1906
1.18M
        
TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation780k
) {
1907
4
      // If the declarator-id is not a template-id, issue a diagnostic and
1908
4
      // recover by ignoring the 'template' keyword.
1909
4
      Diag(Tok, diag::err_template_defn_explicit_instantiation)
1910
4
        << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1911
4
      TemplateParams = nullptr;
1912
4
    }
1913
1.18M
1914
1.18M
    bool IsDependent = false;
1915
1.18M
1916
1.18M
    // Don't pass down template parameter lists if this is just a tag
1917
1.18M
    // reference.  For example, we don't need the template parameters here:
1918
1.18M
    //   template <class T> class A *makeA(T t);
1919
1.18M
    MultiTemplateParamsArg TParams;
1920
1.18M
    if (TUK != Sema::TUK_Reference && 
TemplateParams863k
)
1921
287k
      TParams =
1922
287k
        MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1923
1.18M
1924
1.18M
    stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
1925
1.18M
1926
1.18M
    // Declaration or definition of a class type
1927
1.18M
    TagOrTempResult = Actions.ActOnTag(
1928
1.18M
        getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
1929
1.18M
        DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
1930
1.18M
        SourceLocation(), false, clang::TypeResult(),
1931
1.18M
        DSC == DeclSpecContext::DSC_type_specifier,
1932
1.18M
        DSC == DeclSpecContext::DSC_template_param ||
1933
1.18M
            
DSC == DeclSpecContext::DSC_template_type_arg1.18M
,
1934
1.18M
        &SkipBody);
1935
1.18M
1936
1.18M
    // If ActOnTag said the type was dependent, try again with the
1937
1.18M
    // less common call.
1938
1.18M
    if (IsDependent) {
1939
30
      assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1940
30
      TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1941
30
                                             SS, Name, StartLoc, NameLoc);
1942
30
    }
1943
1.18M
  }
1944
1.45M
1945
1.45M
  // If there is a body, parse it and inform the actions module.
1946
1.45M
  if (TUK == Sema::TUK_Definition) {
1947
1.01M
    assert(Tok.is(tok::l_brace) ||
1948
1.01M
           (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1949
1.01M
           isCXX11FinalKeyword());
1950
1.01M
    if (SkipBody.ShouldSkip)
1951
253
      SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1952
253
                                 TagOrTempResult.get());
1953
1.01M
    else if (getLangOpts().CPlusPlus)
1954
844k
      ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1955
844k
                                  TagOrTempResult.get());
1956
173k
    else {
1957
173k
      Decl *D =
1958
173k
          SkipBody.CheckSameAsPrevious ? 
SkipBody.New8
:
TagOrTempResult.get()173k
;
1959
173k
      // Parse the definition body.
1960
173k
      ParseStructUnionBody(StartLoc, TagType, D);
1961
173k
      if (SkipBody.CheckSameAsPrevious &&
1962
173k
          !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1963
8
                                            SkipBody)) {
1964
2
        DS.SetTypeSpecError();
1965
2
        return;
1966
2
      }
1967
1.45M
    }
1968
1.01M
  }
1969
1.45M
1970
1.45M
  if (!TagOrTempResult.isInvalid())
1971
1.44M
    // Delayed processing of attributes.
1972
1.44M
    Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
1973
1.45M
1974
1.45M
  const char *PrevSpec = nullptr;
1975
1.45M
  unsigned DiagID;
1976
1.45M
  bool Result;
1977
1.45M
  if (!TypeResult.isInvalid()) {
1978
6.47k
    Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1979
6.47k
                                NameLoc.isValid() ? NameLoc : 
StartLoc0
,
1980
6.47k
                                PrevSpec, DiagID, TypeResult.get(), Policy);
1981
1.44M
  } else if (!TagOrTempResult.isInvalid()) {
1982
1.44M
    Result = DS.SetTypeSpecType(TagType, StartLoc,
1983
1.44M
                                NameLoc.isValid() ? 
NameLoc1.33M
:
StartLoc113k
,
1984
1.44M
                                PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1985
1.44M
                                Policy);
1986
1.44M
  } else {
1987
111
    DS.SetTypeSpecError();
1988
111
    return;
1989
111
  }
1990
1.45M
1991
1.45M
  if (Result)
1992
3
    Diag(StartLoc, DiagID) << PrevSpec;
1993
1.45M
1994
1.45M
  // At this point, we've successfully parsed a class-specifier in 'definition'
1995
1.45M
  // form (e.g. "struct foo { int x; }".  While we could just return here, we're
1996
1.45M
  // going to look at what comes after it to improve error recovery.  If an
1997
1.45M
  // impossible token occurs next, we assume that the programmer forgot a ; at
1998
1.45M
  // the end of the declaration and recover that way.
1999
1.45M
  //
2000
1.45M
  // Also enforce C++ [temp]p3:
2001
1.45M
  //   In a template-declaration which defines a class, no declarator
2002
1.45M
  //   is permitted.
2003
1.45M
  //
2004
1.45M
  // After a type-specifier, we don't expect a semicolon. This only happens in
2005
1.45M
  // C, since definitions are not permitted in this context in C++.
2006
1.45M
  if (TUK == Sema::TUK_Definition &&
2007
1.45M
      
(1.01M
getLangOpts().CPlusPlus1.01M
||
!isTypeSpecifier(DSC)173k
) &&
2008
1.45M
      
(1.01M
TemplateInfo.Kind1.01M
||
!isValidAfterTypeSpecifier(false)533k
)) {
2009
484k
    if (Tok.isNot(tok::semi)) {
2010
154
      const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2011
154
      ExpectAndConsume(tok::semi, diag::err_expected_after,
2012
154
                       DeclSpec::getSpecifierName(TagType, PPol));
2013
154
      // Push this token back into the preprocessor and change our current token
2014
154
      // to ';' so that the rest of the code recovers as though there were an
2015
154
      // ';' after the definition.
2016
154
      PP.EnterToken(Tok, /*IsReinject=*/true);
2017
154
      Tok.setKind(tok::semi);
2018
154
    }
2019
484k
  }
2020
1.45M
}
2021
2022
/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
2023
///
2024
///       base-clause : [C++ class.derived]
2025
///         ':' base-specifier-list
2026
///       base-specifier-list:
2027
///         base-specifier '...'[opt]
2028
///         base-specifier-list ',' base-specifier '...'[opt]
2029
257k
void Parser::ParseBaseClause(Decl *ClassDecl) {
2030
257k
  assert(Tok.is(tok::colon) && "Not a base clause");
2031
257k
  ConsumeToken();
2032
257k
2033
257k
  // Build up an array of parsed base specifiers.
2034
257k
  SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
2035
257k
2036
266k
  while (true) {
2037
266k
    // Parse a base-specifier.
2038
266k
    BaseResult Result = ParseBaseSpecifier(ClassDecl);
2039
266k
    if (Result.isInvalid()) {
2040
488
      // Skip the rest of this base specifier, up until the comma or
2041
488
      // opening brace.
2042
488
      SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
2043
265k
    } else {
2044
265k
      // Add this to our array of base specifiers.
2045
265k
      BaseInfo.push_back(Result.get());
2046
265k
    }
2047
266k
2048
266k
    // If the next token is a comma, consume it and keep reading
2049
266k
    // base-specifiers.
2050
266k
    if (!TryConsumeToken(tok::comma))
2051
257k
      break;
2052
266k
  }
2053
257k
2054
257k
  // Attach the base specifiers
2055
257k
  Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
2056
257k
}
2057
2058
/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2059
/// one entry in the base class list of a class specifier, for example:
2060
///    class foo : public bar, virtual private baz {
2061
/// 'public bar' and 'virtual private baz' are each base-specifiers.
2062
///
2063
///       base-specifier: [C++ class.derived]
2064
///         attribute-specifier-seq[opt] base-type-specifier
2065
///         attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2066
///                 base-type-specifier
2067
///         attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2068
///                 base-type-specifier
2069
266k
BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
2070
266k
  bool IsVirtual = false;
2071
266k
  SourceLocation StartLoc = Tok.getLocation();
2072
266k
2073
266k
  ParsedAttributesWithRange Attributes(AttrFactory);
2074
266k
  MaybeParseCXX11Attributes(Attributes);
2075
266k
2076
266k
  // Parse the 'virtual' keyword.
2077
266k
  if (TryConsumeToken(tok::kw_virtual))
2078
2.21k
    IsVirtual = true;
2079
266k
2080
266k
  CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2081
266k
2082
266k
  // Parse an (optional) access specifier.
2083
266k
  AccessSpecifier Access = getAccessSpecifierIfPresent();
2084
266k
  if (Access != AS_none)
2085
216k
    ConsumeToken();
2086
266k
2087
266k
  CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2088
266k
2089
266k
  // Parse the 'virtual' keyword (again!), in case it came after the
2090
266k
  // access specifier.
2091
266k
  if (Tok.is(tok::kw_virtual))  {
2092
260
    SourceLocation VirtualLoc = ConsumeToken();
2093
260
    if (IsVirtual) {
2094
6
      // Complain about duplicate 'virtual'
2095
6
      Diag(VirtualLoc, diag::err_dup_virtual)
2096
6
        << FixItHint::CreateRemoval(VirtualLoc);
2097
6
    }
2098
260
2099
260
    IsVirtual = true;
2100
260
  }
2101
266k
2102
266k
  CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2103
266k
2104
266k
  // Parse the class-name.
2105
266k
2106
266k
  // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2107
266k
  // implementation for VS2013 uses _Atomic as an identifier for one of the
2108
266k
  // classes in <atomic>.  Treat '_Atomic' to be an identifier when we are
2109
266k
  // parsing the class-name for a base specifier.
2110
266k
  if (getLangOpts().MSVCCompat && 
Tok.is(tok::kw__Atomic)168
&&
2111
266k
      
NextToken().is(tok::less)2
)
2112
2
    Tok.setKind(tok::identifier);
2113
266k
2114
266k
  SourceLocation EndLocation;
2115
266k
  SourceLocation BaseLoc;
2116
266k
  TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
2117
266k
  if (BaseType.isInvalid())
2118
253
    return true;
2119
266k
2120
266k
  // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2121
266k
  // actually part of the base-specifier-list grammar productions, but we
2122
266k
  // parse it here for convenience.
2123
266k
  SourceLocation EllipsisLoc;
2124
266k
  TryConsumeToken(tok::ellipsis, EllipsisLoc);
2125
266k
2126
266k
  // Find the complete source range for the base-specifier.
2127
266k
  SourceRange Range(StartLoc, EndLocation);
2128
266k
2129
266k
  // Notify semantic analysis that we have parsed a complete
2130
266k
  // base-specifier.
2131
266k
  return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2132
266k
                                    Access, BaseType.get(), BaseLoc,
2133
266k
                                    EllipsisLoc);
2134
266k
}
2135
2136
/// getAccessSpecifierIfPresent - Determine whether the next token is
2137
/// a C++ access-specifier.
2138
///
2139
///       access-specifier: [C++ class.derived]
2140
///         'private'
2141
///         'protected'
2142
///         'public'
2143
532k
AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
2144
532k
  switch (Tok.getKind()) {
2145
532k
  
default: return AS_none50.0k
;
2146
532k
  
case tok::kw_private: return AS_private101k
;
2147
532k
  
case tok::kw_protected: return AS_protected23.5k
;
2148
532k
  
case tok::kw_public: return AS_public357k
;
2149
532k
  }
2150
532k
}
2151
2152
/// If the given declarator has any parts for which parsing has to be
2153
/// delayed, e.g., default arguments or an exception-specification, create a
2154
/// late-parsed method declaration record to handle the parsing at the end of
2155
/// the class definition.
2156
void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2157
1.66M
                                            Decl *ThisDecl) {
2158
1.66M
  DeclaratorChunk::FunctionTypeInfo &FTI
2159
1.66M
    = DeclaratorInfo.getFunctionTypeInfo();
2160
1.66M
  // If there was a late-parsed exception-specification, we'll need a
2161
1.66M
  // late parse
2162
1.66M
  bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
2163
1.66M
2164
1.66M
  if (!NeedLateParse) {
2165
1.62M
    // Look ahead to see if there are any default args
2166
3.21M
    for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; 
++ParamIdx1.59M
) {
2167
1.67M
      auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2168
1.67M
      if (Param->hasUnparsedDefaultArg()) {
2169
79.6k
        NeedLateParse = true;
2170
79.6k
        break;
2171
79.6k
      }
2172
1.67M
    }
2173
1.62M
  }
2174
1.66M
2175
1.66M
  if (NeedLateParse) {
2176
127k
    // Push this method onto the stack of late-parsed method
2177
127k
    // declarations.
2178
127k
    auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
2179
127k
    getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2180
127k
    LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2181
127k
2182
127k
    // Stash the exception-specification tokens in the late-pased method.
2183
127k
    LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
2184
127k
    FTI.ExceptionSpecTokens = nullptr;
2185
127k
2186
127k
    // Push tokens for each parameter.  Those that do not have
2187
127k
    // defaults will be NULL.
2188
127k
    LateMethod->DefaultArgs.reserve(FTI.NumParams);
2189
346k
    for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; 
++ParamIdx218k
)
2190
218k
      LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
2191
218k
          FTI.Params[ParamIdx].Param,
2192
218k
          std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
2193
127k
  }
2194
1.66M
}
2195
2196
/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
2197
/// virt-specifier.
2198
///
2199
///       virt-specifier:
2200
///         override
2201
///         final
2202
///         __final
2203
8.53M
VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
2204
8.53M
  if (!getLangOpts().CPlusPlus || 
Tok.isNot(tok::identifier)8.22M
)
2205
8.31M
    return VirtSpecifiers::VS_None;
2206
215k
2207
215k
  IdentifierInfo *II = Tok.getIdentifierInfo();
2208
215k
2209
215k
  // Initialize the contextual keywords.
2210
215k
  if (!Ident_final) {
2211
2.58k
    Ident_final = &PP.getIdentifierTable().get("final");
2212
2.58k
    if (getLangOpts().GNUKeywords)
2213
899
      Ident_GNU_final = &PP.getIdentifierTable().get("__final");
2214
2.58k
    if (getLangOpts().MicrosoftExt)
2215
44
      Ident_sealed = &PP.getIdentifierTable().get("sealed");
2216
2.58k
    Ident_override = &PP.getIdentifierTable().get("override");
2217
2.58k
  }
2218
215k
2219
215k
  if (II == Ident_override)
2220
3.39k
    return VirtSpecifiers::VS_Override;
2221
212k
2222
212k
  if (II == Ident_sealed)
2223
33
    return VirtSpecifiers::VS_Sealed;
2224
212k
2225
212k
  if (II == Ident_final)
2226
1.79k
    return VirtSpecifiers::VS_Final;
2227
210k
2228
210k
  if (II == Ident_GNU_final)
2229
6
    return VirtSpecifiers::VS_GNU_Final;
2230
210k
2231
210k
  return VirtSpecifiers::VS_None;
2232
210k
}
2233
2234
/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
2235
///
2236
///       virt-specifier-seq:
2237
///         virt-specifier
2238
///         virt-specifier-seq virt-specifier
2239
void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
2240
                                                bool IsInterface,
2241
7.51M
                                                SourceLocation FriendLoc) {
2242
7.52M
  while (true) {
2243
7.52M
    VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2244
7.52M
    if (Specifier == VirtSpecifiers::VS_None)
2245
7.51M
      return;
2246
3.78k
2247
3.78k
    if (FriendLoc.isValid()) {
2248
6
      Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2249
6
        << VirtSpecifiers::getSpecifierName(Specifier)
2250
6
        << FixItHint::CreateRemoval(Tok.getLocation())
2251
6
        << SourceRange(FriendLoc, FriendLoc);
2252
6
      ConsumeToken();
2253
6
      continue;
2254
6
    }
2255
3.77k
2256
3.77k
    // C++ [class.mem]p8:
2257
3.77k
    //   A virt-specifier-seq shall contain at most one of each virt-specifier.
2258
3.77k
    const char *PrevSpec = nullptr;
2259
3.77k
    if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
2260
4
      Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2261
4
        << PrevSpec
2262
4
        << FixItHint::CreateRemoval(Tok.getLocation());
2263
3.77k
2264
3.77k
    if (IsInterface && 
(3
Specifier == VirtSpecifiers::VS_Final3
||
2265
3
                        
Specifier == VirtSpecifiers::VS_Sealed2
)) {
2266
1
      Diag(Tok.getLocation(), diag::err_override_control_interface)
2267
1
        << VirtSpecifiers::getSpecifierName(Specifier);
2268
3.77k
    } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2269
3
      Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
2270
3.77k
    } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2271
2
      Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
2272
3.77k
    } else {
2273
3.77k
      Diag(Tok.getLocation(),
2274
3.77k
           getLangOpts().CPlusPlus11
2275
3.77k
               ? 
diag::warn_cxx98_compat_override_control_keyword3.76k
2276
3.77k
               : 
diag::ext_override_control_keyword6
)
2277
3.77k
          << VirtSpecifiers::getSpecifierName(Specifier);
2278
3.77k
    }
2279
3.77k
    ConsumeToken();
2280
3.77k
  }
2281
7.51M
}
2282
2283
/// isCXX11FinalKeyword - Determine whether the next token is a C++11
2284
/// 'final' or Microsoft 'sealed' contextual keyword.
2285
876k
bool Parser::isCXX11FinalKeyword() const {
2286
876k
  VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2287
876k
  return Specifier == VirtSpecifiers::VS_Final ||
2288
876k
         
Specifier == VirtSpecifiers::VS_GNU_Final876k
||
2289
876k
         
Specifier == VirtSpecifiers::VS_Sealed876k
;
2290
876k
}
2291
2292
/// Parse a C++ member-declarator up to, but not including, the optional
2293
/// brace-or-equal-initializer or pure-specifier.
2294
bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2295
    Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2296
3.78M
    LateParsedAttrList &LateParsedAttrs) {
2297
3.78M
  // member-declarator:
2298
3.78M
  //   declarator pure-specifier[opt]
2299
3.78M
  //   declarator brace-or-equal-initializer[opt]
2300
3.78M
  //   identifier[opt] ':' constant-expression
2301
3.78M
  if (Tok.isNot(tok::colon))
2302
3.77M
    ParseDeclarator(DeclaratorInfo);
2303
884
  else
2304
884
    DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
2305
3.78M
2306
3.78M
  if (!DeclaratorInfo.isFunctionDeclarator() && 
TryConsumeToken(tok::colon)2.09M
) {
2307
18.2k
    assert(DeclaratorInfo.isPastIdentifier() &&
2308
18.2k
           "don't know where identifier would go yet?");
2309
18.2k
    BitfieldSize = ParseConstantExpression();
2310
18.2k
    if (BitfieldSize.isInvalid())
2311
4
      SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2312
3.76M
  } else {
2313
3.76M
    ParseOptionalCXX11VirtSpecifierSeq(
2314
3.76M
        VS, getCurrentClass().IsInterface,
2315
3.76M
        DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2316
3.76M
    if (!VS.isUnset())
2317
3.75k
      MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2318
3.76M
  }
2319
3.78M
2320
3.78M
  // If a simple-asm-expr is present, parse it.
2321
3.78M
  if (Tok.is(tok::kw_asm)) {
2322
5
    SourceLocation Loc;
2323
5
    ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2324
5
    if (AsmLabel.isInvalid())
2325
0
      SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2326
5
2327
5
    DeclaratorInfo.setAsmLabel(AsmLabel.get());
2328
5
    DeclaratorInfo.SetRangeEnd(Loc);
2329
5
  }
2330
3.78M
2331
3.78M
  // If attributes exist after the declarator, but before an '{', parse them.
2332
3.78M
  MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2333
3.78M
2334
3.78M
  // For compatibility with code written to older Clang, also accept a
2335
3.78M
  // virt-specifier *after* the GNU attributes.
2336
3.78M
  if (BitfieldSize.isUnset() && 
VS.isUnset()3.76M
) {
2337
3.75M
    ParseOptionalCXX11VirtSpecifierSeq(
2338
3.75M
        VS, getCurrentClass().IsInterface,
2339
3.75M
        DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2340
3.75M
    if (!VS.isUnset()) {
2341
4
      // If we saw any GNU-style attributes that are known to GCC followed by a
2342
4
      // virt-specifier, issue a GCC-compat warning.
2343
4
      for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
2344
2
        if (AL.isKnownToGCC() && 
!AL.isCXX11Attribute()1
)
2345
1
          Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
2346
4
2347
4
      MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2348
4
    }
2349
3.75M
  }
2350
3.78M
2351
3.78M
  // If this has neither a name nor a bit width, something has gone seriously
2352
3.78M
  // wrong. Skip until the semi-colon or }.
2353
3.78M
  if (!DeclaratorInfo.hasName() && 
BitfieldSize.isUnset()984
) {
2354
100
    // If so, skip until the semi-colon or a }.
2355
100
    SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2356
100
    return true;
2357
100
  }
2358
3.77M
  return false;
2359
3.77M
}
2360
2361
/// Look for declaration specifiers possibly occurring after C++11
2362
/// virt-specifier-seq and diagnose them.
2363
void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2364
    Declarator &D,
2365
3.76k
    VirtSpecifiers &VS) {
2366
3.76k
  DeclSpec DS(AttrFactory);
2367
3.76k
2368
3.76k
  // GNU-style and C++11 attributes are not allowed here, but they will be
2369
3.76k
  // handled by the caller.  Diagnose everything else.
2370
3.76k
  ParseTypeQualifierListOpt(
2371
3.76k
      DS, AR_NoAttributesParsed, false,
2372
3.76k
      /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2373
2
        Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2374
2
      }));
2375
3.76k
  D.ExtendWithDeclSpec(DS);
2376
3.76k
2377
3.76k
  if (D.isFunctionDeclarator()) {
2378
3.75k
    auto &Function = D.getFunctionTypeInfo();
2379
3.75k
    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2380
4
      auto DeclSpecCheck = [&](DeclSpec::TQ TypeQual, StringRef FixItName,
2381
8
                               SourceLocation SpecLoc) {
2382
8
        FixItHint Insertion;
2383
8
        auto &MQ = Function.getOrCreateMethodQualifiers();
2384
8
        if (!(MQ.getTypeQualifiers() & TypeQual)) {
2385
8
          std::string Name(FixItName.data());
2386
8
          Name += " ";
2387
8
          Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2388
8
          MQ.SetTypeQual(TypeQual, SpecLoc);
2389
8
        }
2390
8
        Diag(SpecLoc, diag::err_declspec_after_virtspec)
2391
8
            << FixItName
2392
8
            << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2393
8
            << FixItHint::CreateRemoval(SpecLoc) << Insertion;
2394
8
      };
2395
4
      DS.forEachQualifier(DeclSpecCheck);
2396
4
    }
2397
3.75k
2398
3.75k
    // Parse ref-qualifiers.
2399
3.75k
    bool RefQualifierIsLValueRef = true;
2400
3.75k
    SourceLocation RefQualifierLoc;
2401
3.75k
    if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2402
4
      const char *Name = (RefQualifierIsLValueRef ? 
"& "2
:
"&& "2
);
2403
4
      FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2404
4
      Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2405
4
      Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2406
4
2407
4
      Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2408
4
        << (RefQualifierIsLValueRef ? 
"&"2
:
"&&"2
)
2409
4
        << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2410
4
        << FixItHint::CreateRemoval(RefQualifierLoc)
2411
4
        << Insertion;
2412
4
      D.SetRangeEnd(RefQualifierLoc);
2413
4
    }
2414
3.75k
  }
2415
3.76k
}
2416
2417
/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2418
///
2419
///       member-declaration:
2420
///         decl-specifier-seq[opt] member-declarator-list[opt] ';'
2421
///         function-definition ';'[opt]
2422
///         ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2423
///         using-declaration                                            [TODO]
2424
/// [C++0x] static_assert-declaration
2425
///         template-declaration
2426
/// [GNU]   '__extension__' member-declaration
2427
///
2428
///       member-declarator-list:
2429
///         member-declarator
2430
///         member-declarator-list ',' member-declarator
2431
///
2432
///       member-declarator:
2433
///         declarator virt-specifier-seq[opt] pure-specifier[opt]
2434
///         declarator constant-initializer[opt]
2435
/// [C++11] declarator brace-or-equal-initializer[opt]
2436
///         identifier[opt] ':' constant-expression
2437
///
2438
///       virt-specifier-seq:
2439
///         virt-specifier
2440
///         virt-specifier-seq virt-specifier
2441
///
2442
///       virt-specifier:
2443
///         override
2444
///         final
2445
/// [MS]    sealed
2446
///
2447
///       pure-specifier:
2448
///         '= 0'
2449
///
2450
///       constant-initializer:
2451
///         '=' constant-expression
2452
///
2453
Parser::DeclGroupPtrTy
2454
Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2455
                                       ParsedAttributes &AccessAttrs,
2456
                                       const ParsedTemplateInfo &TemplateInfo,
2457
4.10M
                                       ParsingDeclRAIIObject *TemplateDiags) {
2458
4.10M
  if (Tok.is(tok::at)) {
2459
2
    if (getLangOpts().ObjC && NextToken().isObjCAtKeyword(tok::objc_defs))
2460
1
      Diag(Tok, diag::err_at_defs_cxx);
2461
1
    else
2462
1
      Diag(Tok, diag::err_at_in_class);
2463
2
2464
2
    ConsumeToken();
2465
2
    SkipUntil(tok::r_brace, StopAtSemi);
2466
2
    return nullptr;
2467
2
  }
2468
4.10M
2469
4.10M
  // Turn on colon protection early, while parsing declspec, although there is
2470
4.10M
  // nothing to protect there. It prevents from false errors if error recovery
2471
4.10M
  // incorrectly determines where the declspec ends, as in the example:
2472
4.10M
  //   struct A { enum class B { C }; };
2473
4.10M
  //   const int C = 4;
2474
4.10M
  //   struct D { A::B : C; };
2475
4.10M
  ColonProtectionRAIIObject X(*this);
2476
4.10M
2477
4.10M
  // Access declarations.
2478
4.10M
  bool MalformedTypeSpec = false;
2479
4.10M
  if (!TemplateInfo.Kind &&
2480
4.10M
      
Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)3.89M
) {
2481
1.11M
    if (TryAnnotateCXXScopeToken())
2482
11
      MalformedTypeSpec = true;
2483
1.11M
2484
1.11M
    bool isAccessDecl;
2485
1.11M
    if (Tok.isNot(tok::annot_cxxscope))
2486
1.10M
      isAccessDecl = false;
2487
7.93k
    else if (NextToken().is(tok::identifier))
2488
6.42k
      isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2489
1.50k
    else
2490
1.50k
      isAccessDecl = NextToken().is(tok::kw_operator);
2491
1.11M
2492
1.11M
    if (isAccessDecl) {
2493
105
      // Collect the scope specifier token we annotated earlier.
2494
105
      CXXScopeSpec SS;
2495
105
      ParseOptionalCXXScopeSpecifier(SS, nullptr,
2496
105
                                     /*EnteringContext=*/false);
2497
105
2498
105
      if (SS.isInvalid()) {
2499
7
        SkipUntil(tok::semi);
2500
7
        return nullptr;
2501
7
      }
2502
98
2503
98
      // Try to parse an unqualified-id.
2504
98
      SourceLocation TemplateKWLoc;
2505
98
      UnqualifiedId Name;
2506
98
      if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
2507
98
                             &TemplateKWLoc, Name)) {
2508
0
        SkipUntil(tok::semi);
2509
0
        return nullptr;
2510
0
      }
2511
98
2512
98
      // TODO: recover from mistakenly-qualified operator declarations.
2513
98
      if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2514
98
                           "access declaration")) {
2515
0
        SkipUntil(tok::semi);
2516
0
        return nullptr;
2517
0
      }
2518
98
2519
98
      // FIXME: We should do something with the 'template' keyword here.
2520
98
      return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
2521
98
          getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2522
98
          /*TypenameLoc*/ SourceLocation(), SS, Name,
2523
98
          /*EllipsisLoc*/ SourceLocation(),
2524
98
          /*AttrList*/ ParsedAttributesView())));
2525
98
    }
2526
1.11M
  }
2527
4.10M
2528
4.10M
  // static_assert-declaration. A templated static_assert declaration is
2529
4.10M
  // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2530
4.10M
  if (!TemplateInfo.Kind &&
2531
4.10M
      
Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)3.89M
) {
2532
12.5k
    SourceLocation DeclEnd;
2533
12.5k
    return DeclGroupPtrTy::make(
2534
12.5k
        DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
2535
12.5k
  }
2536
4.08M
2537
4.08M
  if (Tok.is(tok::kw_template)) {
2538
204k
    assert(!TemplateInfo.TemplateParams &&
2539
204k
           "Nested template improperly parsed?");
2540
204k
    ObjCDeclContextSwitch ObjCDC(*this);
2541
204k
    SourceLocation DeclEnd;
2542
204k
    return DeclGroupPtrTy::make(
2543
204k
        DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
2544
204k
            DeclaratorContext::MemberContext, DeclEnd, AccessAttrs, AS)));
2545
204k
  }
2546
3.88M
2547
3.88M
  // Handle:  member-declaration ::= '__extension__' member-declaration
2548
3.88M
  if (Tok.is(tok::kw___extension__)) {
2549
3
    // __extension__ silences extension warnings in the subexpression.
2550
3
    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
2551
3
    ConsumeToken();
2552
3
    return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2553
3
                                          TemplateInfo, TemplateDiags);
2554
3
  }
2555
3.88M
2556
3.88M
  ParsedAttributesWithRange attrs(AttrFactory);
2557
3.88M
  ParsedAttributesViewWithRange FnAttrs;
2558
3.88M
  // Optional C++11 attribute-specifier
2559
3.88M
  MaybeParseCXX11Attributes(attrs);
2560
3.88M
  // We need to keep these attributes for future diagnostic
2561
3.88M
  // before they are taken over by declaration specifier.
2562
3.88M
  FnAttrs.addAll(attrs.begin(), attrs.end());
2563
3.88M
  FnAttrs.Range = attrs.Range;
2564
3.88M
2565
3.88M
  MaybeParseMicrosoftAttributes(attrs);
2566
3.88M
2567
3.88M
  if (Tok.is(tok::kw_using)) {
2568
37.1k
    ProhibitAttributes(attrs);
2569
37.1k
2570
37.1k
    // Eat 'using'.
2571
37.1k
    SourceLocation UsingLoc = ConsumeToken();
2572
37.1k
2573
37.1k
    // Consume unexpected 'template' keywords.
2574
37.1k
    while (Tok.is(tok::kw_template)) {
2575
1
      SourceLocation TemplateLoc = ConsumeToken();
2576
1
      Diag(TemplateLoc, diag::err_unexpected_template_after_using)
2577
1
          << FixItHint::CreateRemoval(TemplateLoc);
2578
1
    }
2579
37.1k
2580
37.1k
    if (Tok.is(tok::kw_namespace)) {
2581
3
      Diag(UsingLoc, diag::err_using_namespace_in_class);
2582
3
      SkipUntil(tok::semi, StopBeforeMatch);
2583
3
      return nullptr;
2584
3
    }
2585
37.1k
    SourceLocation DeclEnd;
2586
37.1k
    // Otherwise, it must be a using-declaration or an alias-declaration.
2587
37.1k
    return ParseUsingDeclaration(DeclaratorContext::MemberContext, TemplateInfo,
2588
37.1k
                                 UsingLoc, DeclEnd, AS);
2589
37.1k
  }
2590
3.84M
2591
3.84M
  // Hold late-parsed attributes so we can attach a Decl to them later.
2592
3.84M
  LateParsedAttrList CommonLateParsedAttrs;
2593
3.84M
2594
3.84M
  // decl-specifier-seq:
2595
3.84M
  // Parse the common declaration-specifiers piece.
2596
3.84M
  ParsingDeclSpec DS(*this, TemplateDiags);
2597
3.84M
  DS.takeAttributesFrom(attrs);
2598
3.84M
  if (MalformedTypeSpec)
2599
11
    DS.SetTypeSpecError();
2600
3.84M
2601
3.84M
  ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2602
3.84M
                             &CommonLateParsedAttrs);
2603
3.84M
2604
3.84M
  // Turn off colon protection that was set for declspec.
2605
3.84M
  X.restore();
2606
3.84M
2607
3.84M
  // If we had a free-standing type definition with a missing semicolon, we
2608
3.84M
  // may get this far before the problem becomes obvious.
2609
3.84M
  if (DS.hasTagDefinition() &&
2610
3.84M
      
TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate57.6k
&&
2611
3.84M
      DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
2612
57.6k
                                            &CommonLateParsedAttrs))
2613
0
    return nullptr;
2614
3.84M
2615
3.84M
  MultiTemplateParamsArg TemplateParams(
2616
3.84M
      TemplateInfo.TemplateParams? 
TemplateInfo.TemplateParams->data()182k
2617
3.84M
                                 : 
nullptr3.66M
,
2618
3.84M
      TemplateInfo.TemplateParams? 
TemplateInfo.TemplateParams->size()182k
:
03.66M
);
2619
3.84M
2620
3.84M
  if (TryConsumeToken(tok::semi)) {
2621
86.8k
    if (DS.isFriendSpecified())
2622
24.6k
      ProhibitAttributes(FnAttrs);
2623
86.8k
2624
86.8k
    RecordDecl *AnonRecord = nullptr;
2625
86.8k
    Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2626
86.8k
        getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
2627
86.8k
    DS.complete(TheDecl);
2628
86.8k
    if (AnonRecord) {
2629
0
      Decl* decls[] = {AnonRecord, TheDecl};
2630
0
      return Actions.BuildDeclaratorGroup(decls);
2631
0
    }
2632
86.8k
    return Actions.ConvertDeclToDeclGroup(TheDecl);
2633
86.8k
  }
2634
3.76M
2635
3.76M
  ParsingDeclarator DeclaratorInfo(*this, DS, DeclaratorContext::MemberContext);
2636
3.76M
  VirtSpecifiers VS;
2637
3.76M
2638
3.76M
  // Hold late-parsed attributes so we can attach a Decl to them later.
2639
3.76M
  LateParsedAttrList LateParsedAttrs;
2640
3.76M
2641
3.76M
  SourceLocation EqualLoc;
2642
3.76M
  SourceLocation PureSpecLoc;
2643
3.76M
2644
3.76M
  auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
2645
21.5k
    if (Tok.isNot(tok::equal))
2646
5.35k
      return false;
2647
16.1k
2648
16.1k
    auto &Zero = NextToken();
2649
16.1k
    SmallString<8> Buffer;
2650
16.1k
    if (Zero.isNot(tok::numeric_constant) || 
Zero.getLength() != 115.8k
||
2651
16.1k
        
PP.getSpelling(Zero, Buffer) != "0"15.8k
)
2652
382
      return false;
2653
15.8k
2654
15.8k
    auto &After = GetLookAheadToken(2);
2655
15.8k
    if (!After.isOneOf(tok::semi, tok::comma) &&
2656
15.8k
        
!(3
AllowDefinition3
&&
2657
3
          After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2658
0
      return false;
2659
15.8k
2660
15.8k
    EqualLoc = ConsumeToken();
2661
15.8k
    PureSpecLoc = ConsumeToken();
2662
15.8k
    return true;
2663
15.8k
  };
2664
3.76M
2665
3.76M
  SmallVector<Decl *, 8> DeclsInGroup;
2666
3.76M
  ExprResult BitfieldSize;
2667
3.76M
  bool ExpectSemi = true;
2668
3.76M
2669
3.76M
  // Parse the first declarator.
2670
3.76M
  if (ParseCXXMemberDeclaratorBeforeInitializer(
2671
3.76M
          DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
2672
94
    TryConsumeToken(tok::semi);
2673
94
    return nullptr;
2674
94
  }
2675
3.76M
2676
3.76M
  // Check for a member function definition.
2677
3.76M
  if (BitfieldSize.isUnset()) {
2678
3.75M
    // MSVC permits pure specifier on inline functions defined at class scope.
2679
3.75M
    // Hence check for =0 before checking for function definition.
2680
3.75M
    if (getLangOpts().MicrosoftExt && 
DeclaratorInfo.isDeclarationOfFunction()8.71k
)
2681
5.74k
      TryConsumePureSpecifier(/*AllowDefinition*/ true);
2682
3.75M
2683
3.75M
    FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2684
3.75M
    // function-definition:
2685
3.75M
    //
2686
3.75M
    // In C++11, a non-function declarator followed by an open brace is a
2687
3.75M
    // braced-init-list for an in-class member initialization, not an
2688
3.75M
    // erroneous function definition.
2689
3.75M
    if (Tok.is(tok::l_brace) && 
!getLangOpts().CPlusPlus11921k
) {
2690
54.0k
      DefinitionKind = FDK_Definition;
2691
3.69M
    } else if (DeclaratorInfo.isFunctionDeclarator()) {
2692
1.63M
      if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
2693
999k
        DefinitionKind = FDK_Definition;
2694
999k
      } else 
if (632k
Tok.is(tok::equal)632k
) {
2695
46.2k
        const Token &KW = NextToken();
2696
46.2k
        if (KW.is(tok::kw_default))
2697
12.2k
          DefinitionKind = FDK_Defaulted;
2698
34.0k
        else if (KW.is(tok::kw_delete))
2699
18.2k
          DefinitionKind = FDK_Deleted;
2700
46.2k
      }
2701
1.63M
    }
2702
3.75M
    DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
2703
3.75M
2704
3.75M
    // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2705
3.75M
    // to a friend declaration, that declaration shall be a definition.
2706
3.75M
    if (DeclaratorInfo.isFunctionDeclarator() &&
2707
3.75M
        
DefinitionKind != FDK_Definition1.68M
&&
DS.isFriendSpecified()632k
) {
2708
20.0k
      // Diagnose attributes that appear before decl specifier:
2709
20.0k
      // [[]] friend int foo();
2710
20.0k
      ProhibitAttributes(FnAttrs);
2711
20.0k
    }
2712
3.75M
2713
3.75M
    if (DefinitionKind != FDK_Declaration) {
2714
1.08M
      if (!DeclaratorInfo.isFunctionDeclarator()) {
2715
2
        Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2716
2
        ConsumeBrace();
2717
2
        SkipUntil(tok::r_brace);
2718
2
2719
2
        // Consume the optional ';'
2720
2
        TryConsumeToken(tok::semi);
2721
2
2722
2
        return nullptr;
2723
2
      }
2724
1.08M
2725
1.08M
      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2726
12
        Diag(DeclaratorInfo.getIdentifierLoc(),
2727
12
             diag::err_function_declared_typedef);
2728
12
2729
12
        // Recover by treating the 'typedef' as spurious.
2730
12
        DS.ClearStorageClassSpecs();
2731
12
      }
2732
1.08M
2733
1.08M
      Decl *FunDecl =
2734
1.08M
        ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2735
1.08M
                                VS, PureSpecLoc);
2736
1.08M
2737
1.08M
      if (FunDecl) {
2738
1.08M
        for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; 
++i0
) {
2739
0
          CommonLateParsedAttrs[i]->addDecl(FunDecl);
2740
0
        }
2741
1.08M
        for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; 
++i2.72k
) {
2742
2.72k
          LateParsedAttrs[i]->addDecl(FunDecl);
2743
2.72k
        }
2744
1.08M
      }
2745
1.08M
      LateParsedAttrs.clear();
2746
1.08M
2747
1.08M
      // Consume the ';' - it's optional unless we have a delete or default
2748
1.08M
      if (Tok.is(tok::semi))
2749
4.38k
        ConsumeExtraSemi(AfterMemberFunctionDefinition);
2750
1.08M
2751
1.08M
      return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
2752
1.08M
    }
2753
3.75M
  }
2754
2.67M
2755
2.67M
  // member-declarator-list:
2756
2.67M
  //   member-declarator
2757
2.67M
  //   member-declarator-list ',' member-declarator
2758
2.67M
2759
2.69M
  
while (2.67M
1) {
2760
2.69M
    InClassInitStyle HasInClassInit = ICIS_NoInit;
2761
2.69M
    bool HasStaticInitializer = false;
2762
2.69M
    if (Tok.isOneOf(tok::equal, tok::l_brace) && 
PureSpecLoc.isInvalid()337k
) {
2763
337k
      if (DeclaratorInfo.isDeclarationOfFunction()) {
2764
15.8k
        // It's a pure-specifier.
2765
15.8k
        if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2766
23
          // Parse it as an expression so that Sema can diagnose it.
2767
23
          HasStaticInitializer = true;
2768
321k
      } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2769
321k
                     DeclSpec::SCS_static &&
2770
321k
                 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2771
9.82k
                     DeclSpec::SCS_typedef &&
2772
321k
                 
!DS.isFriendSpecified()9.82k
) {
2773
9.82k
        // It's a default member initializer.
2774
9.82k
        if (BitfieldSize.get())
2775
8
          Diag(Tok, getLangOpts().CPlusPlus2a
2776
8
                        ? 
diag::warn_cxx17_compat_bitfield_member_init6
2777
8
                        : 
diag::ext_bitfield_member_init2
);
2778
9.82k
        HasInClassInit = Tok.is(tok::equal) ? 
ICIS_CopyInit9.74k
:
ICIS_ListInit80
;
2779
311k
      } else {
2780
311k
        HasStaticInitializer = true;
2781
311k
      }
2782
337k
    }
2783
2.69M
2784
2.69M
    // NOTE: If Sema is the Action module and declarator is an instance field,
2785
2.69M
    // this call will *not* return the created decl; It will return null.
2786
2.69M
    // See Sema::ActOnCXXMemberDeclarator for details.
2787
2.69M
2788
2.69M
    NamedDecl *ThisDecl = nullptr;
2789
2.69M
    if (DS.isFriendSpecified()) {
2790
20.0k
      // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2791
20.0k
      // to a friend declaration, that declaration shall be a definition.
2792
20.0k
      //
2793
20.0k
      // Diagnose attributes that appear in a friend member function declarator:
2794
20.0k
      //   friend int foo [[]] ();
2795
20.0k
      SmallVector<SourceRange, 4> Ranges;
2796
20.0k
      DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2797
20.0k
      for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2798
20.0k
           E = Ranges.end(); I != E; 
++I4
)
2799
4
        Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
2800
20.0k
2801
20.0k
      ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2802
20.0k
                                                 TemplateParams);
2803
2.67M
    } else {
2804
2.67M
      ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2805
2.67M
                                                  DeclaratorInfo,
2806
2.67M
                                                  TemplateParams,
2807
2.67M
                                                  BitfieldSize.get(),
2808
2.67M
                                                  VS, HasInClassInit);
2809
2.67M
2810
2.67M
      if (VarTemplateDecl *VT =
2811
349
              ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
2812
349
        // Re-direct this decl to refer to the templated decl so that we can
2813
349
        // initialize it.
2814
349
        ThisDecl = VT->getTemplatedDecl();
2815
2.67M
2816
2.67M
      if (ThisDecl)
2817
2.67M
        Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
2818
2.67M
    }
2819
2.69M
2820
2.69M
    // Error recovery might have converted a non-static member into a static
2821
2.69M
    // member.
2822
2.69M
    if (HasInClassInit != ICIS_NoInit &&
2823
2.69M
        DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2824
9.82k
            DeclSpec::SCS_static) {
2825
6
      HasInClassInit = ICIS_NoInit;
2826
6
      HasStaticInitializer = true;
2827
6
    }
2828
2.69M
2829
2.69M
    if (ThisDecl && 
PureSpecLoc.isValid()2.69M
)
2830
15.8k
      Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2831
2.69M
2832
2.69M
    // Handle the initializer.
2833
2.69M
    if (HasInClassInit != ICIS_NoInit) {
2834
9.81k
      // The initializer was deferred; parse it and cache the tokens.
2835
9.81k
      Diag(Tok, getLangOpts().CPlusPlus11
2836
9.81k
                    ? 
diag::warn_cxx98_compat_nonstatic_member_init9.80k
2837
9.81k
                    : 
diag::ext_nonstatic_member_init14
);
2838
9.81k
2839
9.81k
      if (DeclaratorInfo.isArrayOfUnknownBound()) {
2840
4
        // C++11 [dcl.array]p3: An array bound may also be omitted when the
2841
4
        // declarator is followed by an initializer.
2842
4
        //
2843
4
        // A brace-or-equal-initializer for a member-declarator is not an
2844
4
        // initializer in the grammar, so this is ill-formed.
2845
4
        Diag(Tok, diag::err_incomplete_array_member_init);
2846
4
        SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2847
4
2848
4
        // Avoid later warnings about a class member of incomplete type.
2849
4
        if (ThisDecl)
2850
3
          ThisDecl->setInvalidDecl();
2851
4
      } else
2852
9.81k
        ParseCXXNonStaticMemberInitializer(ThisDecl);
2853
2.68M
    } else if (HasStaticInitializer) {
2854
311k
      // Normal initializer.
2855
311k
      ExprResult Init = ParseCXXMemberInitializer(
2856
311k
          ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2857
311k
2858
311k
      if (Init.isInvalid())
2859
40
        SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2860
311k
      else if (ThisDecl)
2861
311k
        Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
2862
2.37M
    } else if (ThisDecl && 
DS.getStorageClassSpec() == DeclSpec::SCS_static2.37M
)
2863
61.7k
      // No initializer.
2864
61.7k
      Actions.ActOnUninitializedDecl(ThisDecl);
2865
2.69M
2866
2.69M
    if (ThisDecl) {
2867
2.69M
      if (!ThisDecl->isInvalidDecl()) {
2868
2.69M
        // Set the Decl for any late parsed attributes
2869
2.69M
        for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; 
++i21
)
2870
21
          CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2871
2.69M
2872
2.69M
        for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; 
++i1.61k
)
2873
1.61k
          LateParsedAttrs[i]->addDecl(ThisDecl);
2874
2.69M
      }
2875
2.69M
      Actions.FinalizeDeclaration(ThisDecl);
2876
2.69M
      DeclsInGroup.push_back(ThisDecl);
2877
2.69M
2878
2.69M
      if (DeclaratorInfo.isFunctionDeclarator() &&
2879
2.69M
          DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2880
602k
              DeclSpec::SCS_typedef)
2881
585k
        HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2882
2.69M
    }
2883
2.69M
    LateParsedAttrs.clear();
2884
2.69M
2885
2.69M
    DeclaratorInfo.complete(ThisDecl);
2886
2.69M
2887
2.69M
    // If we don't have a comma, it is either the end of the list (a ';')
2888
2.69M
    // or an error, bail out.
2889
2.69M
    SourceLocation CommaLoc;
2890
2.69M
    if (!TryConsumeToken(tok::comma, CommaLoc))
2891
2.67M
      break;
2892
18.4k
2893
18.4k
    if (Tok.isAtStartOfLine() &&
2894
18.4k
        
!MightBeDeclarator(DeclaratorContext::MemberContext)10.9k
) {
2895
44
      // This comma was followed by a line-break and something which can't be
2896
44
      // the start of a declarator. The comma was probably a typo for a
2897
44
      // semicolon.
2898
44
      Diag(CommaLoc, diag::err_expected_semi_declaration)
2899
44
        << FixItHint::CreateReplacement(CommaLoc, ";");
2900
44
      ExpectSemi = false;
2901
44
      break;
2902
44
    }
2903
18.3k
2904
18.3k
    // Parse the next declarator.
2905
18.3k
    DeclaratorInfo.clear();
2906
18.3k
    VS.clear();
2907
18.3k
    BitfieldSize = ExprResult(/*Invalid=*/false);
2908
18.3k
    EqualLoc = PureSpecLoc = SourceLocation();
2909
18.3k
    DeclaratorInfo.setCommaLoc(CommaLoc);
2910
18.3k
2911
18.3k
    // GNU attributes are allowed before the second and subsequent declarator.
2912
18.3k
    MaybeParseGNUAttributes(DeclaratorInfo);
2913
18.3k
2914
18.3k
    if (ParseCXXMemberDeclaratorBeforeInitializer(
2915
18.3k
            DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2916
6
      break;
2917
18.3k
  }
2918
2.67M
2919
2.67M
  if (ExpectSemi &&
2920
2.67M
      
ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)2.67M
) {
2921
62
    // Skip to end of block or statement.
2922
62
    SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2923
62
    // If we stopped at a ';', eat it.
2924
62
    TryConsumeToken(tok::semi);
2925
62
    return nullptr;
2926
62
  }
2927
2.67M
2928
2.67M
  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2929
2.67M
}
2930
2931
/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2932
/// Also detect and reject any attempted defaulted/deleted function definition.
2933
/// The location of the '=', if any, will be placed in EqualLoc.
2934
///
2935
/// This does not check for a pure-specifier; that's handled elsewhere.
2936
///
2937
///   brace-or-equal-initializer:
2938
///     '=' initializer-expression
2939
///     braced-init-list
2940
///
2941
///   initializer-clause:
2942
///     assignment-expression
2943
///     braced-init-list
2944
///
2945
///   defaulted/deleted function-definition:
2946
///     '=' 'default'
2947
///     '=' 'delete'
2948
///
2949
/// Prior to C++0x, the assignment-expression in an initializer-clause must
2950
/// be a constant-expression.
2951
ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2952
321k
                                             SourceLocation &EqualLoc) {
2953
321k
  assert(Tok.isOneOf(tok::equal, tok::l_brace)
2954
321k
         && "Data member initializer not starting with '=' or '{'");
2955
321k
2956
321k
  EnterExpressionEvaluationContext Context(
2957
321k
      Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
2958
321k
  if (TryConsumeToken(tok::equal, EqualLoc)) {
2959
321k
    if (Tok.is(tok::kw_delete)) {
2960
2
      // In principle, an initializer of '= delete p;' is legal, but it will
2961
2
      // never type-check. It's better to diagnose it as an ill-formed expression
2962
2
      // than as an ill-formed deleted non-function member.
2963
2
      // An initializer of '= delete p, foo' will never be parsed, because
2964
2
      // a top-level comma always ends the initializer expression.
2965
2
      const Token &Next = NextToken();
2966
2
      if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
2967
2
        if (IsFunction)
2968
0
          Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2969
0
            << 1 /* delete */;
2970
2
        else
2971
2
          Diag(ConsumeToken(), diag::err_deleted_non_function);
2972
2
        return ExprError();
2973
2
      }
2974
321k
    } else if (Tok.is(tok::kw_default)) {
2975
0
      if (IsFunction)
2976
0
        Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2977
0
          << 0 /* default */;
2978
0
      else
2979
0
        Diag(ConsumeToken(), diag::err_default_special_members);
2980
0
      return ExprError();
2981
0
    }
2982
321k
  }
2983
321k
  if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2984
1
    Diag(Tok, diag::err_ms_property_initializer) << PD;
2985
1
    return ExprError();
2986
1
  }
2987
321k
  return ParseInitializer();
2988
321k
}
2989
2990
void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2991
                                        SourceLocation AttrFixitLoc,
2992
253
                                        unsigned TagType, Decl *TagDecl) {
2993
253
  // Skip the optional 'final' keyword.
2994
253
  if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2995
0
    assert(isCXX11FinalKeyword() && "not a class definition");
2996
0
    ConsumeToken();
2997
0
2998
0
    // Diagnose any C++11 attributes after 'final' keyword.
2999
0
    // We deliberately discard these attributes.
3000
0
    ParsedAttributesWithRange Attrs(AttrFactory);
3001
0
    CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3002
0
3003
0
    // This can only happen if we had malformed misplaced attributes;
3004
0
    // we only get called if there is a colon or left-brace after the
3005
0
    // attributes.
3006
0
    if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
3007
0
      return;
3008
253
  }
3009
253
3010
253
  // Skip the base clauses. This requires actually parsing them, because
3011
253
  // otherwise we can't be sure where they end (a left brace may appear
3012
253
  // within a template argument).
3013
253
  if (Tok.is(tok::colon)) {
3014
47
    // Enter the scope of the class so that we can correctly parse its bases.
3015
47
    ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
3016
47
    ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
3017
47
                                      TagType == DeclSpec::TST_interface);
3018
47
    auto OldContext =
3019
47
        Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
3020
47
3021
47
    // Parse the bases but don't attach them to the class.
3022
47
    ParseBaseClause(nullptr);
3023
47
3024
47
    Actions.ActOnTagFinishSkippedDefinition(OldContext);
3025
47
3026
47
    if (!Tok.is(tok::l_brace)) {
3027
0
      Diag(PP.getLocForEndOfToken(PrevTokLocation),
3028
0
           diag::err_expected_lbrace_after_base_specifiers);
3029
0
      return;
3030
0
    }
3031
253
  }
3032
253
3033
253
  // Skip the body.
3034
253
  assert(Tok.is(tok::l_brace));
3035
253
  BalancedDelimiterTracker T(*this, tok::l_brace);
3036
253
  T.consumeOpen();
3037
253
  T.skipToEnd();
3038
253
3039
253
  // Parse and discard any trailing attributes.
3040
253
  ParsedAttributes Attrs(AttrFactory);
3041
253
  if (Tok.is(tok::kw___attribute))
3042
5
    MaybeParseGNUAttributes(Attrs);
3043
253
}
3044
3045
Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3046
    AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3047
4.16M
    DeclSpec::TST TagType, Decl *TagDecl) {
3048
4.16M
  ParenBraceBracketBalancer BalancerRAIIObj(*this);
3049
4.16M
3050
4.16M
  switch (Tok.getKind()) {
3051
4.16M
  case tok::kw___if_exists:
3052
8
  case tok::kw___if_not_exists:
3053
8
    ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS);
3054
8
    return nullptr;
3055
8
3056
716
  case tok::semi:
3057
716
    // Check for extraneous top-level semicolon.
3058
716
    ConsumeExtraSemi(InsideStruct, TagType);
3059
716
    return nullptr;
3060
8
3061
8
    // Handle pragmas that can appear as member declarations.
3062
8
  case tok::annot_pragma_vis:
3063
2
    HandlePragmaVisibility();
3064
2
    return nullptr;
3065
8
  case tok::annot_pragma_pack:
3066
0
    HandlePragmaPack();
3067
0
    return nullptr;
3068
8
  case tok::annot_pragma_align:
3069
1
    HandlePragmaAlign();
3070
1
    return nullptr;
3071
8
  case tok::annot_pragma_ms_pointers_to_members:
3072
0
    HandlePragmaMSPointersToMembers();
3073
0
    return nullptr;
3074
8
  case tok::annot_pragma_ms_pragma:
3075
6
    HandlePragmaMSPragma();
3076
6
    return nullptr;
3077
8
  case tok::annot_pragma_ms_vtordisp:
3078
2
    HandlePragmaMSVtorDisp();
3079
2
    return nullptr;
3080
8
  case tok::annot_pragma_dump:
3081
0
    HandlePragmaDump();
3082
0
    return nullptr;
3083
8
3084
8
  case tok::kw_namespace:
3085
2
    // If we see a namespace here, a close brace was missing somewhere.
3086
2
    DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
3087
2
    return nullptr;
3088
8
3089
93.5k
  case tok::kw_private:
3090
93.5k
    // FIXME: We don't accept GNU attributes on access specifiers in OpenCL mode
3091
93.5k
    // yet.
3092
93.5k
    if (getLangOpts().OpenCL && 
!NextToken().is(tok::colon)6
)
3093
4
      return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
3094
93.4k
    LLVM_FALLTHROUGH;
3095
265k
  case tok::kw_public:
3096
265k
  case tok::kw_protected: {
3097
265k
    AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3098
265k
    assert(NewAS != AS_none);
3099
265k
    // Current token is a C++ access specifier.
3100
265k
    AS = NewAS;
3101
265k
    SourceLocation ASLoc = Tok.getLocation();
3102
265k
    unsigned TokLength = Tok.getLength();
3103
265k
    ConsumeToken();
3104
265k
    AccessAttrs.clear();
3105
265k
    MaybeParseGNUAttributes(AccessAttrs);
3106
265k
3107
265k
    SourceLocation EndLoc;
3108
265k
    if (TryConsumeToken(tok::colon, EndLoc)) {
3109
265k
    } else 
if (10
TryConsumeToken(tok::semi, EndLoc)10
) {
3110
3
      Diag(EndLoc, diag::err_expected)
3111
3
          << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3112
7
    } else {
3113
7
      EndLoc = ASLoc.getLocWithOffset(TokLength);
3114
7
      Diag(EndLoc, diag::err_expected)
3115
7
          << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3116
7
    }
3117
265k
3118
265k
    // The Microsoft extension __interface does not permit non-public
3119
265k
    // access specifiers.
3120
265k
    if (TagType == DeclSpec::TST_interface && 
AS != AS_public5
) {
3121
4
      Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3122
4
    }
3123
265k
3124
265k
    if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) {
3125
1
      // found another attribute than only annotations
3126
1
      AccessAttrs.clear();
3127
1
    }
3128
265k
3129
265k
    return nullptr;
3130
265k
  }
3131
265k
3132
265k
  case tok::annot_pragma_openmp:
3133
283
    return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3134
283
                                                      TagDecl);
3135
265k
3136
3.89M
  default:
3137
3.89M
    return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
3138
4.16M
  }
3139
4.16M
}
3140
3141
/// ParseCXXMemberSpecification - Parse the class definition.
3142
///
3143
///       member-specification:
3144
///         member-declaration member-specification[opt]
3145
///         access-specifier ':' member-specification[opt]
3146
///
3147
void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
3148
                                         SourceLocation AttrFixitLoc,
3149
                                         ParsedAttributesWithRange &Attrs,
3150
844k
                                         unsigned TagType, Decl *TagDecl) {
3151
844k
  assert((TagType == DeclSpec::TST_struct ||
3152
844k
         TagType == DeclSpec::TST_interface ||
3153
844k
         TagType == DeclSpec::TST_union  ||
3154
844k
         TagType == DeclSpec::TST_class) && "Invalid TagType!");
3155
844k
3156
844k
  llvm::TimeTraceScope TimeScope("ParseClass", [&]() {
3157
1
    if (auto *TD = dyn_cast_or_null<NamedDecl>(TagDecl))
3158
1
      return TD->getQualifiedNameAsString();
3159
0
    return std::string("<anonymous>");
3160
0
  });
3161
844k
3162
844k
  PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
3163
844k
                                      "parsing struct/union/class body");
3164
844k
3165
844k
  // Determine whether this is a non-nested class. Note that local
3166
844k
  // classes are *not* considered to be nested classes.
3167
844k
  bool NonNestedClass = true;
3168
844k
  if (!ClassStack.empty()) {
3169
70.8k
    for (const Scope *S = getCurScope(); S; 
S = S->getParent()10.2k
) {
3170
70.8k
      if (S->isClassScope()) {
3171
58.4k
        // We're inside a class scope, so this is a nested class.
3172
58.4k
        NonNestedClass = false;
3173
58.4k
3174
58.4k
        // The Microsoft extension __interface does not permit nested classes.
3175
58.4k
        if (getCurrentClass().IsInterface) {
3176
1
          Diag(RecordLoc, diag::err_invalid_member_in_interface)
3177
1
            << /*ErrorType=*/6
3178
1
            << (isa<NamedDecl>(TagDecl)
3179
1
                  ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
3180
1
                  : 
"(anonymous)"0
);
3181
1
        }
3182
58.4k
        break;
3183
58.4k
      }
3184
12.3k
3185
12.3k
      if ((S->getFlags() & Scope::FnScope))
3186
2.11k
        // If we're in a function or function template then this is a local
3187
2.11k
        // class rather than a nested class.
3188
2.11k
        break;
3189
12.3k
    }
3190
60.5k
  }
3191
844k
3192
844k
  // Enter a scope for the class.
3193
844k
  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
3194
844k
3195
844k
  // Note that we are parsing a new (potentially-nested) class definition.
3196
844k
  ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3197
844k
                                    TagType == DeclSpec::TST_interface);
3198
844k
3199
844k
  if (TagDecl)
3200
844k
    Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3201
844k
3202
844k
  SourceLocation FinalLoc;
3203
844k
  bool IsFinalSpelledSealed = false;
3204
844k
3205
844k
  // Parse the optional 'final' keyword.
3206
844k
  if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
3207
703
    VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3208
703
    assert((Specifier == VirtSpecifiers::VS_Final ||
3209
703
            Specifier == VirtSpecifiers::VS_GNU_Final ||
3210
703
            Specifier == VirtSpecifiers::VS_Sealed) &&
3211
703
           "not a class definition");
3212
703
    FinalLoc = ConsumeToken();
3213
703
    IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
3214
703
3215
703
    if (TagType == DeclSpec::TST_interface)
3216
4
      Diag(FinalLoc, diag::err_override_control_interface)
3217
4
        << VirtSpecifiers::getSpecifierName(Specifier);
3218
699
    else if (Specifier == VirtSpecifiers::VS_Final)
3219
685
      Diag(FinalLoc, getLangOpts().CPlusPlus11
3220
685
                         ? 
diag::warn_cxx98_compat_override_control_keyword683
3221
685
                         : 
diag::ext_override_control_keyword2
)
3222
685
        << VirtSpecifiers::getSpecifierName(Specifier);
3223
14
    else if (Specifier == VirtSpecifiers::VS_Sealed)
3224
12
      Diag(FinalLoc, diag::ext_ms_sealed_keyword);
3225
2
    else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3226
2
      Diag(FinalLoc, diag::ext_warn_gnu_final);
3227
703
3228
703
    // Parse any C++11 attributes after 'final' keyword.
3229
703
    // These attributes are not allowed to appear here,
3230
703
    // and the only possible place for them to appertain
3231
703
    // to the class would be between class-key and class-name.
3232
703
    CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3233
703
3234
703
    // ParseClassSpecifier() does only a superficial check for attributes before
3235
703
    // deciding to call this method.  For example, for
3236
703
    // `class C final alignas ([l) {` it will decide that this looks like a
3237
703
    // misplaced attribute since it sees `alignas '(' ')'`.  But the actual
3238
703
    // attribute parsing code will try to parse the '[' as a constexpr lambda
3239
703
    // and consume enough tokens that the alignas parsing code will eat the
3240
703
    // opening '{'.  So bail out if the next token isn't one we expect.
3241
703
    if (!Tok.is(tok::colon) && 
!Tok.is(tok::l_brace)656
) {
3242
2
      if (TagDecl)
3243
2
        Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3244
2
      return;
3245
2
    }
3246
844k
  }
3247
844k
3248
844k
  if (Tok.is(tok::colon)) {
3249
257k
    ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3250
257k
                                          Scope::ClassInheritanceScope);
3251
257k
3252
257k
    ParseBaseClause(TagDecl);
3253
257k
    if (!Tok.is(tok::l_brace)) {
3254
46
      bool SuggestFixIt = false;
3255
46
      SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3256
46
      if (Tok.isAtStartOfLine()) {
3257
36
        switch (Tok.getKind()) {
3258
36
        case tok::kw_private:
3259
5
        case tok::kw_protected:
3260
5
        case tok::kw_public:
3261
5
          SuggestFixIt = NextToken().getKind() == tok::colon;
3262
5
          break;
3263
13
        case tok::kw_static_assert:
3264
13
        case tok::r_brace:
3265
13
        case tok::kw_using:
3266
13
        // base-clause can have simple-template-id; 'template' can't be there
3267
13
        case tok::kw_template:
3268
13
          SuggestFixIt = true;
3269
13
          break;
3270
13
        case tok::identifier:
3271
9
          SuggestFixIt = isConstructorDeclarator(true);
3272
9
          break;
3273
13
        default:
3274
9
          SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3275
9
          break;
3276
46
        }
3277
46
      }
3278
46
      DiagnosticBuilder LBraceDiag =
3279
46
          Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3280
46
      if (SuggestFixIt) {
3281
31
        LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3282
31
        // Try recovering from missing { after base-clause.
3283
31
        PP.EnterToken(Tok, /*IsReinject*/true);
3284
31
        Tok.setKind(tok::l_brace);
3285
31
      } else {
3286
15
        if (TagDecl)
3287
15
          Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3288
15
        return;
3289
15
      }
3290
844k
    }
3291
257k
  }
3292
844k
3293
844k
  assert(Tok.is(tok::l_brace));
3294
844k
  BalancedDelimiterTracker T(*this, tok::l_brace);
3295
844k
  T.consumeOpen();
3296
844k
3297
844k
  if (TagDecl)
3298
844k
    Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
3299
844k
                                            IsFinalSpelledSealed,
3300
844k
                                            T.getOpenLocation());
3301
844k
3302
844k
  // C++ 11p3: Members of a class defined with the keyword class are private
3303
844k
  // by default. Members of a class defined with the keywords struct or union
3304
844k
  // are public by default.
3305
844k
  AccessSpecifier CurAS;
3306
844k
  if (TagType == DeclSpec::TST_class)
3307
144k
    CurAS = AS_private;
3308
699k
  else
3309
699k
    CurAS = AS_public;
3310
844k
  ParsedAttributesWithRange AccessAttrs(AttrFactory);
3311
844k
3312
844k
  if (TagDecl) {
3313
844k
    // While we still have something to read, read the member-declarations.
3314
5.00M
    while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3315
5.00M
           
Tok.isNot(tok::eof)4.16M
) {
3316
4.16M
      // Each iteration of this loop reads one member-declaration.
3317
4.16M
      ParseCXXClassMemberDeclarationWithPragmas(
3318
4.16M
          CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
3319
4.16M
    }
3320
844k
    T.consumeClose();
3321
844k
  } else {
3322
185
    SkipUntil(tok::r_brace);
3323
185
  }
3324
844k
3325
844k
  // If attributes exist after class contents, parse them.
3326
844k
  ParsedAttributes attrs(AttrFactory);
3327
844k
  MaybeParseGNUAttributes(attrs);
3328
844k
3329
844k
  if (TagDecl)
3330
844k
    Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
3331
844k
                                              T.getOpenLocation(),
3332
844k
                                              T.getCloseLocation(), attrs);
3333
844k
3334
844k
  // C++11 [class.mem]p2:
3335
844k
  //   Within the class member-specification, the class is regarded as complete
3336
844k
  //   within function bodies, default arguments, exception-specifications, and
3337
844k
  //   brace-or-equal-initializers for non-static data members (including such
3338
844k
  //   things in nested classes).
3339
844k
  if (TagDecl && 
NonNestedClass844k
) {
3340
785k
    // We are not inside a nested class. This class and its nested classes
3341
785k
    // are complete and we can parse the delayed portions of method
3342
785k
    // declarations and the lexed inline method definitions, along with any
3343
785k
    // delayed attributes.
3344
785k
    SourceLocation SavedPrevTokLocation = PrevTokLocation;
3345
785k
    ParseLexedAttributes(getCurrentClass());
3346
785k
    ParseLexedMethodDeclarations(getCurrentClass());
3347
785k
3348
785k
    // We've finished with all pending member declarations.
3349
785k
    Actions.ActOnFinishCXXMemberDecls();
3350
785k
3351
785k
    ParseLexedMemberInitializers(getCurrentClass());
3352
785k
    ParseLexedMethodDefs(getCurrentClass());
3353
785k
    PrevTokLocation = SavedPrevTokLocation;
3354
785k
3355
785k
    // We've finished parsing everything, including default argument
3356
785k
    // initializers.
3357
785k
    Actions.ActOnFinishCXXNonNestedClass(TagDecl);
3358
785k
  }
3359
844k
3360
844k
  if (TagDecl)
3361
844k
    Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
3362
844k
3363
844k
  // Leave the class scope.
3364
844k
  ParsingDef.Pop();
3365
844k
  ClassScope.Exit();
3366
844k
}
3367
3368
2
void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
3369
2
  assert(Tok.is(tok::kw_namespace));
3370
2
3371
2
  // FIXME: Suggest where the close brace should have gone by looking
3372
2
  // at indentation changes within the definition body.
3373
2
  Diag(D->getLocation(),
3374
2
       diag::err_missing_end_of_definition) << D;
3375
2
  Diag(Tok.getLocation(),
3376
2
       diag::note_missing_end_of_definition_before) << D;
3377
2
3378
2
  // Push '};' onto the token stream to recover.
3379
2
  PP.EnterToken(Tok, /*IsReinject*/ true);
3380
2
3381
2
  Tok.startToken();
3382
2
  Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3383
2
  Tok.setKind(tok::semi);
3384
2
  PP.EnterToken(Tok, /*IsReinject*/ true);
3385
2
3386
2
  Tok.setKind(tok::r_brace);
3387
2
}
3388
3389
/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3390
/// which explicitly initializes the members or base classes of a
3391
/// class (C++ [class.base.init]). For example, the three initializers
3392
/// after the ':' in the Derived constructor below:
3393
///
3394
/// @code
3395
/// class Base { };
3396
/// class Derived : Base {
3397
///   int x;
3398
///   float f;
3399
/// public:
3400
///   Derived(float f) : Base(), x(17), f(f) { }
3401
/// };
3402
/// @endcode
3403
///
3404
/// [C++]  ctor-initializer:
3405
///          ':' mem-initializer-list
3406
///
3407
/// [C++]  mem-initializer-list:
3408
///          mem-initializer ...[opt]
3409
///          mem-initializer ...[opt] , mem-initializer-list
3410
164k
void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
3411
164k
  assert(Tok.is(tok::colon) &&
3412
164k
         "Constructor initializer always starts with ':'");
3413
164k
3414
164k
  // Poison the SEH identifiers so they are flagged as illegal in constructor
3415
164k
  // initializers.
3416
164k
  PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
3417
164k
  SourceLocation ColonLoc = ConsumeToken();
3418
164k
3419
164k
  SmallVector<CXXCtorInitializer*, 4> MemInitializers;
3420
164k
  bool AnyErrors = false;
3421
164k
3422
269k
  do {
3423
269k
    if (Tok.is(tok::code_completion)) {
3424
28
      Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3425
28
                                                 MemInitializers);
3426
28
      return cutOffParsing();
3427
28
    }
3428
269k
3429
269k
    MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3430
269k
    if (!MemInit.isInvalid())
3431
269k
      MemInitializers.push_back(MemInit.get());
3432
162
    else
3433
162
      AnyErrors = true;
3434
269k
3435
269k
    if (Tok.is(tok::comma))
3436
105k
      ConsumeToken();
3437
164k
    else if (Tok.is(tok::l_brace))
3438
164k
      break;
3439
28
    // If the previous initializer was valid and the next token looks like a
3440
28
    // base or member initializer, assume that we're just missing a comma.
3441
28
    else if (!MemInit.isInvalid() &&
3442
28
             
Tok.isOneOf(tok::identifier, tok::coloncolon)9
) {
3443
8
      SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3444
8
      Diag(Loc, diag::err_ctor_init_missing_comma)
3445
8
        << FixItHint::CreateInsertion(Loc, ", ");
3446
20
    } else {
3447
20
      // Skip over garbage, until we get to '{'.  Don't eat the '{'.
3448
20
      if (!MemInit.isInvalid())
3449
1
        Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3450
1
                                                           << tok::comma;
3451
20
      SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
3452
20
      break;
3453
20
    }
3454
105k
  } while (true);
3455
164k
3456
164k
  Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
3457
164k
                               AnyErrors);
3458
164k
}
3459
3460
/// ParseMemInitializer - Parse a C++ member initializer, which is
3461
/// part of a constructor initializer that explicitly initializes one
3462
/// member or base class (C++ [class.base.init]). See
3463
/// ParseConstructorInitializer for an example.
3464
///
3465
/// [C++] mem-initializer:
3466
///         mem-initializer-id '(' expression-list[opt] ')'
3467
/// [C++0x] mem-initializer-id braced-init-list
3468
///
3469
/// [C++] mem-initializer-id:
3470
///         '::'[opt] nested-name-specifier[opt] class-name
3471
///         identifier
3472
269k
MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
3473
269k
  // parse '::'[opt] nested-name-specifier[opt]
3474
269k
  CXXScopeSpec SS;
3475
269k
  if (ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false))
3476
2
    return true;
3477
269k
3478
269k
  // : identifier
3479
269k
  IdentifierInfo *II = nullptr;
3480
269k
  SourceLocation IdLoc = Tok.getLocation();
3481
269k
  // : declype(...)
3482
269k
  DeclSpec DS(AttrFactory);
3483
269k
  // : template_name<...>
3484
269k
  ParsedType TemplateTypeTy;
3485
269k
3486
269k
  if (Tok.is(tok::identifier)) {
3487
259k
    // Get the identifier. This may be a member name or a class name,
3488
259k
    // but we'll let the semantic analysis determine which it is.
3489
259k
    II = Tok.getIdentifierInfo();
3490
259k
    ConsumeToken();
3491
259k
  } else 
if (9.37k
Tok.is(tok::annot_decltype)9.37k
) {
3492
6
    // Get the decltype expression, if there is one.
3493
6
    // Uses of decltype will already have been converted to annot_decltype by
3494
6
    // ParseOptionalCXXScopeSpecifier at this point.
3495
6
    // FIXME: Can we get here with a scope specifier?
3496
6
    ParseDecltypeSpecifier(DS);
3497
9.37k
  } else {
3498
9.37k
    TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3499
9.37k
                                           ? 
takeTemplateIdAnnotation(Tok)9.34k
3500
9.37k
                                           : 
nullptr26
;
3501
9.37k
    if (TemplateId && 
(9.34k
TemplateId->Kind == TNK_Type_template9.34k
||
3502
9.34k
                       
TemplateId->Kind == TNK_Dependent_template_name12
||
3503
9.34k
                       
TemplateId->Kind == TNK_Undeclared_template2
)) {
3504
9.34k
      AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
3505
9.34k
      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
3506
9.34k
      TemplateTypeTy = getTypeAnnotation(Tok);
3507
9.34k
      ConsumeAnnotationToken();
3508
9.34k
      if (!TemplateTypeTy)
3509
5
        return true;
3510
27
    } else {
3511
27
      Diag(Tok, diag::err_expected_member_or_base_name);
3512
27
      return true;
3513
27
    }
3514
269k
  }
3515
269k
3516
269k
  // Parse the '('.
3517
269k
  if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)260k
) {
3518
3.27k
    Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3519
3.27k
3520
3.27k
    // FIXME: Add support for signature help inside initializer lists.
3521
3.27k
    ExprResult InitList = ParseBraceInitializer();
3522
3.27k
    if (InitList.isInvalid())
3523
0
      return true;
3524
3.27k
3525
3.27k
    SourceLocation EllipsisLoc;
3526
3.27k
    TryConsumeToken(tok::ellipsis, EllipsisLoc);
3527
3.27k
3528
3.27k
    return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3529
3.27k
                                       TemplateTypeTy, DS, IdLoc,
3530
3.27k
                                       InitList.get(), EllipsisLoc);
3531
266k
  } else if(Tok.is(tok::l_paren)) {
3532
266k
    BalancedDelimiterTracker T(*this, tok::l_paren);
3533
266k
    T.consumeOpen();
3534
266k
3535
266k
    // Parse the optional expression-list.
3536
266k
    ExprVector ArgExprs;
3537
266k
    CommaLocsTy CommaLocs;
3538
266k
    auto RunSignatureHelp = [&] {
3539
2
      QualType PreferredType = Actions.ProduceCtorInitMemberSignatureHelp(
3540
2
          getCurScope(), ConstructorDecl, SS, TemplateTypeTy, ArgExprs, II,
3541
2
          T.getOpenLocation());
3542
2
      CalledSignatureHelp = true;
3543
2
      return PreferredType;
3544
2
    };
3545
266k
    if (Tok.isNot(tok::r_paren) &&
3546
304k
        
ParseExpressionList(ArgExprs, CommaLocs, [&] 255k
{
3547
304k
          PreferredType.enterFunctionArgument(Tok.getLocation(),
3548
304k
                                              RunSignatureHelp);
3549
304k
        })) {
3550
33
      if (PP.isCodeCompletionReached() && 
!CalledSignatureHelp6
)
3551
0
        RunSignatureHelp();
3552
33
      SkipUntil(tok::r_paren, StopAtSemi);
3553
33
      return true;
3554
33
    }
3555
265k
3556
265k
    T.consumeClose();
3557
265k
3558
265k
    SourceLocation EllipsisLoc;
3559
265k
    TryConsumeToken(tok::ellipsis, EllipsisLoc);
3560
265k
3561
265k
    return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3562
265k
                                       TemplateTypeTy, DS, IdLoc,
3563
265k
                                       T.getOpenLocation(), ArgExprs,
3564
265k
                                       T.getCloseLocation(), EllipsisLoc);
3565
265k
  }
3566
0
3567
0
  if (getLangOpts().CPlusPlus11)
3568
0
    return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3569
0
  else
3570
0
    return Diag(Tok, diag::err_expected) << tok::l_paren;
3571
0
}
3572
3573
/// Parse a C++ exception-specification if present (C++0x [except.spec]).
3574
///
3575
///       exception-specification:
3576
///         dynamic-exception-specification
3577
///         noexcept-specification
3578
///
3579
///       noexcept-specification:
3580
///         'noexcept'
3581
///         'noexcept' '(' constant-expression ')'
3582
ExceptionSpecificationType
3583
Parser::tryParseExceptionSpecification(bool Delayed,
3584
                    SourceRange &SpecificationRange,
3585
                    SmallVectorImpl<ParsedType> &DynamicExceptions,
3586
                    SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
3587
                    ExprResult &NoexceptExpr,
3588
4.08M
                    CachedTokens *&ExceptionSpecTokens) {
3589
4.08M
  ExceptionSpecificationType Result = EST_None;
3590
4.08M
  ExceptionSpecTokens = nullptr;
3591
4.08M
3592
4.08M
  // Handle delayed parsing of exception-specifications.
3593
4.08M
  if (Delayed) {
3594
1.63M
    if (Tok.isNot(tok::kw_throw) && 
Tok.isNot(tok::kw_noexcept)1.62M
)
3595
1.26M
      return EST_None;
3596
372k
3597
372k
    // Consume and cache the starting token.
3598
372k
    bool IsNoexcept = Tok.is(tok::kw_noexcept);
3599
372k
    Token StartTok = Tok;
3600
372k
    SpecificationRange = SourceRange(ConsumeToken());
3601
372k
3602
372k
    // Check for a '('.
3603
372k
    if (!Tok.is(tok::l_paren)) {
3604
323k
      // If this is a bare 'noexcept', we're done.
3605
323k
      if (IsNoexcept) {
3606
323k
        Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3607
323k
        NoexceptExpr = nullptr;
3608
323k
        return EST_BasicNoexcept;
3609
323k
      }
3610
0
3611
0
      Diag(Tok, diag::err_expected_lparen_after) << "throw";
3612
0
      return EST_DynamicNone;
3613
0
    }
3614
48.2k
3615
48.2k
    // Cache the tokens for the exception-specification.
3616
48.2k
    ExceptionSpecTokens = new CachedTokens;
3617
48.2k
    ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3618
48.2k
    ExceptionSpecTokens->push_back(Tok); // '('
3619
48.2k
    SpecificationRange.setEnd(ConsumeParen()); // '('
3620
48.2k
3621
48.2k
    ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3622
48.2k
                         /*StopAtSemi=*/true,
3623
48.2k
                         /*ConsumeFinalToken=*/true);
3624
48.2k
    SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3625
48.2k
3626
48.2k
    return EST_Unparsed;
3627
48.2k
  }
3628
2.45M
3629
2.45M
  // See if there's a dynamic specification.
3630
2.45M
  if (Tok.is(tok::kw_throw)) {
3631
49.3k
    Result = ParseDynamicExceptionSpecification(SpecificationRange,
3632
49.3k
                                                DynamicExceptions,
3633
49.3k
                                                DynamicExceptionRanges);
3634
49.3k
    assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3635
49.3k
           "Produced different number of exception types and ranges.");
3636
49.3k
  }
3637
2.45M
3638
2.45M
  // If there's no noexcept specification, we're done.
3639
2.45M
  if (Tok.isNot(tok::kw_noexcept))
3640
2.10M
    return Result;
3641
341k
3642
341k
  Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3643
341k
3644
341k
  // If we already had a dynamic specification, parse the noexcept for,
3645
341k
  // recovery, but emit a diagnostic and don't store the results.
3646
341k
  SourceRange NoexceptRange;
3647
341k
  ExceptionSpecificationType NoexceptType = EST_None;
3648
341k
3649
341k
  SourceLocation KeywordLoc = ConsumeToken();
3650
341k
  if (Tok.is(tok::l_paren)) {
3651
52.2k
    // There is an argument.
3652
52.2k
    BalancedDelimiterTracker T(*this, tok::l_paren);
3653
52.2k
    T.consumeOpen();
3654
52.2k
    NoexceptExpr = ParseConstantExpression();
3655
52.2k
    T.consumeClose();
3656
52.2k
    if (!NoexceptExpr.isInvalid()) {
3657
52.2k
      NoexceptExpr = Actions.ActOnNoexceptSpec(KeywordLoc, NoexceptExpr.get(),
3658
52.2k
                                               NoexceptType);
3659
52.2k
      NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3660
52.2k
    } else {
3661
14
      NoexceptType = EST_BasicNoexcept;
3662
14
    }
3663
289k
  } else {
3664
289k
    // There is no argument.
3665
289k
    NoexceptType = EST_BasicNoexcept;
3666
289k
    NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3667
289k
  }
3668
341k
3669
341k
  if (Result == EST_None) {
3670
341k
    SpecificationRange = NoexceptRange;
3671
341k
    Result = NoexceptType;
3672
341k
3673
341k
    // If there's a dynamic specification after a noexcept specification,
3674
341k
    // parse that and ignore the results.
3675
341k
    if (Tok.is(tok::kw_throw)) {
3676
1
      Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3677
1
      ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3678
1
                                         DynamicExceptionRanges);
3679
1
    }
3680
341k
  } else {
3681
1
    Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3682
1
  }
3683
341k
3684
341k
  return Result;
3685
341k
}
3686
3687
static void diagnoseDynamicExceptionSpecification(
3688
49.3k
    Parser &P, SourceRange Range, bool IsNoexcept) {
3689
49.3k
  if (P.getLangOpts().CPlusPlus11) {
3690
7.05k
    const char *Replacement = IsNoexcept ? 
"noexcept"6.54k
:
"noexcept(false)"505
;
3691
7.05k
    P.Diag(Range.getBegin(),
3692
7.05k
           P.getLangOpts().CPlusPlus17 && 
!IsNoexcept239
3693
7.05k
               ? 
diag::ext_dynamic_exception_spec43
3694
7.05k
               : 
diag::warn_exception_spec_deprecated7.00k
)
3695
7.05k
        << Range;
3696
7.05k
    P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3697
7.05k
      << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3698
7.05k
  }
3699
49.3k
}
3700
3701
/// ParseDynamicExceptionSpecification - Parse a C++
3702
/// dynamic-exception-specification (C++ [except.spec]).
3703
///
3704
///       dynamic-exception-specification:
3705
///         'throw' '(' type-id-list [opt] ')'
3706
/// [MS]    'throw' '(' '...' ')'
3707
///
3708
///       type-id-list:
3709
///         type-id ... [opt]
3710
///         type-id-list ',' type-id ... [opt]
3711
///
3712
ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3713
                                  SourceRange &SpecificationRange,
3714
                                  SmallVectorImpl<ParsedType> &Exceptions,
3715
49.3k
                                  SmallVectorImpl<SourceRange> &Ranges) {
3716
49.3k
  assert(Tok.is(tok::kw_throw) && "expected throw");
3717
49.3k
3718
49.3k
  SpecificationRange.setBegin(ConsumeToken());
3719
49.3k
  BalancedDelimiterTracker T(*this, tok::l_paren);
3720
49.3k
  if (T.consumeOpen()) {
3721
0
    Diag(Tok, diag::err_expected_lparen_after) << "throw";
3722
0
    SpecificationRange.setEnd(SpecificationRange.getBegin());
3723
0
    return EST_DynamicNone;
3724
0
  }
3725
49.3k
3726
49.3k
  // Parse throw(...), a Microsoft extension that means "this function
3727
49.3k
  // can throw anything".
3728
49.3k
  if (Tok.is(tok::ellipsis)) {
3729
52
    SourceLocation EllipsisLoc = ConsumeToken();
3730
52
    if (!getLangOpts().MicrosoftExt)
3731
37
      Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3732
52
    T.consumeClose();
3733
52
    SpecificationRange.setEnd(T.getCloseLocation());
3734
52
    diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3735
52
    return EST_MSAny;
3736
52
  }
3737
49.2k
3738
49.2k
  // Parse the sequence of type-ids.
3739
49.2k
  SourceRange Range;
3740
49.3k
  while (Tok.isNot(tok::r_paren)) {
3741
947
    TypeResult Res(ParseTypeName(&Range));
3742
947
3743
947
    if (Tok.is(tok::ellipsis)) {
3744
13
      // C++0x [temp.variadic]p5:
3745
13
      //   - In a dynamic-exception-specification (15.4); the pattern is a
3746
13
      //     type-id.
3747
13
      SourceLocation Ellipsis = ConsumeToken();
3748
13
      Range.setEnd(Ellipsis);
3749
13
      if (!Res.isInvalid())
3750
13
        Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3751
13
    }
3752
947
3753
947
    if (!Res.isInvalid()) {
3754
939
      Exceptions.push_back(Res.get());
3755
939
      Ranges.push_back(Range);
3756
939
    }
3757
947
3758
947
    if (!TryConsumeToken(tok::comma))
3759
869
      break;
3760
947
  }
3761
49.2k
3762
49.2k
  T.consumeClose();
3763
49.2k
  SpecificationRange.setEnd(T.getCloseLocation());
3764
49.2k
  diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3765
49.2k
                                        Exceptions.empty());
3766
49.2k
  return Exceptions.empty() ? 
EST_DynamicNone48.3k
:
EST_Dynamic861
;
3767
49.2k
}
3768
3769
/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3770
/// function declaration.
3771
TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
3772
23.7k
                                           bool MayBeFollowedByDirectInit) {
3773
23.7k
  assert(Tok.is(tok::arrow) && "expected arrow");
3774
23.7k
3775
23.7k
  ConsumeToken();
3776
23.7k
3777
23.7k
  return ParseTypeName(&Range, MayBeFollowedByDirectInit
3778
23.7k
                                   ? 
DeclaratorContext::TrailingReturnVarContext15.2k
3779
23.7k
                                   : 
DeclaratorContext::TrailingReturnContext8.46k
);
3780
23.7k
}
3781
3782
/// We have just started parsing the definition of a new class,
3783
/// so push that class onto our stack of classes that is currently
3784
/// being parsed.
3785
Sema::ParsingClassState
3786
Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3787
844k
                         bool IsInterface) {
3788
844k
  assert((NonNestedClass || !ClassStack.empty()) &&
3789
844k
         "Nested class without outer class");
3790
844k
  ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
3791
844k
  return Actions.PushParsingClass();
3792
844k
}
3793
3794
/// Deallocate the given parsed class and all of its nested
3795
/// classes.
3796
844k
void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
3797
2.05M
  for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; 
++I1.20M
)
3798
1.20M
    delete Class->LateParsedDeclarations[I];
3799
844k
  delete Class;
3800
844k
}
3801
3802
/// Pop the top class of the stack of classes that are
3803
/// currently being parsed.
3804
///
3805
/// This routine should be called when we have finished parsing the
3806
/// definition of a class, but have not yet popped the Scope
3807
/// associated with the class's definition.
3808
844k
void Parser::PopParsingClass(Sema::ParsingClassState state) {
3809
844k
  assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3810
844k
3811
844k
  Actions.PopParsingClass(state);
3812
844k
3813
844k
  ParsingClass *Victim = ClassStack.top();
3814
844k
  ClassStack.pop();
3815
844k
  if (Victim->TopLevelClass) {
3816
785k
    // Deallocate all of the nested classes of this class,
3817
785k
    // recursively: we don't need to keep any of this information.
3818
785k
    DeallocateParsedClasses(Victim);
3819
785k
    return;
3820
785k
  }
3821
58.4k
  assert(!ClassStack.empty() && "Missing top-level class?");
3822
58.4k
3823
58.4k
  if (Victim->LateParsedDeclarations.empty()) {
3824
45.6k
    // The victim is a nested class, but we will not need to perform
3825
45.6k
    // any processing after the definition of this class since it has
3826
45.6k
    // no members whose handling was delayed. Therefore, we can just
3827
45.6k
    // remove this nested class.
3828
45.6k
    DeallocateParsedClasses(Victim);
3829
45.6k
    return;
3830
45.6k
  }
3831
12.8k
3832
12.8k
  // This nested class has some members that will need to be processed
3833
12.8k
  // after the top-level class is completely defined. Therefore, add
3834
12.8k
  // it to the list of nested classes within its parent.
3835
12.8k
  assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3836
12.8k
  ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3837
12.8k
  Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3838
12.8k
}
3839
3840
/// Try to parse an 'identifier' which appears within an attribute-token.
3841
///
3842
/// \return the parsed identifier on success, and 0 if the next token is not an
3843
/// attribute-token.
3844
///
3845
/// C++11 [dcl.attr.grammar]p3:
3846
///   If a keyword or an alternative token that satisfies the syntactic
3847
///   requirements of an identifier is contained in an attribute-token,
3848
///   it is considered an identifier.
3849
11.1k
IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3850
11.1k
  switch (Tok.getKind()) {
3851
11.1k
  default:
3852
11.1k
    // Identifiers and keywords have identifier info attached.
3853
11.1k
    if (!Tok.isAnnotation()) {
3854
11.1k
      if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3855
11.1k
        Loc = ConsumeToken();
3856
11.1k
        return II;
3857
11.1k
      }
3858
17
    }
3859
17
    return nullptr;
3860
17
3861
17
  case tok::numeric_constant: {
3862
7
    // If we got a numeric constant, check to see if it comes from a macro that
3863
7
    // corresponds to the predefined __clang__ macro. If it does, warn the user
3864
7
    // and recover by pretending they said _Clang instead.
3865
7
    if (Tok.getLocation().isMacroID()) {
3866
5
      SmallString<8> ExpansionBuf;
3867
5
      SourceLocation ExpansionLoc =
3868
5
          PP.getSourceManager().getExpansionLoc(Tok.getLocation());
3869
5
      StringRef Spelling = PP.getSpelling(ExpansionLoc, ExpansionBuf);
3870
5
      if (Spelling == "__clang__") {
3871
5
        SourceRange TokRange(
3872
5
            ExpansionLoc,
3873
5
            PP.getSourceManager().getExpansionLoc(Tok.getEndLoc()));
3874
5
        Diag(Tok, diag::warn_wrong_clang_attr_namespace)
3875
5
            << FixItHint::CreateReplacement(TokRange, "_Clang");
3876
5
        Loc = ConsumeToken();
3877
5
        return &PP.getIdentifierTable().get("_Clang");
3878
5
      }
3879
2
    }
3880
2
    return nullptr;
3881
2
  }
3882
2
3883
8
  case tok::ampamp:       // 'and'
3884
8
  case tok::pipe:         // 'bitor'
3885
8
  case tok::pipepipe:     // 'or'
3886
8
  case tok::caret:        // 'xor'
3887
8
  case tok::tilde:        // 'compl'
3888
8
  case tok::amp:          // 'bitand'
3889
8
  case tok::ampequal:     // 'and_eq'
3890
8
  case tok::pipeequal:    // 'or_eq'
3891
8
  case tok::caretequal:   // 'xor_eq'
3892
8
  case tok::exclaim:      // 'not'
3893
8
  case tok::exclaimequal: // 'not_eq'
3894
8
    // Alternative tokens do not have identifier info, but their spelling
3895
8
    // starts with an alphabetical character.
3896
8
    SmallString<8> SpellingBuf;
3897
8
    SourceLocation SpellingLoc =
3898
8
        PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3899
8
    StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
3900
8
    if (isLetter(Spelling[0])) {
3901
7
      Loc = ConsumeToken();
3902
7
      return &PP.getIdentifierTable().get(Spelling);
3903
7
    }
3904
1
    return nullptr;
3905
11.1k
  }
3906
11.1k
}
3907
3908
static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3909
9.77k
                                              IdentifierInfo *ScopeName) {
3910
9.77k
  switch (ParsedAttr::getKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) {
3911
9.77k
  case ParsedAttr::AT_CarriesDependency:
3912
8.92k
  case ParsedAttr::AT_Deprecated:
3913
8.92k
  case ParsedAttr::AT_FallThrough:
3914
8.92k
  case ParsedAttr::AT_CXX11NoReturn:
3915
8.92k
  case ParsedAttr::AT_NoUniqueAddress:
3916
8.92k
    return true;
3917
8.92k
  case ParsedAttr::AT_WarnUnusedResult:
3918
78
    return !ScopeName && 
AttrName->getName().equals("nodiscard")69
;
3919
8.92k
  case ParsedAttr::AT_Unused:
3920
51
    return !ScopeName && 
AttrName->getName().equals("maybe_unused")42
;
3921
8.92k
  default:
3922
721
    return false;
3923
9.77k
  }
3924
9.77k
}
3925
3926
/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3927
///
3928
/// [C++11] attribute-argument-clause:
3929
///         '(' balanced-token-seq ')'
3930
///
3931
/// [C++11] balanced-token-seq:
3932
///         balanced-token
3933
///         balanced-token-seq balanced-token
3934
///
3935
/// [C++11] balanced-token:
3936
///         '(' balanced-token-seq ')'
3937
///         '[' balanced-token-seq ']'
3938
///         '{' balanced-token-seq '}'
3939
///         any token but '(', ')', '[', ']', '{', or '}'
3940
bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3941
                                     SourceLocation AttrNameLoc,
3942
                                     ParsedAttributes &Attrs,
3943
                                     SourceLocation *EndLoc,
3944
                                     IdentifierInfo *ScopeName,
3945
180
                                     SourceLocation ScopeLoc) {
3946
180
  assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
3947
180
  SourceLocation LParenLoc = Tok.getLocation();
3948
180
  const LangOptions &LO = getLangOpts();
3949
180
  ParsedAttr::Syntax Syntax =
3950
180
      LO.CPlusPlus ? 
ParsedAttr::AS_CXX11133
:
ParsedAttr::AS_C2x47
;
3951
180
3952
180
  // If the attribute isn't known, we will not attempt to parse any
3953
180
  // arguments.
3954
180
  if (!hasAttribute(LO.CPlusPlus ? 
AttrSyntax::CXX133
:
AttrSyntax::C47
, ScopeName,
3955
180
                    AttrName, getTargetInfo(), getLangOpts())) {
3956
11
    // Eat the left paren, then skip to the ending right paren.
3957
11
    ConsumeParen();
3958
11
    SkipUntil(tok::r_paren);
3959
11
    return false;
3960
11
  }
3961
169
3962
169
  if (ScopeName && 
(131
ScopeName->isStr("gnu")131
||
ScopeName->isStr("__gnu__")103
)) {
3963
28
    // GNU-scoped attributes have some special cases to handle GNU-specific
3964
28
    // behaviors.
3965
28
    ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3966
28
                          ScopeLoc, Syntax, nullptr);
3967
28
    return true;
3968
28
  }
3969
141
3970
141
  unsigned NumArgs;
3971
141
  // Some Clang-scoped attributes have some special parsing behavior.
3972
141
  if (ScopeName && 
(103
ScopeName->isStr("clang")103
||
ScopeName->isStr("_Clang")19
))
3973
90
    NumArgs = ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc,
3974
90
                                      ScopeName, ScopeLoc, Syntax);
3975
51
  else
3976
51
    NumArgs =
3977
51
        ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3978
51
                                 ScopeName, ScopeLoc, Syntax);
3979
141
3980
141
  if (!Attrs.empty() &&
3981
141
      
IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)132
) {
3982
37
    ParsedAttr &Attr = Attrs.back();
3983
37
    // If the attribute is a standard or built-in attribute and we are
3984
37
    // parsing an argument list, we need to determine whether this attribute
3985
37
    // was allowed to have an argument list (such as [[deprecated]]), and how
3986
37
    // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3987
37
    if (Attr.getMaxArgs() && 
!NumArgs28
) {
3988
1
      // The attribute was allowed to have arguments, but none were provided
3989
1
      // even though the attribute parsed successfully. This is an error.
3990
1
      Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3991
1
      Attr.setInvalid(true);
3992
36
    } else if (!Attr.getMaxArgs()) {
3993
9
      // The attribute parsed successfully, but was not allowed to have any
3994
9
      // arguments. It doesn't matter whether any were provided -- the
3995
9
      // presence of the argument list (even if empty) is diagnosed.
3996
9
      Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3997
9
          << AttrName
3998
9
          << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3999
9
      Attr.setInvalid(true);
4000
9
    }
4001
37
  }
4002
141
  return true;
4003
141
}
4004
4005
/// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
4006
///
4007
/// [C++11] attribute-specifier:
4008
///         '[' '[' attribute-list ']' ']'
4009
///         alignment-specifier
4010
///
4011
/// [C++11] attribute-list:
4012
///         attribute[opt]
4013
///         attribute-list ',' attribute[opt]
4014
///         attribute '...'
4015
///         attribute-list ',' attribute '...'
4016
///
4017
/// [C++11] attribute:
4018
///         attribute-token attribute-argument-clause[opt]
4019
///
4020
/// [C++11] attribute-token:
4021
///         identifier
4022
///         attribute-scoped-token
4023
///
4024
/// [C++11] attribute-scoped-token:
4025
///         attribute-namespace '::' identifier
4026
///
4027
/// [C++11] attribute-namespace:
4028
///         identifier
4029
void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
4030
20.9k
                                          SourceLocation *endLoc) {
4031
20.9k
  if (Tok.is(tok::kw_alignas)) {
4032
10.8k
    Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
4033
10.8k
    ParseAlignmentSpecifier(attrs, endLoc);
4034
10.8k
    return;
4035
10.8k
  }
4036
10.0k
4037
10.0k
  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
4038
10.0k
         "Not a double square bracket attribute list");
4039
10.0k
4040
10.0k
  Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
4041
10.0k
4042
10.0k
  ConsumeBracket();
4043
10.0k
  ConsumeBracket();
4044
10.0k
4045
10.0k
  SourceLocation CommonScopeLoc;
4046
10.0k
  IdentifierInfo *CommonScopeName = nullptr;
4047
10.0k
  if (Tok.is(tok::kw_using)) {
4048
9
    Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4049
9
                                ? diag::warn_cxx14_compat_using_attribute_ns
4050
9
                                : 
diag::ext_using_attribute_ns0
);
4051
9
    ConsumeToken();
4052
9
4053
9
    CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
4054
9
    if (!CommonScopeName) {
4055
2
      Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4056
2
      SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
4057
2
    }
4058
9
    if (!TryConsumeToken(tok::colon) && 
CommonScopeName2
)
4059
1
      Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
4060
9
  }
4061
10.0k
4062
10.0k
  llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
4063
10.0k
4064
19.7k
  while (Tok.isNot(tok::r_square)) {
4065
9.69k
    // attribute not present
4066
9.69k
    if (TryConsumeToken(tok::comma))
4067
42
      continue;
4068
9.65k
4069
9.65k
    SourceLocation ScopeLoc, AttrLoc;
4070
9.65k
    IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
4071
9.65k
4072
9.65k
    AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4073
9.65k
    if (!AttrName)
4074
6
      // Break out to the "expected ']'" diagnostic.
4075
6
      break;
4076
9.64k
4077
9.64k
    // scoped attribute
4078
9.64k
    if (TryConsumeToken(tok::coloncolon)) {
4079
1.42k
      ScopeName = AttrName;
4080
1.42k
      ScopeLoc = AttrLoc;
4081
1.42k
4082
1.42k
      AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4083
1.42k
      if (!AttrName) {
4084
1
        Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4085
1
        SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
4086
1
        continue;
4087
1
      }
4088
9.64k
    }
4089
9.64k
4090
9.64k
    if (CommonScopeName) {
4091
6
      if (ScopeName) {
4092
1
        Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4093
1
            << SourceRange(CommonScopeLoc);
4094
5
      } else {
4095
5
        ScopeName = CommonScopeName;
4096
5
        ScopeLoc = CommonScopeLoc;
4097
5
      }
4098
6
    }
4099
9.64k
4100
9.64k
    bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
4101
9.64k
    bool AttrParsed = false;
4102
9.64k
4103
9.64k
    if (StandardAttr &&
4104
9.64k
        
!SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second9.00k
)
4105
10
      Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
4106
10
          << AttrName << SourceRange(SeenAttrs[AttrName]);
4107
9.64k
4108
9.64k
    // Parse attribute arguments
4109
9.64k
    if (Tok.is(tok::l_paren))
4110
180
      AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4111
180
                                           ScopeName, ScopeLoc);
4112
9.64k
4113
9.64k
    if (!AttrParsed)
4114
9.47k
      attrs.addNew(
4115
9.47k
          AttrName,
4116
9.47k
          SourceRange(ScopeLoc.isValid() ? 
ScopeLoc1.29k
:
AttrLoc8.18k
, AttrLoc),
4117
9.47k
          ScopeName, ScopeLoc, nullptr, 0,
4118
9.47k
          getLangOpts().CPlusPlus ? 
ParsedAttr::AS_CXX119.37k
:
ParsedAttr::AS_C2x101
);
4119
9.64k
4120
9.64k
    if (TryConsumeToken(tok::ellipsis))
4121
5
      Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
4122
5
        << AttrName;
4123
9.64k
  }
4124
10.0k
4125
10.0k
  if (ExpectAndConsume(tok::r_square))
4126
6
    SkipUntil(tok::r_square);
4127
10.0k
  if (endLoc)
4128
10.0k
    *endLoc = Tok.getLocation();
4129
10.0k
  if (ExpectAndConsume(tok::r_square))
4130
5
    SkipUntil(tok::r_square);
4131
10.0k
}
4132
4133
/// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
4134
///
4135
/// attribute-specifier-seq:
4136
///       attribute-specifier-seq[opt] attribute-specifier
4137
void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
4138
20.7k
                                  SourceLocation *endLoc) {
4139
20.7k
  assert(standardAttributesAllowed());
4140
20.7k
4141
20.7k
  SourceLocation StartLoc = Tok.getLocation(), Loc;
4142
20.7k
  if (!endLoc)
4143
20.5k
    endLoc = &Loc;
4144
20.7k
4145
20.9k
  do {
4146
20.9k
    ParseCXX11AttributeSpecifier(attrs, endLoc);
4147
20.9k
  } while (isCXX11AttributeSpecifier());
4148
20.7k
4149
20.7k
  attrs.Range = SourceRange(StartLoc, *endLoc);
4150
20.7k
}
4151
4152
143k
void Parser::DiagnoseAndSkipCXX11Attributes() {
4153
143k
  // Start and end location of an attribute or an attribute list.
4154
143k
  SourceLocation StartLoc = Tok.getLocation();
4155
143k
  SourceLocation EndLoc = SkipCXX11Attributes();
4156
143k
4157
143k
  if (EndLoc.isValid()) {
4158
3
    SourceRange Range(StartLoc, EndLoc);
4159
3
    Diag(StartLoc, diag::err_attributes_not_allowed)
4160
3
      << Range;
4161
3
  }
4162
143k
}
4163
4164
602k
SourceLocation Parser::SkipCXX11Attributes() {
4165
602k
  SourceLocation EndLoc;
4166
602k
4167
602k
  if (!isCXX11AttributeSpecifier())
4168
602k
    return EndLoc;
4169
13
4170
13
  do {
4171
13
    if (Tok.is(tok::l_square)) {
4172
10
      BalancedDelimiterTracker T(*this, tok::l_square);
4173
10
      T.consumeOpen();
4174
10
      T.skipToEnd();
4175
10
      EndLoc = T.getCloseLocation();
4176
10
    } else {
4177
3
      assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4178
3
      ConsumeToken();
4179
3
      BalancedDelimiterTracker T(*this, tok::l_paren);
4180
3
      if (!T.consumeOpen())
4181
3
        T.skipToEnd();
4182
3
      EndLoc = T.getCloseLocation();
4183
3
    }
4184
13
  } while (isCXX11AttributeSpecifier());
4185
13
4186
13
  return EndLoc;
4187
13
}
4188
4189
/// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4190
61
void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4191
61
  assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4192
61
  IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4193
61
  assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4194
61
4195
61
  SourceLocation UuidLoc = Tok.getLocation();
4196
61
  ConsumeToken();
4197
61
4198
61
  // Ignore the left paren location for now.
4199
61
  BalancedDelimiterTracker T(*this, tok::l_paren);
4200
61
  if (T.consumeOpen()) {
4201
1
    Diag(Tok, diag::err_expected) << tok::l_paren;
4202
1
    return;
4203
1
  }
4204
60
4205
60
  ArgsVector ArgExprs;
4206
60
  if (Tok.is(tok::string_literal)) {
4207
35
    // Easy case: uuid("...") -- quoted string.
4208
35
    ExprResult StringResult = ParseStringLiteralExpression();
4209
35
    if (StringResult.isInvalid())
4210
0
      return;
4211
35
    ArgExprs.push_back(StringResult.get());
4212
35
  } else {
4213
25
    // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4214
25
    // quotes in the parens. Just append the spelling of all tokens encountered
4215
25
    // until the closing paren.
4216
25
4217
25
    SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4218
25
    StrBuffer += "\"";
4219
25
4220
25
    // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4221
25
    // tok::r_brace, tok::minus, tok::identifier (think C000) and
4222
25
    // tok::numeric_constant (0000) should be enough. But the spelling of the
4223
25
    // uuid argument is checked later anyways, so there's no harm in accepting
4224
25
    // almost anything here.
4225
25
    // cl is very strict about whitespace in this form and errors out if any
4226
25
    // is present, so check the space flags on the tokens.
4227
25
    SourceLocation StartLoc = Tok.getLocation();
4228
218
    while (Tok.isNot(tok::r_paren)) {
4229
197
      if (Tok.hasLeadingSpace() || 
Tok.isAtStartOfLine()194
) {
4230
4
        Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4231
4
        SkipUntil(tok::r_paren, StopAtSemi);
4232
4
        return;
4233
4
      }
4234
193
      SmallString<16> SpellingBuffer;
4235
193
      SpellingBuffer.resize(Tok.getLength() + 1);
4236
193
      bool Invalid = false;
4237
193
      StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4238
193
      if (Invalid) {
4239
0
        SkipUntil(tok::r_paren, StopAtSemi);
4240
0
        return;
4241
0
      }
4242
193
      StrBuffer += TokSpelling;
4243
193
      ConsumeAnyToken();
4244
193
    }
4245
25
    StrBuffer += "\"";
4246
21
4247
21
    if (Tok.hasLeadingSpace() || 
Tok.isAtStartOfLine()20
) {
4248
2
      Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4249
2
      ConsumeParen();
4250
2
      return;
4251
2
    }
4252
19
4253
19
    // Pretend the user wrote the appropriate string literal here.
4254
19
    // ActOnStringLiteral() copies the string data into the literal, so it's
4255
19
    // ok that the Token points to StrBuffer.
4256
19
    Token Toks[1];
4257
19
    Toks[0].startToken();
4258
19
    Toks[0].setKind(tok::string_literal);
4259
19
    Toks[0].setLocation(StartLoc);
4260
19
    Toks[0].setLiteralData(StrBuffer.data());
4261
19
    Toks[0].setLength(StrBuffer.size());
4262
19
    StringLiteral *UuidString =
4263
19
        cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4264
19
    ArgExprs.push_back(UuidString);
4265
19
  }
4266
60
4267
60
  
if (54
!T.consumeClose()54
) {
4268
52
    Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4269
52
                 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
4270
52
                 ParsedAttr::AS_Microsoft);
4271
52
  }
4272
54
}
4273
4274
/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
4275
///
4276
/// [MS] ms-attribute:
4277
///             '[' token-seq ']'
4278
///
4279
/// [MS] ms-attribute-seq:
4280
///             ms-attribute[opt]
4281
///             ms-attribute ms-attribute-seq
4282
void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4283
75
                                      SourceLocation *endLoc) {
4284
75
  assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4285
75
4286
76
  do {
4287
76
    // FIXME: If this is actually a C++11 attribute, parse it as one.
4288
76
    BalancedDelimiterTracker T(*this, tok::l_square);
4289
76
    T.consumeOpen();
4290
76
4291
76
    // Skip most ms attributes except for a whitelist.
4292
161
    while (true) {
4293
161
      SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4294
161
      if (Tok.isNot(tok::identifier)) // ']', but also eof
4295
76
        break;
4296
85
      if (Tok.getIdentifierInfo()->getName() == "uuid")
4297
61
        ParseMicrosoftUuidAttributeArgs(attrs);
4298
24
      else
4299
24
        ConsumeToken();
4300
85
    }
4301
76
4302
76
    T.consumeClose();
4303
76
    if (endLoc)
4304
0
      *endLoc = T.getCloseLocation();
4305
76
  } while (Tok.is(tok::l_square));
4306
75
}
4307
4308
void Parser::ParseMicrosoftIfExistsClassDeclaration(
4309
    DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
4310
9
    AccessSpecifier &CurAS) {
4311
9
  IfExistsCondition Result;
4312
9
  if (ParseMicrosoftIfExistsCondition(Result))
4313
0
    return;
4314
9
4315
9
  BalancedDelimiterTracker Braces(*this, tok::l_brace);
4316
9
  if (Braces.consumeOpen()) {
4317
0
    Diag(Tok, diag::err_expected) << tok::l_brace;
4318
0
    return;
4319
0
  }
4320
9
4321
9
  switch (Result.Behavior) {
4322
9
  case IEB_Parse:
4323
5
    // Parse the declarations below.
4324
5
    break;
4325
9
4326
9
  case IEB_Dependent:
4327
1
    Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4328
1
      << Result.IsIfExists;
4329
1
    // Fall through to skip.
4330
1
    LLVM_FALLTHROUGH;
4331
1
4332
4
  case IEB_Skip:
4333
4
    Braces.skipToEnd();
4334
4
    return;
4335
5
  }
4336
5
4337
11
  
while (5
Tok.isNot(tok::r_brace) &&
!isEofOrEom()6
) {
4338
6
    // __if_exists, __if_not_exists can nest.
4339
6
    if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
4340
1
      ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType,
4341
1
                                             AccessAttrs, CurAS);
4342
1
      continue;
4343
1
    }
4344
5
4345
5
    // Check for extraneous top-level semicolon.
4346
5
    if (Tok.is(tok::semi)) {
4347
0
      ConsumeExtraSemi(InsideStruct, TagType);
4348
0
      continue;
4349
0
    }
4350
5
4351
5
    AccessSpecifier AS = getAccessSpecifierIfPresent();
4352
5
    if (AS != AS_none) {
4353
0
      // Current token is a C++ access specifier.
4354
0
      CurAS = AS;
4355
0
      SourceLocation ASLoc = Tok.getLocation();
4356
0
      ConsumeToken();
4357
0
      if (Tok.is(tok::colon))
4358
0
        Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
4359
0
                                     ParsedAttributesView{});
4360
0
      else
4361
0
        Diag(Tok, diag::err_expected) << tok::colon;
4362
0
      ConsumeToken();
4363
0
      continue;
4364
0
    }
4365
5
4366
5
    // Parse all the comma separated declarators.
4367
5
    ParseCXXClassMemberDeclaration(CurAS, AccessAttrs);
4368
5
  }
4369
5
4370
5
  Braces.consumeClose();
4371
5
}