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