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