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