Coverage Report

Created: 2020-02-15 09:57

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