Coverage Report

Created: 2021-09-21 08:58

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