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