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