Coverage Report

Created: 2022-01-18 06:27

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