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