Coverage Report

Created: 2020-09-22 08:39

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