Coverage Report

Created: 2022-07-16 07:03

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