1 //===--- ParseDeclCXX.cpp - C++ Declaration Parsing -----------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the C++ Declaration portions of the Parser interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/Basic/Attributes.h"
19 #include "clang/Basic/CharInfo.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Basic/OperatorKinds.h"
22 #include "clang/Parse/ParseDiagnostic.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/ParsedTemplate.h"
25 #include "clang/Sema/PrettyDeclStackTrace.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/SemaDiagnostic.h"
28 #include "llvm/ADT/SmallString.h"
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++ 7.3: basic.namespace]
36 /// named-namespace-definition
37 /// unnamed-namespace-definition
38 ///
39 /// unnamed-namespace-definition:
40 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
41 ///
42 /// named-namespace-definition:
43 /// original-namespace-definition
44 /// extension-namespace-definition
45 ///
46 /// original-namespace-definition:
47 /// 'inline'[opt] 'namespace' identifier attributes[opt]
48 /// '{' namespace-body '}'
49 ///
50 /// extension-namespace-definition:
51 /// 'inline'[opt] 'namespace' original-namespace-name
52 /// '{' namespace-body '}'
53 ///
54 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
55 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
56 ///
ParseNamespace(unsigned Context,SourceLocation & DeclEnd,SourceLocation InlineLoc)57 Decl *Parser::ParseNamespace(unsigned Context,
58 SourceLocation &DeclEnd,
59 SourceLocation InlineLoc) {
60 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
61 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
62 ObjCDeclContextSwitch ObjCDC(*this);
63
64 if (Tok.is(tok::code_completion)) {
65 Actions.CodeCompleteNamespaceDecl(getCurScope());
66 cutOffParsing();
67 return nullptr;
68 }
69
70 SourceLocation IdentLoc;
71 IdentifierInfo *Ident = nullptr;
72 std::vector<SourceLocation> ExtraIdentLoc;
73 std::vector<IdentifierInfo*> ExtraIdent;
74 std::vector<SourceLocation> ExtraNamespaceLoc;
75
76 Token attrTok;
77
78 if (Tok.is(tok::identifier)) {
79 Ident = Tok.getIdentifierInfo();
80 IdentLoc = ConsumeToken(); // eat the identifier.
81 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
82 ExtraNamespaceLoc.push_back(ConsumeToken());
83 ExtraIdent.push_back(Tok.getIdentifierInfo());
84 ExtraIdentLoc.push_back(ConsumeToken());
85 }
86 }
87
88 // Read label attributes, if present.
89 ParsedAttributes attrs(AttrFactory);
90 if (Tok.is(tok::kw___attribute)) {
91 attrTok = Tok;
92 ParseGNUAttributes(attrs);
93 }
94
95 if (Tok.is(tok::equal)) {
96 if (!Ident) {
97 Diag(Tok, diag::err_expected) << tok::identifier;
98 // Skip to end of the definition and eat the ';'.
99 SkipUntil(tok::semi);
100 return nullptr;
101 }
102 if (!attrs.empty())
103 Diag(attrTok, diag::err_unexpected_namespace_attributes_alias);
104 if (InlineLoc.isValid())
105 Diag(InlineLoc, diag::err_inline_namespace_alias)
106 << FixItHint::CreateRemoval(InlineLoc);
107 return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
108 }
109
110
111 BalancedDelimiterTracker T(*this, tok::l_brace);
112 if (T.consumeOpen()) {
113 if (!ExtraIdent.empty()) {
114 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
115 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
116 }
117
118 if (Ident)
119 Diag(Tok, diag::err_expected) << tok::l_brace;
120 else
121 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
122
123 return nullptr;
124 }
125
126 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
127 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
128 getCurScope()->getFnParent()) {
129 if (!ExtraIdent.empty()) {
130 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
131 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
132 }
133 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
134 SkipUntil(tok::r_brace);
135 return nullptr;
136 }
137
138 if (!ExtraIdent.empty()) {
139 TentativeParsingAction TPA(*this);
140 SkipUntil(tok::r_brace, StopBeforeMatch);
141 Token rBraceToken = Tok;
142 TPA.Revert();
143
144 if (!rBraceToken.is(tok::r_brace)) {
145 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
146 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
147 } else {
148 std::string NamespaceFix;
149 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
150 E = ExtraIdent.end(); I != E; ++I) {
151 NamespaceFix += " { namespace ";
152 NamespaceFix += (*I)->getName();
153 }
154
155 std::string RBraces;
156 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
157 RBraces += "} ";
158
159 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
160 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
161 ExtraIdentLoc.back()),
162 NamespaceFix)
163 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
164 }
165 }
166
167 // If we're still good, complain about inline namespaces in non-C++0x now.
168 if (InlineLoc.isValid())
169 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
170 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
171
172 // Enter a scope for the namespace.
173 ParseScope NamespaceScope(this, Scope::DeclScope);
174
175 Decl *NamespcDecl =
176 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
177 IdentLoc, Ident, T.getOpenLocation(),
178 attrs.getList());
179
180 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
181 "parsing namespace");
182
183 // Parse the contents of the namespace. This includes parsing recovery on
184 // any improperly nested namespaces.
185 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
186 InlineLoc, attrs, T);
187
188 // Leave the namespace scope.
189 NamespaceScope.Exit();
190
191 DeclEnd = T.getCloseLocation();
192 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
193
194 return NamespcDecl;
195 }
196
197 /// ParseInnerNamespace - Parse the contents of a namespace.
ParseInnerNamespace(std::vector<SourceLocation> & IdentLoc,std::vector<IdentifierInfo * > & Ident,std::vector<SourceLocation> & NamespaceLoc,unsigned int index,SourceLocation & InlineLoc,ParsedAttributes & attrs,BalancedDelimiterTracker & Tracker)198 void Parser::ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
199 std::vector<IdentifierInfo*>& Ident,
200 std::vector<SourceLocation>& NamespaceLoc,
201 unsigned int index, SourceLocation& InlineLoc,
202 ParsedAttributes& attrs,
203 BalancedDelimiterTracker &Tracker) {
204 if (index == Ident.size()) {
205 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
206 ParsedAttributesWithRange attrs(AttrFactory);
207 MaybeParseCXX11Attributes(attrs);
208 MaybeParseMicrosoftAttributes(attrs);
209 ParseExternalDeclaration(attrs);
210 }
211
212 // The caller is what called check -- we are simply calling
213 // the close for it.
214 Tracker.consumeClose();
215
216 return;
217 }
218
219 // Parse improperly nested namespaces.
220 ParseScope NamespaceScope(this, Scope::DeclScope);
221 Decl *NamespcDecl =
222 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
223 NamespaceLoc[index], IdentLoc[index],
224 Ident[index], Tracker.getOpenLocation(),
225 attrs.getList());
226
227 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
228 attrs, Tracker);
229
230 NamespaceScope.Exit();
231
232 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
233 }
234
235 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
236 /// alias definition.
237 ///
ParseNamespaceAlias(SourceLocation NamespaceLoc,SourceLocation AliasLoc,IdentifierInfo * Alias,SourceLocation & DeclEnd)238 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
239 SourceLocation AliasLoc,
240 IdentifierInfo *Alias,
241 SourceLocation &DeclEnd) {
242 assert(Tok.is(tok::equal) && "Not equal token");
243
244 ConsumeToken(); // eat the '='.
245
246 if (Tok.is(tok::code_completion)) {
247 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
248 cutOffParsing();
249 return nullptr;
250 }
251
252 CXXScopeSpec SS;
253 // Parse (optional) nested-name-specifier.
254 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
255
256 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
257 Diag(Tok, diag::err_expected_namespace_name);
258 // Skip to end of the definition and eat the ';'.
259 SkipUntil(tok::semi);
260 return nullptr;
261 }
262
263 // Parse identifier.
264 IdentifierInfo *Ident = Tok.getIdentifierInfo();
265 SourceLocation IdentLoc = ConsumeToken();
266
267 // Eat the ';'.
268 DeclEnd = Tok.getLocation();
269 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
270 SkipUntil(tok::semi);
271
272 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias,
273 SS, IdentLoc, Ident);
274 }
275
276 /// ParseLinkage - We know that the current token is a string_literal
277 /// and just before that, that extern was seen.
278 ///
279 /// linkage-specification: [C++ 7.5p2: dcl.link]
280 /// 'extern' string-literal '{' declaration-seq[opt] '}'
281 /// 'extern' string-literal declaration
282 ///
ParseLinkage(ParsingDeclSpec & DS,unsigned Context)283 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
284 assert(isTokenStringLiteral() && "Not a string literal!");
285 ExprResult Lang = ParseStringLiteralExpression(false);
286
287 ParseScope LinkageScope(this, Scope::DeclScope);
288 Decl *LinkageSpec =
289 Lang.isInvalid()
290 ? nullptr
291 : Actions.ActOnStartLinkageSpecification(
292 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
293 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
294
295 ParsedAttributesWithRange attrs(AttrFactory);
296 MaybeParseCXX11Attributes(attrs);
297 MaybeParseMicrosoftAttributes(attrs);
298
299 if (Tok.isNot(tok::l_brace)) {
300 // Reset the source range in DS, as the leading "extern"
301 // does not really belong to the inner declaration ...
302 DS.SetRangeStart(SourceLocation());
303 DS.SetRangeEnd(SourceLocation());
304 // ... but anyway remember that such an "extern" was seen.
305 DS.setExternInLinkageSpec(true);
306 ParseExternalDeclaration(attrs, &DS);
307 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
308 getCurScope(), LinkageSpec, SourceLocation())
309 : nullptr;
310 }
311
312 DS.abort();
313
314 ProhibitAttributes(attrs);
315
316 BalancedDelimiterTracker T(*this, tok::l_brace);
317 T.consumeOpen();
318
319 unsigned NestedModules = 0;
320 while (true) {
321 switch (Tok.getKind()) {
322 case tok::annot_module_begin:
323 ++NestedModules;
324 ParseTopLevelDecl();
325 continue;
326
327 case tok::annot_module_end:
328 if (!NestedModules)
329 break;
330 --NestedModules;
331 ParseTopLevelDecl();
332 continue;
333
334 case tok::annot_module_include:
335 ParseTopLevelDecl();
336 continue;
337
338 case tok::eof:
339 break;
340
341 case tok::r_brace:
342 if (!NestedModules)
343 break;
344 // Fall through.
345 default:
346 ParsedAttributesWithRange attrs(AttrFactory);
347 MaybeParseCXX11Attributes(attrs);
348 MaybeParseMicrosoftAttributes(attrs);
349 ParseExternalDeclaration(attrs);
350 continue;
351 }
352
353 break;
354 }
355
356 T.consumeClose();
357 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
358 getCurScope(), LinkageSpec, T.getCloseLocation())
359 : nullptr;
360 }
361
362 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
363 /// using-directive. Assumes that current token is 'using'.
ParseUsingDirectiveOrDeclaration(unsigned Context,const ParsedTemplateInfo & TemplateInfo,SourceLocation & DeclEnd,ParsedAttributesWithRange & attrs,Decl ** OwnedType)364 Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
365 const ParsedTemplateInfo &TemplateInfo,
366 SourceLocation &DeclEnd,
367 ParsedAttributesWithRange &attrs,
368 Decl **OwnedType) {
369 assert(Tok.is(tok::kw_using) && "Not using token");
370 ObjCDeclContextSwitch ObjCDC(*this);
371
372 // Eat 'using'.
373 SourceLocation UsingLoc = ConsumeToken();
374
375 if (Tok.is(tok::code_completion)) {
376 Actions.CodeCompleteUsing(getCurScope());
377 cutOffParsing();
378 return nullptr;
379 }
380
381 // 'using namespace' means this is a using-directive.
382 if (Tok.is(tok::kw_namespace)) {
383 // Template parameters are always an error here.
384 if (TemplateInfo.Kind) {
385 SourceRange R = TemplateInfo.getSourceRange();
386 Diag(UsingLoc, diag::err_templated_using_directive)
387 << R << FixItHint::CreateRemoval(R);
388 }
389
390 return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
391 }
392
393 // Otherwise, it must be a using-declaration or an alias-declaration.
394
395 // Using declarations can't have attributes.
396 ProhibitAttributes(attrs);
397
398 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
399 AS_none, OwnedType);
400 }
401
402 /// ParseUsingDirective - Parse C++ using-directive, assumes
403 /// that current token is 'namespace' and 'using' was already parsed.
404 ///
405 /// using-directive: [C++ 7.3.p4: namespace.udir]
406 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
407 /// namespace-name ;
408 /// [GNU] using-directive:
409 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
410 /// namespace-name attributes[opt] ;
411 ///
ParseUsingDirective(unsigned Context,SourceLocation UsingLoc,SourceLocation & DeclEnd,ParsedAttributes & attrs)412 Decl *Parser::ParseUsingDirective(unsigned Context,
413 SourceLocation UsingLoc,
414 SourceLocation &DeclEnd,
415 ParsedAttributes &attrs) {
416 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
417
418 // Eat 'namespace'.
419 SourceLocation NamespcLoc = ConsumeToken();
420
421 if (Tok.is(tok::code_completion)) {
422 Actions.CodeCompleteUsingDirective(getCurScope());
423 cutOffParsing();
424 return nullptr;
425 }
426
427 CXXScopeSpec SS;
428 // Parse (optional) nested-name-specifier.
429 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
430
431 IdentifierInfo *NamespcName = nullptr;
432 SourceLocation IdentLoc = SourceLocation();
433
434 // Parse namespace-name.
435 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
436 Diag(Tok, diag::err_expected_namespace_name);
437 // If there was invalid namespace name, skip to end of decl, and eat ';'.
438 SkipUntil(tok::semi);
439 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
440 return nullptr;
441 }
442
443 // Parse identifier.
444 NamespcName = Tok.getIdentifierInfo();
445 IdentLoc = ConsumeToken();
446
447 // Parse (optional) attributes (most likely GNU strong-using extension).
448 bool GNUAttr = false;
449 if (Tok.is(tok::kw___attribute)) {
450 GNUAttr = true;
451 ParseGNUAttributes(attrs);
452 }
453
454 // Eat ';'.
455 DeclEnd = Tok.getLocation();
456 if (ExpectAndConsume(tok::semi,
457 GNUAttr ? diag::err_expected_semi_after_attribute_list
458 : diag::err_expected_semi_after_namespace_name))
459 SkipUntil(tok::semi);
460
461 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
462 IdentLoc, NamespcName, attrs.getList());
463 }
464
465 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
466 /// Assumes that 'using' was already seen.
467 ///
468 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
469 /// 'using' 'typename'[opt] ::[opt] nested-name-specifier
470 /// unqualified-id
471 /// 'using' :: unqualified-id
472 ///
473 /// alias-declaration: C++11 [dcl.dcl]p1
474 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
475 ///
ParseUsingDeclaration(unsigned Context,const ParsedTemplateInfo & TemplateInfo,SourceLocation UsingLoc,SourceLocation & DeclEnd,AccessSpecifier AS,Decl ** OwnedType)476 Decl *Parser::ParseUsingDeclaration(unsigned Context,
477 const ParsedTemplateInfo &TemplateInfo,
478 SourceLocation UsingLoc,
479 SourceLocation &DeclEnd,
480 AccessSpecifier AS,
481 Decl **OwnedType) {
482 CXXScopeSpec SS;
483 SourceLocation TypenameLoc;
484 bool HasTypenameKeyword = false;
485
486 // Check for misplaced attributes before the identifier in an
487 // alias-declaration.
488 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
489 MaybeParseCXX11Attributes(MisplacedAttrs);
490
491 // Ignore optional 'typename'.
492 // FIXME: This is wrong; we should parse this as a typename-specifier.
493 if (TryConsumeToken(tok::kw_typename, TypenameLoc))
494 HasTypenameKeyword = true;
495
496 // Parse nested-name-specifier.
497 IdentifierInfo *LastII = nullptr;
498 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false,
499 /*MayBePseudoDtor=*/nullptr,
500 /*IsTypename=*/false,
501 /*LastII=*/&LastII);
502
503 // Check nested-name specifier.
504 if (SS.isInvalid()) {
505 SkipUntil(tok::semi);
506 return nullptr;
507 }
508
509 SourceLocation TemplateKWLoc;
510 UnqualifiedId Name;
511
512 // Parse the unqualified-id. We allow parsing of both constructor and
513 // destructor names and allow the action module to diagnose any semantic
514 // errors.
515 //
516 // C++11 [class.qual]p2:
517 // [...] in a using-declaration that is a member-declaration, if the name
518 // specified after the nested-name-specifier is the same as the identifier
519 // or the simple-template-id's template-name in the last component of the
520 // nested-name-specifier, the name is [...] considered to name the
521 // constructor.
522 if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
523 Tok.is(tok::identifier) && NextToken().is(tok::semi) &&
524 SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
525 !SS.getScopeRep()->getAsNamespace() &&
526 !SS.getScopeRep()->getAsNamespaceAlias()) {
527 SourceLocation IdLoc = ConsumeToken();
528 ParsedType Type = Actions.getInheritingConstructorName(SS, IdLoc, *LastII);
529 Name.setConstructorName(Type, IdLoc, IdLoc);
530 } else if (ParseUnqualifiedId(SS, /*EnteringContext=*/ false,
531 /*AllowDestructorName=*/ true,
532 /*AllowConstructorName=*/ true, ParsedType(),
533 TemplateKWLoc, Name)) {
534 SkipUntil(tok::semi);
535 return nullptr;
536 }
537
538 ParsedAttributesWithRange Attrs(AttrFactory);
539 MaybeParseGNUAttributes(Attrs);
540 MaybeParseCXX11Attributes(Attrs);
541
542 // Maybe this is an alias-declaration.
543 TypeResult TypeAlias;
544 bool IsAliasDecl = Tok.is(tok::equal);
545 if (IsAliasDecl) {
546 // If we had any misplaced attributes from earlier, this is where they
547 // should have been written.
548 if (MisplacedAttrs.Range.isValid()) {
549 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
550 << FixItHint::CreateInsertionFromRange(
551 Tok.getLocation(),
552 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
553 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
554 Attrs.takeAllFrom(MisplacedAttrs);
555 }
556
557 ConsumeToken();
558
559 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
560 diag::warn_cxx98_compat_alias_declaration :
561 diag::ext_alias_declaration);
562
563 // Type alias templates cannot be specialized.
564 int SpecKind = -1;
565 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
566 Name.getKind() == UnqualifiedId::IK_TemplateId)
567 SpecKind = 0;
568 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
569 SpecKind = 1;
570 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
571 SpecKind = 2;
572 if (SpecKind != -1) {
573 SourceRange Range;
574 if (SpecKind == 0)
575 Range = SourceRange(Name.TemplateId->LAngleLoc,
576 Name.TemplateId->RAngleLoc);
577 else
578 Range = TemplateInfo.getSourceRange();
579 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
580 << SpecKind << Range;
581 SkipUntil(tok::semi);
582 return nullptr;
583 }
584
585 // Name must be an identifier.
586 if (Name.getKind() != UnqualifiedId::IK_Identifier) {
587 Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier);
588 // No removal fixit: can't recover from this.
589 SkipUntil(tok::semi);
590 return nullptr;
591 } else if (HasTypenameKeyword)
592 Diag(TypenameLoc, diag::err_alias_declaration_not_identifier)
593 << FixItHint::CreateRemoval(SourceRange(TypenameLoc,
594 SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc));
595 else if (SS.isNotEmpty())
596 Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
597 << FixItHint::CreateRemoval(SS.getRange());
598
599 TypeAlias = ParseTypeName(nullptr, TemplateInfo.Kind ?
600 Declarator::AliasTemplateContext :
601 Declarator::AliasDeclContext, AS, OwnedType,
602 &Attrs);
603 } else {
604 // C++11 attributes are not allowed on a using-declaration, but GNU ones
605 // are.
606 ProhibitAttributes(MisplacedAttrs);
607 ProhibitAttributes(Attrs);
608
609 // Parse (optional) attributes (most likely GNU strong-using extension).
610 MaybeParseGNUAttributes(Attrs);
611 }
612
613 // Eat ';'.
614 DeclEnd = Tok.getLocation();
615 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
616 !Attrs.empty() ? "attributes list"
617 : IsAliasDecl ? "alias declaration"
618 : "using declaration"))
619 SkipUntil(tok::semi);
620
621 // Diagnose an attempt to declare a templated using-declaration.
622 // In C++11, alias-declarations can be templates:
623 // template <...> using id = type;
624 if (TemplateInfo.Kind && !IsAliasDecl) {
625 SourceRange R = TemplateInfo.getSourceRange();
626 Diag(UsingLoc, diag::err_templated_using_declaration)
627 << R << FixItHint::CreateRemoval(R);
628
629 // Unfortunately, we have to bail out instead of recovering by
630 // ignoring the parameters, just in case the nested name specifier
631 // depends on the parameters.
632 return nullptr;
633 }
634
635 // "typename" keyword is allowed for identifiers only,
636 // because it may be a type definition.
637 if (HasTypenameKeyword && Name.getKind() != UnqualifiedId::IK_Identifier) {
638 Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only)
639 << FixItHint::CreateRemoval(SourceRange(TypenameLoc));
640 // Proceed parsing, but reset the HasTypenameKeyword flag.
641 HasTypenameKeyword = false;
642 }
643
644 if (IsAliasDecl) {
645 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
646 MultiTemplateParamsArg TemplateParamsArg(
647 TemplateParams ? TemplateParams->data() : nullptr,
648 TemplateParams ? TemplateParams->size() : 0);
649 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
650 UsingLoc, Name, Attrs.getList(),
651 TypeAlias);
652 }
653
654 return Actions.ActOnUsingDeclaration(getCurScope(), AS,
655 /* HasUsingKeyword */ true, UsingLoc,
656 SS, Name, Attrs.getList(),
657 HasTypenameKeyword, TypenameLoc);
658 }
659
660 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
661 ///
662 /// [C++0x] static_assert-declaration:
663 /// static_assert ( constant-expression , string-literal ) ;
664 ///
665 /// [C11] static_assert-declaration:
666 /// _Static_assert ( constant-expression , string-literal ) ;
667 ///
ParseStaticAssertDeclaration(SourceLocation & DeclEnd)668 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
669 assert((Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) &&
670 "Not a static_assert declaration");
671
672 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
673 Diag(Tok, diag::ext_c11_static_assert);
674 if (Tok.is(tok::kw_static_assert))
675 Diag(Tok, diag::warn_cxx98_compat_static_assert);
676
677 SourceLocation StaticAssertLoc = ConsumeToken();
678
679 BalancedDelimiterTracker T(*this, tok::l_paren);
680 if (T.consumeOpen()) {
681 Diag(Tok, diag::err_expected) << tok::l_paren;
682 SkipMalformedDecl();
683 return nullptr;
684 }
685
686 ExprResult AssertExpr(ParseConstantExpression());
687 if (AssertExpr.isInvalid()) {
688 SkipMalformedDecl();
689 return nullptr;
690 }
691
692 ExprResult AssertMessage;
693 if (Tok.is(tok::r_paren)) {
694 Diag(Tok, getLangOpts().CPlusPlus1z
695 ? diag::warn_cxx1y_compat_static_assert_no_message
696 : diag::ext_static_assert_no_message)
697 << (getLangOpts().CPlusPlus1z
698 ? FixItHint()
699 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
700 } else {
701 if (ExpectAndConsume(tok::comma)) {
702 SkipUntil(tok::semi);
703 return nullptr;
704 }
705
706 if (!isTokenStringLiteral()) {
707 Diag(Tok, diag::err_expected_string_literal)
708 << /*Source='static_assert'*/1;
709 SkipMalformedDecl();
710 return nullptr;
711 }
712
713 AssertMessage = ParseStringLiteralExpression();
714 if (AssertMessage.isInvalid()) {
715 SkipMalformedDecl();
716 return nullptr;
717 }
718 }
719
720 T.consumeClose();
721
722 DeclEnd = Tok.getLocation();
723 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
724
725 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
726 AssertExpr.get(),
727 AssertMessage.get(),
728 T.getCloseLocation());
729 }
730
731 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
732 ///
733 /// 'decltype' ( expression )
734 /// 'decltype' ( 'auto' ) [C++1y]
735 ///
ParseDecltypeSpecifier(DeclSpec & DS)736 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
737 assert((Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))
738 && "Not a decltype specifier");
739
740 ExprResult Result;
741 SourceLocation StartLoc = Tok.getLocation();
742 SourceLocation EndLoc;
743
744 if (Tok.is(tok::annot_decltype)) {
745 Result = getExprAnnotation(Tok);
746 EndLoc = Tok.getAnnotationEndLoc();
747 ConsumeToken();
748 if (Result.isInvalid()) {
749 DS.SetTypeSpecError();
750 return EndLoc;
751 }
752 } else {
753 if (Tok.getIdentifierInfo()->isStr("decltype"))
754 Diag(Tok, diag::warn_cxx98_compat_decltype);
755
756 ConsumeToken();
757
758 BalancedDelimiterTracker T(*this, tok::l_paren);
759 if (T.expectAndConsume(diag::err_expected_lparen_after,
760 "decltype", tok::r_paren)) {
761 DS.SetTypeSpecError();
762 return T.getOpenLocation() == Tok.getLocation() ?
763 StartLoc : T.getOpenLocation();
764 }
765
766 // Check for C++1y 'decltype(auto)'.
767 if (Tok.is(tok::kw_auto)) {
768 // No need to disambiguate here: an expression can't start with 'auto',
769 // because the typename-specifier in a function-style cast operation can't
770 // be 'auto'.
771 Diag(Tok.getLocation(),
772 getLangOpts().CPlusPlus1y
773 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
774 : diag::ext_decltype_auto_type_specifier);
775 ConsumeToken();
776 } else {
777 // Parse the expression
778
779 // C++11 [dcl.type.simple]p4:
780 // The operand of the decltype specifier is an unevaluated operand.
781 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
782 nullptr,/*IsDecltype=*/true);
783 Result = ParseExpression();
784 if (Result.isInvalid()) {
785 DS.SetTypeSpecError();
786 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
787 EndLoc = ConsumeParen();
788 } else {
789 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
790 // Backtrack to get the location of the last token before the semi.
791 PP.RevertCachedTokens(2);
792 ConsumeToken(); // the semi.
793 EndLoc = ConsumeAnyToken();
794 assert(Tok.is(tok::semi));
795 } else {
796 EndLoc = Tok.getLocation();
797 }
798 }
799 return EndLoc;
800 }
801
802 Result = Actions.ActOnDecltypeExpression(Result.get());
803 }
804
805 // Match the ')'
806 T.consumeClose();
807 if (T.getCloseLocation().isInvalid()) {
808 DS.SetTypeSpecError();
809 // FIXME: this should return the location of the last token
810 // that was consumed (by "consumeClose()")
811 return T.getCloseLocation();
812 }
813
814 if (Result.isInvalid()) {
815 DS.SetTypeSpecError();
816 return T.getCloseLocation();
817 }
818
819 EndLoc = T.getCloseLocation();
820 }
821 assert(!Result.isInvalid());
822
823 const char *PrevSpec = nullptr;
824 unsigned DiagID;
825 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
826 // Check for duplicate type specifiers (e.g. "int decltype(a)").
827 if (Result.get()
828 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
829 DiagID, Result.get(), Policy)
830 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
831 DiagID, Policy)) {
832 Diag(StartLoc, DiagID) << PrevSpec;
833 DS.SetTypeSpecError();
834 }
835 return EndLoc;
836 }
837
AnnotateExistingDecltypeSpecifier(const DeclSpec & DS,SourceLocation StartLoc,SourceLocation EndLoc)838 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
839 SourceLocation StartLoc,
840 SourceLocation EndLoc) {
841 // make sure we have a token we can turn into an annotation token
842 if (PP.isBacktrackEnabled())
843 PP.RevertCachedTokens(1);
844 else
845 PP.EnterToken(Tok);
846
847 Tok.setKind(tok::annot_decltype);
848 setExprAnnotation(Tok,
849 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
850 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
851 ExprError());
852 Tok.setAnnotationEndLoc(EndLoc);
853 Tok.setLocation(StartLoc);
854 PP.AnnotateCachedTokens(Tok);
855 }
856
ParseUnderlyingTypeSpecifier(DeclSpec & DS)857 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
858 assert(Tok.is(tok::kw___underlying_type) &&
859 "Not an underlying type specifier");
860
861 SourceLocation StartLoc = ConsumeToken();
862 BalancedDelimiterTracker T(*this, tok::l_paren);
863 if (T.expectAndConsume(diag::err_expected_lparen_after,
864 "__underlying_type", tok::r_paren)) {
865 return;
866 }
867
868 TypeResult Result = ParseTypeName();
869 if (Result.isInvalid()) {
870 SkipUntil(tok::r_paren, StopAtSemi);
871 return;
872 }
873
874 // Match the ')'
875 T.consumeClose();
876 if (T.getCloseLocation().isInvalid())
877 return;
878
879 const char *PrevSpec = nullptr;
880 unsigned DiagID;
881 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
882 DiagID, Result.get(),
883 Actions.getASTContext().getPrintingPolicy()))
884 Diag(StartLoc, DiagID) << PrevSpec;
885 DS.setTypeofParensRange(T.getRange());
886 }
887
888 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
889 /// class name or decltype-specifier. Note that we only check that the result
890 /// names a type; semantic analysis will need to verify that the type names a
891 /// class. The result is either a type or null, depending on whether a type
892 /// name was found.
893 ///
894 /// base-type-specifier: [C++11 class.derived]
895 /// class-or-decltype
896 /// class-or-decltype: [C++11 class.derived]
897 /// nested-name-specifier[opt] class-name
898 /// decltype-specifier
899 /// class-name: [C++ class.name]
900 /// identifier
901 /// simple-template-id
902 ///
903 /// In C++98, instead of base-type-specifier, we have:
904 ///
905 /// ::[opt] nested-name-specifier[opt] class-name
ParseBaseTypeSpecifier(SourceLocation & BaseLoc,SourceLocation & EndLocation)906 Parser::TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
907 SourceLocation &EndLocation) {
908 // Ignore attempts to use typename
909 if (Tok.is(tok::kw_typename)) {
910 Diag(Tok, diag::err_expected_class_name_not_template)
911 << FixItHint::CreateRemoval(Tok.getLocation());
912 ConsumeToken();
913 }
914
915 // Parse optional nested-name-specifier
916 CXXScopeSpec SS;
917 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
918
919 BaseLoc = Tok.getLocation();
920
921 // Parse decltype-specifier
922 // tok == kw_decltype is just error recovery, it can only happen when SS
923 // isn't empty
924 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
925 if (SS.isNotEmpty())
926 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
927 << FixItHint::CreateRemoval(SS.getRange());
928 // Fake up a Declarator to use with ActOnTypeName.
929 DeclSpec DS(AttrFactory);
930
931 EndLocation = ParseDecltypeSpecifier(DS);
932
933 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
934 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
935 }
936
937 // Check whether we have a template-id that names a type.
938 if (Tok.is(tok::annot_template_id)) {
939 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
940 if (TemplateId->Kind == TNK_Type_template ||
941 TemplateId->Kind == TNK_Dependent_template_name) {
942 AnnotateTemplateIdTokenAsType();
943
944 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
945 ParsedType Type = getTypeAnnotation(Tok);
946 EndLocation = Tok.getAnnotationEndLoc();
947 ConsumeToken();
948
949 if (Type)
950 return Type;
951 return true;
952 }
953
954 // Fall through to produce an error below.
955 }
956
957 if (Tok.isNot(tok::identifier)) {
958 Diag(Tok, diag::err_expected_class_name);
959 return true;
960 }
961
962 IdentifierInfo *Id = Tok.getIdentifierInfo();
963 SourceLocation IdLoc = ConsumeToken();
964
965 if (Tok.is(tok::less)) {
966 // It looks the user intended to write a template-id here, but the
967 // template-name was wrong. Try to fix that.
968 TemplateNameKind TNK = TNK_Type_template;
969 TemplateTy Template;
970 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
971 &SS, Template, TNK)) {
972 Diag(IdLoc, diag::err_unknown_template_name)
973 << Id;
974 }
975
976 if (!Template) {
977 TemplateArgList TemplateArgs;
978 SourceLocation LAngleLoc, RAngleLoc;
979 ParseTemplateIdAfterTemplateName(TemplateTy(), IdLoc, SS,
980 true, LAngleLoc, TemplateArgs, RAngleLoc);
981 return true;
982 }
983
984 // Form the template name
985 UnqualifiedId TemplateName;
986 TemplateName.setIdentifier(Id, IdLoc);
987
988 // Parse the full template-id, then turn it into a type.
989 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
990 TemplateName, true))
991 return true;
992 if (TNK == TNK_Dependent_template_name)
993 AnnotateTemplateIdTokenAsType();
994
995 // If we didn't end up with a typename token, there's nothing more we
996 // can do.
997 if (Tok.isNot(tok::annot_typename))
998 return true;
999
1000 // Retrieve the type from the annotation token, consume that token, and
1001 // return.
1002 EndLocation = Tok.getAnnotationEndLoc();
1003 ParsedType Type = getTypeAnnotation(Tok);
1004 ConsumeToken();
1005 return Type;
1006 }
1007
1008 // We have an identifier; check whether it is actually a type.
1009 IdentifierInfo *CorrectedII = nullptr;
1010 ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true,
1011 false, ParsedType(),
1012 /*IsCtorOrDtorName=*/false,
1013 /*NonTrivialTypeSourceInfo=*/true,
1014 &CorrectedII);
1015 if (!Type) {
1016 Diag(IdLoc, diag::err_expected_class_name);
1017 return true;
1018 }
1019
1020 // Consume the identifier.
1021 EndLocation = IdLoc;
1022
1023 // Fake up a Declarator to use with ActOnTypeName.
1024 DeclSpec DS(AttrFactory);
1025 DS.SetRangeStart(IdLoc);
1026 DS.SetRangeEnd(EndLocation);
1027 DS.getTypeSpecScope() = SS;
1028
1029 const char *PrevSpec = nullptr;
1030 unsigned DiagID;
1031 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1032 Actions.getASTContext().getPrintingPolicy());
1033
1034 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1035 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1036 }
1037
ParseMicrosoftInheritanceClassAttributes(ParsedAttributes & attrs)1038 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
1039 while (Tok.is(tok::kw___single_inheritance) ||
1040 Tok.is(tok::kw___multiple_inheritance) ||
1041 Tok.is(tok::kw___virtual_inheritance)) {
1042 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1043 SourceLocation AttrNameLoc = ConsumeToken();
1044 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1045 AttributeList::AS_Keyword);
1046 }
1047 }
1048
1049 /// Determine whether the following tokens are valid after a type-specifier
1050 /// which could be a standalone declaration. This will conservatively return
1051 /// true if there's any doubt, and is appropriate for insert-';' fixits.
isValidAfterTypeSpecifier(bool CouldBeBitfield)1052 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
1053 // This switch enumerates the valid "follow" set for type-specifiers.
1054 switch (Tok.getKind()) {
1055 default: break;
1056 case tok::semi: // struct foo {...} ;
1057 case tok::star: // struct foo {...} * P;
1058 case tok::amp: // struct foo {...} & R = ...
1059 case tok::ampamp: // struct foo {...} && R = ...
1060 case tok::identifier: // struct foo {...} V ;
1061 case tok::r_paren: //(struct foo {...} ) {4}
1062 case tok::annot_cxxscope: // struct foo {...} a:: b;
1063 case tok::annot_typename: // struct foo {...} a ::b;
1064 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1065 case tok::l_paren: // struct foo {...} ( x);
1066 case tok::comma: // __builtin_offsetof(struct foo{...} ,
1067 case tok::kw_operator: // struct foo operator ++() {...}
1068 case tok::kw___declspec: // struct foo {...} __declspec(...)
1069 return true;
1070 case tok::colon:
1071 return CouldBeBitfield; // enum E { ... } : 2;
1072 // Type qualifiers
1073 case tok::kw_const: // struct foo {...} const x;
1074 case tok::kw_volatile: // struct foo {...} volatile x;
1075 case tok::kw_restrict: // struct foo {...} restrict x;
1076 // Function specifiers
1077 // Note, no 'explicit'. An explicit function must be either a conversion
1078 // operator or a constructor. Either way, it can't have a return type.
1079 case tok::kw_inline: // struct foo inline f();
1080 case tok::kw_virtual: // struct foo virtual f();
1081 case tok::kw_friend: // struct foo friend f();
1082 // Storage-class specifiers
1083 case tok::kw_static: // struct foo {...} static x;
1084 case tok::kw_extern: // struct foo {...} extern x;
1085 case tok::kw_typedef: // struct foo {...} typedef x;
1086 case tok::kw_register: // struct foo {...} register x;
1087 case tok::kw_auto: // struct foo {...} auto x;
1088 case tok::kw_mutable: // struct foo {...} mutable x;
1089 case tok::kw_thread_local: // struct foo {...} thread_local x;
1090 case tok::kw_constexpr: // struct foo {...} constexpr x;
1091 // As shown above, type qualifiers and storage class specifiers absolutely
1092 // can occur after class specifiers according to the grammar. However,
1093 // almost no one actually writes code like this. If we see one of these,
1094 // it is much more likely that someone missed a semi colon and the
1095 // type/storage class specifier we're seeing is part of the *next*
1096 // intended declaration, as in:
1097 //
1098 // struct foo { ... }
1099 // typedef int X;
1100 //
1101 // We'd really like to emit a missing semicolon error instead of emitting
1102 // an error on the 'int' saying that you can't have two type specifiers in
1103 // the same declaration of X. Because of this, we look ahead past this
1104 // token to see if it's a type specifier. If so, we know the code is
1105 // otherwise invalid, so we can produce the expected semi error.
1106 if (!isKnownToBeTypeSpecifier(NextToken()))
1107 return true;
1108 break;
1109 case tok::r_brace: // struct bar { struct foo {...} }
1110 // Missing ';' at end of struct is accepted as an extension in C mode.
1111 if (!getLangOpts().CPlusPlus)
1112 return true;
1113 break;
1114 // C++11 attributes
1115 case tok::l_square: // enum E [[]] x
1116 // Note, no tok::kw_alignas here; alignas cannot appertain to a type.
1117 return getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
1118 case tok::greater:
1119 // template<class T = class X>
1120 return getLangOpts().CPlusPlus;
1121 }
1122 return false;
1123 }
1124
1125 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1126 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1127 /// until we reach the start of a definition or see a token that
1128 /// cannot start a definition.
1129 ///
1130 /// class-specifier: [C++ class]
1131 /// class-head '{' member-specification[opt] '}'
1132 /// class-head '{' member-specification[opt] '}' attributes[opt]
1133 /// class-head:
1134 /// class-key identifier[opt] base-clause[opt]
1135 /// class-key nested-name-specifier identifier base-clause[opt]
1136 /// class-key nested-name-specifier[opt] simple-template-id
1137 /// base-clause[opt]
1138 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1139 /// [GNU] class-key attributes[opt] nested-name-specifier
1140 /// identifier base-clause[opt]
1141 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1142 /// simple-template-id base-clause[opt]
1143 /// class-key:
1144 /// 'class'
1145 /// 'struct'
1146 /// 'union'
1147 ///
1148 /// elaborated-type-specifier: [C++ dcl.type.elab]
1149 /// class-key ::[opt] nested-name-specifier[opt] identifier
1150 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1151 /// simple-template-id
1152 ///
1153 /// Note that the C++ class-specifier and elaborated-type-specifier,
1154 /// together, subsume the C99 struct-or-union-specifier:
1155 ///
1156 /// struct-or-union-specifier: [C99 6.7.2.1]
1157 /// struct-or-union identifier[opt] '{' struct-contents '}'
1158 /// struct-or-union identifier
1159 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1160 /// '}' attributes[opt]
1161 /// [GNU] struct-or-union attributes[opt] identifier
1162 /// struct-or-union:
1163 /// 'struct'
1164 /// 'union'
ParseClassSpecifier(tok::TokenKind TagTokKind,SourceLocation StartLoc,DeclSpec & DS,const ParsedTemplateInfo & TemplateInfo,AccessSpecifier AS,bool EnteringContext,DeclSpecContext DSC,ParsedAttributesWithRange & Attributes)1165 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1166 SourceLocation StartLoc, DeclSpec &DS,
1167 const ParsedTemplateInfo &TemplateInfo,
1168 AccessSpecifier AS,
1169 bool EnteringContext, DeclSpecContext DSC,
1170 ParsedAttributesWithRange &Attributes) {
1171 DeclSpec::TST TagType;
1172 if (TagTokKind == tok::kw_struct)
1173 TagType = DeclSpec::TST_struct;
1174 else if (TagTokKind == tok::kw___interface)
1175 TagType = DeclSpec::TST_interface;
1176 else if (TagTokKind == tok::kw_class)
1177 TagType = DeclSpec::TST_class;
1178 else {
1179 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1180 TagType = DeclSpec::TST_union;
1181 }
1182
1183 if (Tok.is(tok::code_completion)) {
1184 // Code completion for a struct, class, or union name.
1185 Actions.CodeCompleteTag(getCurScope(), TagType);
1186 return cutOffParsing();
1187 }
1188
1189 // C++03 [temp.explicit] 14.7.2/8:
1190 // The usual access checking rules do not apply to names used to specify
1191 // explicit instantiations.
1192 //
1193 // As an extension we do not perform access checking on the names used to
1194 // specify explicit specializations either. This is important to allow
1195 // specializing traits classes for private types.
1196 //
1197 // Note that we don't suppress if this turns out to be an elaborated
1198 // type specifier.
1199 bool shouldDelayDiagsInTag =
1200 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1201 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1202 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1203
1204 ParsedAttributesWithRange attrs(AttrFactory);
1205 // If attributes exist after tag, parse them.
1206 MaybeParseGNUAttributes(attrs);
1207
1208 // If declspecs exist after tag, parse them.
1209 while (Tok.is(tok::kw___declspec))
1210 ParseMicrosoftDeclSpec(attrs);
1211
1212 // Parse inheritance specifiers.
1213 if (Tok.is(tok::kw___single_inheritance) ||
1214 Tok.is(tok::kw___multiple_inheritance) ||
1215 Tok.is(tok::kw___virtual_inheritance))
1216 ParseMicrosoftInheritanceClassAttributes(attrs);
1217
1218 // If C++0x attributes exist here, parse them.
1219 // FIXME: Are we consistent with the ordering of parsing of different
1220 // styles of attributes?
1221 MaybeParseCXX11Attributes(attrs);
1222
1223 // Source location used by FIXIT to insert misplaced
1224 // C++11 attributes
1225 SourceLocation AttrFixitLoc = Tok.getLocation();
1226
1227 // GNU libstdc++ and libc++ use certain intrinsic names as the
1228 // name of struct templates, but some are keywords in GCC >= 4.3
1229 // MSVC and Clang. For compatibility, convert the token to an identifier
1230 // and issue a warning diagnostic.
1231 if (TagType == DeclSpec::TST_struct && !Tok.is(tok::identifier) &&
1232 !Tok.isAnnotation()) {
1233 const IdentifierInfo *II = Tok.getIdentifierInfo();
1234 // We rarely end up here so the following check is efficient.
1235 if (II && II->getName().startswith("__is_"))
1236 TryKeywordIdentFallback(true);
1237 }
1238
1239 // Parse the (optional) nested-name-specifier.
1240 CXXScopeSpec &SS = DS.getTypeSpecScope();
1241 if (getLangOpts().CPlusPlus) {
1242 // "FOO : BAR" is not a potential typo for "FOO::BAR".
1243 ColonProtectionRAIIObject X(*this);
1244
1245 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1246 DS.SetTypeSpecError();
1247 if (SS.isSet())
1248 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
1249 Diag(Tok, diag::err_expected) << tok::identifier;
1250 }
1251
1252 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1253
1254 // Parse the (optional) class name or simple-template-id.
1255 IdentifierInfo *Name = nullptr;
1256 SourceLocation NameLoc;
1257 TemplateIdAnnotation *TemplateId = nullptr;
1258 if (Tok.is(tok::identifier)) {
1259 Name = Tok.getIdentifierInfo();
1260 NameLoc = ConsumeToken();
1261
1262 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1263 // The name was supposed to refer to a template, but didn't.
1264 // Eat the template argument list and try to continue parsing this as
1265 // a class (or template thereof).
1266 TemplateArgList TemplateArgs;
1267 SourceLocation LAngleLoc, RAngleLoc;
1268 if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS,
1269 true, LAngleLoc,
1270 TemplateArgs, RAngleLoc)) {
1271 // We couldn't parse the template argument list at all, so don't
1272 // try to give any location information for the list.
1273 LAngleLoc = RAngleLoc = SourceLocation();
1274 }
1275
1276 Diag(NameLoc, diag::err_explicit_spec_non_template)
1277 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1278 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
1279
1280 // Strip off the last template parameter list if it was empty, since
1281 // we've removed its template argument list.
1282 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1283 if (TemplateParams && TemplateParams->size() > 1) {
1284 TemplateParams->pop_back();
1285 } else {
1286 TemplateParams = nullptr;
1287 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1288 = ParsedTemplateInfo::NonTemplate;
1289 }
1290 } else if (TemplateInfo.Kind
1291 == ParsedTemplateInfo::ExplicitInstantiation) {
1292 // Pretend this is just a forward declaration.
1293 TemplateParams = nullptr;
1294 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1295 = ParsedTemplateInfo::NonTemplate;
1296 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1297 = SourceLocation();
1298 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1299 = SourceLocation();
1300 }
1301 }
1302 } else if (Tok.is(tok::annot_template_id)) {
1303 TemplateId = takeTemplateIdAnnotation(Tok);
1304 NameLoc = ConsumeToken();
1305
1306 if (TemplateId->Kind != TNK_Type_template &&
1307 TemplateId->Kind != TNK_Dependent_template_name) {
1308 // The template-name in the simple-template-id refers to
1309 // something other than a class template. Give an appropriate
1310 // error message and skip to the ';'.
1311 SourceRange Range(NameLoc);
1312 if (SS.isNotEmpty())
1313 Range.setBegin(SS.getBeginLoc());
1314
1315 // FIXME: Name may be null here.
1316 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1317 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
1318
1319 DS.SetTypeSpecError();
1320 SkipUntil(tok::semi, StopBeforeMatch);
1321 return;
1322 }
1323 }
1324
1325 // There are four options here.
1326 // - If we are in a trailing return type, this is always just a reference,
1327 // and we must not try to parse a definition. For instance,
1328 // [] () -> struct S { };
1329 // does not define a type.
1330 // - If we have 'struct foo {...', 'struct foo :...',
1331 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1332 // - If we have 'struct foo;', then this is either a forward declaration
1333 // or a friend declaration, which have to be treated differently.
1334 // - Otherwise we have something like 'struct foo xyz', a reference.
1335 //
1336 // We also detect these erroneous cases to provide better diagnostic for
1337 // C++11 attributes parsing.
1338 // - attributes follow class name:
1339 // struct foo [[]] {};
1340 // - attributes appear before or after 'final':
1341 // struct foo [[]] final [[]] {};
1342 //
1343 // However, in type-specifier-seq's, things look like declarations but are
1344 // just references, e.g.
1345 // new struct s;
1346 // or
1347 // &T::operator struct s;
1348 // For these, DSC is DSC_type_specifier or DSC_alias_declaration.
1349
1350 // If there are attributes after class name, parse them.
1351 MaybeParseCXX11Attributes(Attributes);
1352
1353 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1354 Sema::TagUseKind TUK;
1355 if (DSC == DSC_trailing)
1356 TUK = Sema::TUK_Reference;
1357 else if (Tok.is(tok::l_brace) ||
1358 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1359 (isCXX11FinalKeyword() &&
1360 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1361 if (DS.isFriendSpecified()) {
1362 // C++ [class.friend]p2:
1363 // A class shall not be defined in a friend declaration.
1364 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1365 << SourceRange(DS.getFriendSpecLoc());
1366
1367 // Skip everything up to the semicolon, so that this looks like a proper
1368 // friend class (or template thereof) declaration.
1369 SkipUntil(tok::semi, StopBeforeMatch);
1370 TUK = Sema::TUK_Friend;
1371 } else {
1372 // Okay, this is a class definition.
1373 TUK = Sema::TUK_Definition;
1374 }
1375 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1376 NextToken().is(tok::kw_alignas))) {
1377 // We can't tell if this is a definition or reference
1378 // until we skipped the 'final' and C++11 attribute specifiers.
1379 TentativeParsingAction PA(*this);
1380
1381 // Skip the 'final' keyword.
1382 ConsumeToken();
1383
1384 // Skip C++11 attribute specifiers.
1385 while (true) {
1386 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1387 ConsumeBracket();
1388 if (!SkipUntil(tok::r_square, StopAtSemi))
1389 break;
1390 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1391 ConsumeToken();
1392 ConsumeParen();
1393 if (!SkipUntil(tok::r_paren, StopAtSemi))
1394 break;
1395 } else {
1396 break;
1397 }
1398 }
1399
1400 if (Tok.is(tok::l_brace) || Tok.is(tok::colon))
1401 TUK = Sema::TUK_Definition;
1402 else
1403 TUK = Sema::TUK_Reference;
1404
1405 PA.Revert();
1406 } else if (!isTypeSpecifier(DSC) &&
1407 (Tok.is(tok::semi) ||
1408 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1409 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1410 if (Tok.isNot(tok::semi)) {
1411 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1412 // A semicolon was missing after this declaration. Diagnose and recover.
1413 ExpectAndConsume(tok::semi, diag::err_expected_after,
1414 DeclSpec::getSpecifierName(TagType, PPol));
1415 PP.EnterToken(Tok);
1416 Tok.setKind(tok::semi);
1417 }
1418 } else
1419 TUK = Sema::TUK_Reference;
1420
1421 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1422 // to caller to handle.
1423 if (TUK != Sema::TUK_Reference) {
1424 // If this is not a reference, then the only possible
1425 // valid place for C++11 attributes to appear here
1426 // is between class-key and class-name. If there are
1427 // any attributes after class-name, we try a fixit to move
1428 // them to the right place.
1429 SourceRange AttrRange = Attributes.Range;
1430 if (AttrRange.isValid()) {
1431 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1432 << AttrRange
1433 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1434 CharSourceRange(AttrRange, true))
1435 << FixItHint::CreateRemoval(AttrRange);
1436
1437 // Recover by adding misplaced attributes to the attribute list
1438 // of the class so they can be applied on the class later.
1439 attrs.takeAllFrom(Attributes);
1440 }
1441 }
1442
1443 // If this is an elaborated type specifier, and we delayed
1444 // diagnostics before, just merge them into the current pool.
1445 if (shouldDelayDiagsInTag) {
1446 diagsFromTag.done();
1447 if (TUK == Sema::TUK_Reference)
1448 diagsFromTag.redelay();
1449 }
1450
1451 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1452 TUK != Sema::TUK_Definition)) {
1453 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1454 // We have a declaration or reference to an anonymous class.
1455 Diag(StartLoc, diag::err_anon_type_definition)
1456 << DeclSpec::getSpecifierName(TagType, Policy);
1457 }
1458
1459 // If we are parsing a definition and stop at a base-clause, continue on
1460 // until the semicolon. Continuing from the comma will just trick us into
1461 // thinking we are seeing a variable declaration.
1462 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1463 SkipUntil(tok::semi, StopBeforeMatch);
1464 else
1465 SkipUntil(tok::comma, StopAtSemi);
1466 return;
1467 }
1468
1469 // Create the tag portion of the class or class template.
1470 DeclResult TagOrTempResult = true; // invalid
1471 TypeResult TypeResult = true; // invalid
1472
1473 bool Owned = false;
1474 if (TemplateId) {
1475 // Explicit specialization, class template partial specialization,
1476 // or explicit instantiation.
1477 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1478 TemplateId->NumArgs);
1479 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1480 TUK == Sema::TUK_Declaration) {
1481 // This is an explicit instantiation of a class template.
1482 ProhibitAttributes(attrs);
1483
1484 TagOrTempResult
1485 = Actions.ActOnExplicitInstantiation(getCurScope(),
1486 TemplateInfo.ExternLoc,
1487 TemplateInfo.TemplateLoc,
1488 TagType,
1489 StartLoc,
1490 SS,
1491 TemplateId->Template,
1492 TemplateId->TemplateNameLoc,
1493 TemplateId->LAngleLoc,
1494 TemplateArgsPtr,
1495 TemplateId->RAngleLoc,
1496 attrs.getList());
1497
1498 // Friend template-ids are treated as references unless
1499 // they have template headers, in which case they're ill-formed
1500 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1501 // We diagnose this error in ActOnClassTemplateSpecialization.
1502 } else if (TUK == Sema::TUK_Reference ||
1503 (TUK == Sema::TUK_Friend &&
1504 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1505 ProhibitAttributes(attrs);
1506 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1507 TemplateId->SS,
1508 TemplateId->TemplateKWLoc,
1509 TemplateId->Template,
1510 TemplateId->TemplateNameLoc,
1511 TemplateId->LAngleLoc,
1512 TemplateArgsPtr,
1513 TemplateId->RAngleLoc);
1514 } else {
1515 // This is an explicit specialization or a class template
1516 // partial specialization.
1517 TemplateParameterLists FakedParamLists;
1518 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1519 // This looks like an explicit instantiation, because we have
1520 // something like
1521 //
1522 // template class Foo<X>
1523 //
1524 // but it actually has a definition. Most likely, this was
1525 // meant to be an explicit specialization, but the user forgot
1526 // the '<>' after 'template'.
1527 // It this is friend declaration however, since it cannot have a
1528 // template header, it is most likely that the user meant to
1529 // remove the 'template' keyword.
1530 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1531 "Expected a definition here");
1532
1533 if (TUK == Sema::TUK_Friend) {
1534 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1535 TemplateParams = nullptr;
1536 } else {
1537 SourceLocation LAngleLoc =
1538 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1539 Diag(TemplateId->TemplateNameLoc,
1540 diag::err_explicit_instantiation_with_definition)
1541 << SourceRange(TemplateInfo.TemplateLoc)
1542 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1543
1544 // Create a fake template parameter list that contains only
1545 // "template<>", so that we treat this construct as a class
1546 // template specialization.
1547 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1548 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr,
1549 0, LAngleLoc));
1550 TemplateParams = &FakedParamLists;
1551 }
1552 }
1553
1554 // Build the class template specialization.
1555 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1556 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1557 *TemplateId, attrs.getList(),
1558 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1559 : nullptr,
1560 TemplateParams ? TemplateParams->size() : 0));
1561 }
1562 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1563 TUK == Sema::TUK_Declaration) {
1564 // Explicit instantiation of a member of a class template
1565 // specialization, e.g.,
1566 //
1567 // template struct Outer<int>::Inner;
1568 //
1569 ProhibitAttributes(attrs);
1570
1571 TagOrTempResult
1572 = Actions.ActOnExplicitInstantiation(getCurScope(),
1573 TemplateInfo.ExternLoc,
1574 TemplateInfo.TemplateLoc,
1575 TagType, StartLoc, SS, Name,
1576 NameLoc, attrs.getList());
1577 } else if (TUK == Sema::TUK_Friend &&
1578 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1579 ProhibitAttributes(attrs);
1580
1581 TagOrTempResult =
1582 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1583 TagType, StartLoc, SS,
1584 Name, NameLoc, attrs.getList(),
1585 MultiTemplateParamsArg(
1586 TemplateParams? &(*TemplateParams)[0]
1587 : nullptr,
1588 TemplateParams? TemplateParams->size() : 0));
1589 } else {
1590 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1591 ProhibitAttributes(attrs);
1592
1593 if (TUK == Sema::TUK_Definition &&
1594 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1595 // If the declarator-id is not a template-id, issue a diagnostic and
1596 // recover by ignoring the 'template' keyword.
1597 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1598 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1599 TemplateParams = nullptr;
1600 }
1601
1602 bool IsDependent = false;
1603
1604 // Don't pass down template parameter lists if this is just a tag
1605 // reference. For example, we don't need the template parameters here:
1606 // template <class T> class A *makeA(T t);
1607 MultiTemplateParamsArg TParams;
1608 if (TUK != Sema::TUK_Reference && TemplateParams)
1609 TParams =
1610 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1611
1612 // Declaration or definition of a class type
1613 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1614 SS, Name, NameLoc, attrs.getList(), AS,
1615 DS.getModulePrivateSpecLoc(),
1616 TParams, Owned, IsDependent,
1617 SourceLocation(), false,
1618 clang::TypeResult(),
1619 DSC == DSC_type_specifier);
1620
1621 // If ActOnTag said the type was dependent, try again with the
1622 // less common call.
1623 if (IsDependent) {
1624 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1625 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1626 SS, Name, StartLoc, NameLoc);
1627 }
1628 }
1629
1630 // If there is a body, parse it and inform the actions module.
1631 if (TUK == Sema::TUK_Definition) {
1632 assert(Tok.is(tok::l_brace) ||
1633 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1634 isCXX11FinalKeyword());
1635 if (getLangOpts().CPlusPlus)
1636 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1637 TagOrTempResult.get());
1638 else
1639 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
1640 }
1641
1642 const char *PrevSpec = nullptr;
1643 unsigned DiagID;
1644 bool Result;
1645 if (!TypeResult.isInvalid()) {
1646 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1647 NameLoc.isValid() ? NameLoc : StartLoc,
1648 PrevSpec, DiagID, TypeResult.get(), Policy);
1649 } else if (!TagOrTempResult.isInvalid()) {
1650 Result = DS.SetTypeSpecType(TagType, StartLoc,
1651 NameLoc.isValid() ? NameLoc : StartLoc,
1652 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1653 Policy);
1654 } else {
1655 DS.SetTypeSpecError();
1656 return;
1657 }
1658
1659 if (Result)
1660 Diag(StartLoc, DiagID) << PrevSpec;
1661
1662 // At this point, we've successfully parsed a class-specifier in 'definition'
1663 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1664 // going to look at what comes after it to improve error recovery. If an
1665 // impossible token occurs next, we assume that the programmer forgot a ; at
1666 // the end of the declaration and recover that way.
1667 //
1668 // Also enforce C++ [temp]p3:
1669 // In a template-declaration which defines a class, no declarator
1670 // is permitted.
1671 if (TUK == Sema::TUK_Definition &&
1672 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1673 if (Tok.isNot(tok::semi)) {
1674 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1675 ExpectAndConsume(tok::semi, diag::err_expected_after,
1676 DeclSpec::getSpecifierName(TagType, PPol));
1677 // Push this token back into the preprocessor and change our current token
1678 // to ';' so that the rest of the code recovers as though there were an
1679 // ';' after the definition.
1680 PP.EnterToken(Tok);
1681 Tok.setKind(tok::semi);
1682 }
1683 }
1684 }
1685
1686 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1687 ///
1688 /// base-clause : [C++ class.derived]
1689 /// ':' base-specifier-list
1690 /// base-specifier-list:
1691 /// base-specifier '...'[opt]
1692 /// base-specifier-list ',' base-specifier '...'[opt]
ParseBaseClause(Decl * ClassDecl)1693 void Parser::ParseBaseClause(Decl *ClassDecl) {
1694 assert(Tok.is(tok::colon) && "Not a base clause");
1695 ConsumeToken();
1696
1697 // Build up an array of parsed base specifiers.
1698 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1699
1700 while (true) {
1701 // Parse a base-specifier.
1702 BaseResult Result = ParseBaseSpecifier(ClassDecl);
1703 if (Result.isInvalid()) {
1704 // Skip the rest of this base specifier, up until the comma or
1705 // opening brace.
1706 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
1707 } else {
1708 // Add this to our array of base specifiers.
1709 BaseInfo.push_back(Result.get());
1710 }
1711
1712 // If the next token is a comma, consume it and keep reading
1713 // base-specifiers.
1714 if (!TryConsumeToken(tok::comma))
1715 break;
1716 }
1717
1718 // Attach the base specifiers
1719 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
1720 }
1721
1722 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1723 /// one entry in the base class list of a class specifier, for example:
1724 /// class foo : public bar, virtual private baz {
1725 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1726 ///
1727 /// base-specifier: [C++ class.derived]
1728 /// attribute-specifier-seq[opt] base-type-specifier
1729 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
1730 /// base-type-specifier
1731 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
1732 /// base-type-specifier
ParseBaseSpecifier(Decl * ClassDecl)1733 Parser::BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
1734 bool IsVirtual = false;
1735 SourceLocation StartLoc = Tok.getLocation();
1736
1737 ParsedAttributesWithRange Attributes(AttrFactory);
1738 MaybeParseCXX11Attributes(Attributes);
1739
1740 // Parse the 'virtual' keyword.
1741 if (TryConsumeToken(tok::kw_virtual))
1742 IsVirtual = true;
1743
1744 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1745
1746 // Parse an (optional) access specifier.
1747 AccessSpecifier Access = getAccessSpecifierIfPresent();
1748 if (Access != AS_none)
1749 ConsumeToken();
1750
1751 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1752
1753 // Parse the 'virtual' keyword (again!), in case it came after the
1754 // access specifier.
1755 if (Tok.is(tok::kw_virtual)) {
1756 SourceLocation VirtualLoc = ConsumeToken();
1757 if (IsVirtual) {
1758 // Complain about duplicate 'virtual'
1759 Diag(VirtualLoc, diag::err_dup_virtual)
1760 << FixItHint::CreateRemoval(VirtualLoc);
1761 }
1762
1763 IsVirtual = true;
1764 }
1765
1766 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1767
1768 // Parse the class-name.
1769 SourceLocation EndLocation;
1770 SourceLocation BaseLoc;
1771 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
1772 if (BaseType.isInvalid())
1773 return true;
1774
1775 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
1776 // actually part of the base-specifier-list grammar productions, but we
1777 // parse it here for convenience.
1778 SourceLocation EllipsisLoc;
1779 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1780
1781 // Find the complete source range for the base-specifier.
1782 SourceRange Range(StartLoc, EndLocation);
1783
1784 // Notify semantic analysis that we have parsed a complete
1785 // base-specifier.
1786 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
1787 Access, BaseType.get(), BaseLoc,
1788 EllipsisLoc);
1789 }
1790
1791 /// getAccessSpecifierIfPresent - Determine whether the next token is
1792 /// a C++ access-specifier.
1793 ///
1794 /// access-specifier: [C++ class.derived]
1795 /// 'private'
1796 /// 'protected'
1797 /// 'public'
getAccessSpecifierIfPresent() const1798 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
1799 switch (Tok.getKind()) {
1800 default: return AS_none;
1801 case tok::kw_private: return AS_private;
1802 case tok::kw_protected: return AS_protected;
1803 case tok::kw_public: return AS_public;
1804 }
1805 }
1806
1807 /// \brief If the given declarator has any parts for which parsing has to be
1808 /// delayed, e.g., default arguments, create a late-parsed method declaration
1809 /// record to handle the parsing at the end of the class definition.
HandleMemberFunctionDeclDelays(Declarator & DeclaratorInfo,Decl * ThisDecl)1810 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
1811 Decl *ThisDecl) {
1812 // We just declared a member function. If this member function
1813 // has any default arguments, we'll need to parse them later.
1814 LateParsedMethodDeclaration *LateMethod = nullptr;
1815 DeclaratorChunk::FunctionTypeInfo &FTI
1816 = DeclaratorInfo.getFunctionTypeInfo();
1817
1818 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
1819 if (LateMethod || FTI.Params[ParamIdx].DefaultArgTokens) {
1820 if (!LateMethod) {
1821 // Push this method onto the stack of late-parsed method
1822 // declarations.
1823 LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
1824 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
1825 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
1826
1827 // Add all of the parameters prior to this one (they don't
1828 // have default arguments).
1829 LateMethod->DefaultArgs.reserve(FTI.NumParams);
1830 for (unsigned I = 0; I < ParamIdx; ++I)
1831 LateMethod->DefaultArgs.push_back(
1832 LateParsedDefaultArgument(FTI.Params[I].Param));
1833 }
1834
1835 // Add this parameter to the list of parameters (it may or may
1836 // not have a default argument).
1837 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
1838 FTI.Params[ParamIdx].Param, FTI.Params[ParamIdx].DefaultArgTokens));
1839 }
1840 }
1841 }
1842
1843 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
1844 /// virt-specifier.
1845 ///
1846 /// virt-specifier:
1847 /// override
1848 /// final
isCXX11VirtSpecifier(const Token & Tok) const1849 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
1850 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
1851 return VirtSpecifiers::VS_None;
1852
1853 IdentifierInfo *II = Tok.getIdentifierInfo();
1854
1855 // Initialize the contextual keywords.
1856 if (!Ident_final) {
1857 Ident_final = &PP.getIdentifierTable().get("final");
1858 if (getLangOpts().MicrosoftExt)
1859 Ident_sealed = &PP.getIdentifierTable().get("sealed");
1860 Ident_override = &PP.getIdentifierTable().get("override");
1861 }
1862
1863 if (II == Ident_override)
1864 return VirtSpecifiers::VS_Override;
1865
1866 if (II == Ident_sealed)
1867 return VirtSpecifiers::VS_Sealed;
1868
1869 if (II == Ident_final)
1870 return VirtSpecifiers::VS_Final;
1871
1872 return VirtSpecifiers::VS_None;
1873 }
1874
1875 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
1876 ///
1877 /// virt-specifier-seq:
1878 /// virt-specifier
1879 /// virt-specifier-seq virt-specifier
ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers & VS,bool IsInterface)1880 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
1881 bool IsInterface) {
1882 while (true) {
1883 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
1884 if (Specifier == VirtSpecifiers::VS_None)
1885 return;
1886
1887 // C++ [class.mem]p8:
1888 // A virt-specifier-seq shall contain at most one of each virt-specifier.
1889 const char *PrevSpec = nullptr;
1890 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
1891 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
1892 << PrevSpec
1893 << FixItHint::CreateRemoval(Tok.getLocation());
1894
1895 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
1896 Specifier == VirtSpecifiers::VS_Sealed)) {
1897 Diag(Tok.getLocation(), diag::err_override_control_interface)
1898 << VirtSpecifiers::getSpecifierName(Specifier);
1899 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
1900 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
1901 } else {
1902 Diag(Tok.getLocation(),
1903 getLangOpts().CPlusPlus11
1904 ? diag::warn_cxx98_compat_override_control_keyword
1905 : diag::ext_override_control_keyword)
1906 << VirtSpecifiers::getSpecifierName(Specifier);
1907 }
1908 ConsumeToken();
1909 }
1910 }
1911
1912 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
1913 /// 'final' or Microsoft 'sealed' contextual keyword.
isCXX11FinalKeyword() const1914 bool Parser::isCXX11FinalKeyword() const {
1915 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
1916 return Specifier == VirtSpecifiers::VS_Final ||
1917 Specifier == VirtSpecifiers::VS_Sealed;
1918 }
1919
1920 /// \brief Parse a C++ member-declarator up to, but not including, the optional
1921 /// brace-or-equal-initializer or pure-specifier.
ParseCXXMemberDeclaratorBeforeInitializer(Declarator & DeclaratorInfo,VirtSpecifiers & VS,ExprResult & BitfieldSize,LateParsedAttrList & LateParsedAttrs)1922 void Parser::ParseCXXMemberDeclaratorBeforeInitializer(
1923 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
1924 LateParsedAttrList &LateParsedAttrs) {
1925 // member-declarator:
1926 // declarator pure-specifier[opt]
1927 // declarator brace-or-equal-initializer[opt]
1928 // identifier[opt] ':' constant-expression
1929 if (Tok.isNot(tok::colon)) {
1930 // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it
1931 // is a bitfield.
1932 // FIXME: This should only apply when parsing the id-expression (see
1933 // PR18587).
1934 ColonProtectionRAIIObject X(*this);
1935 ParseDeclarator(DeclaratorInfo);
1936 }
1937
1938 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
1939 BitfieldSize = ParseConstantExpression();
1940 if (BitfieldSize.isInvalid())
1941 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
1942 } else
1943 ParseOptionalCXX11VirtSpecifierSeq(VS, getCurrentClass().IsInterface);
1944
1945 // If a simple-asm-expr is present, parse it.
1946 if (Tok.is(tok::kw_asm)) {
1947 SourceLocation Loc;
1948 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1949 if (AsmLabel.isInvalid())
1950 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
1951
1952 DeclaratorInfo.setAsmLabel(AsmLabel.get());
1953 DeclaratorInfo.SetRangeEnd(Loc);
1954 }
1955
1956 // If attributes exist after the declarator, but before an '{', parse them.
1957 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
1958
1959 // For compatibility with code written to older Clang, also accept a
1960 // virt-specifier *after* the GNU attributes.
1961 // FIXME: If we saw any attributes that are known to GCC followed by a
1962 // virt-specifier, issue a GCC-compat warning.
1963 if (BitfieldSize.isUnset() && VS.isUnset())
1964 ParseOptionalCXX11VirtSpecifierSeq(VS, getCurrentClass().IsInterface);
1965 }
1966
1967 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
1968 ///
1969 /// member-declaration:
1970 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
1971 /// function-definition ';'[opt]
1972 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
1973 /// using-declaration [TODO]
1974 /// [C++0x] static_assert-declaration
1975 /// template-declaration
1976 /// [GNU] '__extension__' member-declaration
1977 ///
1978 /// member-declarator-list:
1979 /// member-declarator
1980 /// member-declarator-list ',' member-declarator
1981 ///
1982 /// member-declarator:
1983 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
1984 /// declarator constant-initializer[opt]
1985 /// [C++11] declarator brace-or-equal-initializer[opt]
1986 /// identifier[opt] ':' constant-expression
1987 ///
1988 /// virt-specifier-seq:
1989 /// virt-specifier
1990 /// virt-specifier-seq virt-specifier
1991 ///
1992 /// virt-specifier:
1993 /// override
1994 /// final
1995 /// [MS] sealed
1996 ///
1997 /// pure-specifier:
1998 /// '= 0'
1999 ///
2000 /// constant-initializer:
2001 /// '=' constant-expression
2002 ///
ParseCXXClassMemberDeclaration(AccessSpecifier AS,AttributeList * AccessAttrs,const ParsedTemplateInfo & TemplateInfo,ParsingDeclRAIIObject * TemplateDiags)2003 void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2004 AttributeList *AccessAttrs,
2005 const ParsedTemplateInfo &TemplateInfo,
2006 ParsingDeclRAIIObject *TemplateDiags) {
2007 if (Tok.is(tok::at)) {
2008 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
2009 Diag(Tok, diag::err_at_defs_cxx);
2010 else
2011 Diag(Tok, diag::err_at_in_class);
2012
2013 ConsumeToken();
2014 SkipUntil(tok::r_brace, StopAtSemi);
2015 return;
2016 }
2017
2018 // Access declarations.
2019 bool MalformedTypeSpec = false;
2020 if (!TemplateInfo.Kind &&
2021 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon))) {
2022 if (TryAnnotateCXXScopeToken())
2023 MalformedTypeSpec = true;
2024
2025 bool isAccessDecl;
2026 if (Tok.isNot(tok::annot_cxxscope))
2027 isAccessDecl = false;
2028 else if (NextToken().is(tok::identifier))
2029 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2030 else
2031 isAccessDecl = NextToken().is(tok::kw_operator);
2032
2033 if (isAccessDecl) {
2034 // Collect the scope specifier token we annotated earlier.
2035 CXXScopeSpec SS;
2036 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
2037 /*EnteringContext=*/false);
2038
2039 // Try to parse an unqualified-id.
2040 SourceLocation TemplateKWLoc;
2041 UnqualifiedId Name;
2042 if (ParseUnqualifiedId(SS, false, true, true, ParsedType(),
2043 TemplateKWLoc, Name)) {
2044 SkipUntil(tok::semi);
2045 return;
2046 }
2047
2048 // TODO: recover from mistakenly-qualified operator declarations.
2049 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2050 "access declaration")) {
2051 SkipUntil(tok::semi);
2052 return;
2053 }
2054
2055 Actions.ActOnUsingDeclaration(getCurScope(), AS,
2056 /* HasUsingKeyword */ false,
2057 SourceLocation(),
2058 SS, Name,
2059 /* AttrList */ nullptr,
2060 /* HasTypenameKeyword */ false,
2061 SourceLocation());
2062 return;
2063 }
2064 }
2065
2066 // static_assert-declaration
2067 if (Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) {
2068 // FIXME: Check for templates
2069 SourceLocation DeclEnd;
2070 ParseStaticAssertDeclaration(DeclEnd);
2071 return;
2072 }
2073
2074 if (Tok.is(tok::kw_template)) {
2075 assert(!TemplateInfo.TemplateParams &&
2076 "Nested template improperly parsed?");
2077 SourceLocation DeclEnd;
2078 ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
2079 AS, AccessAttrs);
2080 return;
2081 }
2082
2083 // Handle: member-declaration ::= '__extension__' member-declaration
2084 if (Tok.is(tok::kw___extension__)) {
2085 // __extension__ silences extension warnings in the subexpression.
2086 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2087 ConsumeToken();
2088 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2089 TemplateInfo, TemplateDiags);
2090 }
2091
2092 ParsedAttributesWithRange attrs(AttrFactory);
2093 ParsedAttributesWithRange FnAttrs(AttrFactory);
2094 // Optional C++11 attribute-specifier
2095 MaybeParseCXX11Attributes(attrs);
2096 // We need to keep these attributes for future diagnostic
2097 // before they are taken over by declaration specifier.
2098 FnAttrs.addAll(attrs.getList());
2099 FnAttrs.Range = attrs.Range;
2100
2101 MaybeParseMicrosoftAttributes(attrs);
2102
2103 if (Tok.is(tok::kw_using)) {
2104 ProhibitAttributes(attrs);
2105
2106 // Eat 'using'.
2107 SourceLocation UsingLoc = ConsumeToken();
2108
2109 if (Tok.is(tok::kw_namespace)) {
2110 Diag(UsingLoc, diag::err_using_namespace_in_class);
2111 SkipUntil(tok::semi, StopBeforeMatch);
2112 } else {
2113 SourceLocation DeclEnd;
2114 // Otherwise, it must be a using-declaration or an alias-declaration.
2115 ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
2116 UsingLoc, DeclEnd, AS);
2117 }
2118 return;
2119 }
2120
2121 // Hold late-parsed attributes so we can attach a Decl to them later.
2122 LateParsedAttrList CommonLateParsedAttrs;
2123
2124 // decl-specifier-seq:
2125 // Parse the common declaration-specifiers piece.
2126 ParsingDeclSpec DS(*this, TemplateDiags);
2127 DS.takeAttributesFrom(attrs);
2128 if (MalformedTypeSpec)
2129 DS.SetTypeSpecError();
2130
2131 {
2132 // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it
2133 // is a bitfield.
2134 ColonProtectionRAIIObject X(*this);
2135 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2136 &CommonLateParsedAttrs);
2137 }
2138
2139 // If we had a free-standing type definition with a missing semicolon, we
2140 // may get this far before the problem becomes obvious.
2141 if (DS.hasTagDefinition() &&
2142 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2143 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2144 &CommonLateParsedAttrs))
2145 return;
2146
2147 MultiTemplateParamsArg TemplateParams(
2148 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2149 : nullptr,
2150 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2151
2152 if (TryConsumeToken(tok::semi)) {
2153 if (DS.isFriendSpecified())
2154 ProhibitAttributes(FnAttrs);
2155
2156 Decl *TheDecl =
2157 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams);
2158 DS.complete(TheDecl);
2159 return;
2160 }
2161
2162 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
2163 VirtSpecifiers VS;
2164
2165 // Hold late-parsed attributes so we can attach a Decl to them later.
2166 LateParsedAttrList LateParsedAttrs;
2167
2168 SourceLocation EqualLoc;
2169 bool HasInitializer = false;
2170 ExprResult Init;
2171
2172 SmallVector<Decl *, 8> DeclsInGroup;
2173 ExprResult BitfieldSize;
2174 bool ExpectSemi = true;
2175
2176 // Parse the first declarator.
2177 ParseCXXMemberDeclaratorBeforeInitializer(DeclaratorInfo, VS, BitfieldSize,
2178 LateParsedAttrs);
2179
2180 // If this has neither a name nor a bit width, something has gone seriously
2181 // wrong. Skip until the semi-colon or }.
2182 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2183 // If so, skip until the semi-colon or a }.
2184 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2185 TryConsumeToken(tok::semi);
2186 return;
2187 }
2188
2189 // Check for a member function definition.
2190 if (BitfieldSize.isUnset()) {
2191 // MSVC permits pure specifier on inline functions defined at class scope.
2192 // Hence check for =0 before checking for function definition.
2193 if (getLangOpts().MicrosoftExt && Tok.is(tok::equal) &&
2194 DeclaratorInfo.isFunctionDeclarator() &&
2195 NextToken().is(tok::numeric_constant)) {
2196 EqualLoc = ConsumeToken();
2197 Init = ParseInitializer();
2198 if (Init.isInvalid())
2199 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2200 else
2201 HasInitializer = true;
2202 }
2203
2204 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2205 // function-definition:
2206 //
2207 // In C++11, a non-function declarator followed by an open brace is a
2208 // braced-init-list for an in-class member initialization, not an
2209 // erroneous function definition.
2210 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2211 DefinitionKind = FDK_Definition;
2212 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2213 if (Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
2214 DefinitionKind = FDK_Definition;
2215 } else if (Tok.is(tok::equal)) {
2216 const Token &KW = NextToken();
2217 if (KW.is(tok::kw_default))
2218 DefinitionKind = FDK_Defaulted;
2219 else if (KW.is(tok::kw_delete))
2220 DefinitionKind = FDK_Deleted;
2221 }
2222 }
2223
2224 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2225 // to a friend declaration, that declaration shall be a definition.
2226 if (DeclaratorInfo.isFunctionDeclarator() &&
2227 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2228 // Diagnose attributes that appear before decl specifier:
2229 // [[]] friend int foo();
2230 ProhibitAttributes(FnAttrs);
2231 }
2232
2233 if (DefinitionKind) {
2234 if (!DeclaratorInfo.isFunctionDeclarator()) {
2235 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2236 ConsumeBrace();
2237 SkipUntil(tok::r_brace);
2238
2239 // Consume the optional ';'
2240 TryConsumeToken(tok::semi);
2241
2242 return;
2243 }
2244
2245 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2246 Diag(DeclaratorInfo.getIdentifierLoc(),
2247 diag::err_function_declared_typedef);
2248
2249 // Recover by treating the 'typedef' as spurious.
2250 DS.ClearStorageClassSpecs();
2251 }
2252
2253 Decl *FunDecl =
2254 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2255 VS, DefinitionKind, Init);
2256
2257 if (FunDecl) {
2258 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2259 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2260 }
2261 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2262 LateParsedAttrs[i]->addDecl(FunDecl);
2263 }
2264 }
2265 LateParsedAttrs.clear();
2266
2267 // Consume the ';' - it's optional unless we have a delete or default
2268 if (Tok.is(tok::semi))
2269 ConsumeExtraSemi(AfterMemberFunctionDefinition);
2270
2271 return;
2272 }
2273 }
2274
2275 // member-declarator-list:
2276 // member-declarator
2277 // member-declarator-list ',' member-declarator
2278
2279 while (1) {
2280 InClassInitStyle HasInClassInit = ICIS_NoInit;
2281 if ((Tok.is(tok::equal) || Tok.is(tok::l_brace)) && !HasInitializer) {
2282 if (BitfieldSize.get()) {
2283 Diag(Tok, diag::err_bitfield_member_init);
2284 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2285 } else {
2286 HasInitializer = true;
2287 if (!DeclaratorInfo.isDeclarationOfFunction() &&
2288 DeclaratorInfo.getDeclSpec().getStorageClassSpec()
2289 != DeclSpec::SCS_typedef)
2290 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2291 }
2292 }
2293
2294 // NOTE: If Sema is the Action module and declarator is an instance field,
2295 // this call will *not* return the created decl; It will return null.
2296 // See Sema::ActOnCXXMemberDeclarator for details.
2297
2298 NamedDecl *ThisDecl = nullptr;
2299 if (DS.isFriendSpecified()) {
2300 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2301 // to a friend declaration, that declaration shall be a definition.
2302 //
2303 // Diagnose attributes that appear in a friend member function declarator:
2304 // friend int foo [[]] ();
2305 SmallVector<SourceRange, 4> Ranges;
2306 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2307 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2308 E = Ranges.end(); I != E; ++I)
2309 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
2310
2311 // TODO: handle initializers, VS, bitfields, 'delete'
2312 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2313 TemplateParams);
2314 } else {
2315 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2316 DeclaratorInfo,
2317 TemplateParams,
2318 BitfieldSize.get(),
2319 VS, HasInClassInit);
2320
2321 if (VarTemplateDecl *VT =
2322 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
2323 // Re-direct this decl to refer to the templated decl so that we can
2324 // initialize it.
2325 ThisDecl = VT->getTemplatedDecl();
2326
2327 if (ThisDecl && AccessAttrs)
2328 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
2329 }
2330
2331 // Handle the initializer.
2332 if (HasInClassInit != ICIS_NoInit &&
2333 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2334 DeclSpec::SCS_static) {
2335 // The initializer was deferred; parse it and cache the tokens.
2336 Diag(Tok, getLangOpts().CPlusPlus11
2337 ? diag::warn_cxx98_compat_nonstatic_member_init
2338 : diag::ext_nonstatic_member_init);
2339
2340 if (DeclaratorInfo.isArrayOfUnknownBound()) {
2341 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2342 // declarator is followed by an initializer.
2343 //
2344 // A brace-or-equal-initializer for a member-declarator is not an
2345 // initializer in the grammar, so this is ill-formed.
2346 Diag(Tok, diag::err_incomplete_array_member_init);
2347 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2348
2349 // Avoid later warnings about a class member of incomplete type.
2350 if (ThisDecl)
2351 ThisDecl->setInvalidDecl();
2352 } else
2353 ParseCXXNonStaticMemberInitializer(ThisDecl);
2354 } else if (HasInitializer) {
2355 // Normal initializer.
2356 if (!Init.isUsable())
2357 Init = ParseCXXMemberInitializer(
2358 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2359
2360 if (Init.isInvalid())
2361 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2362 else if (ThisDecl)
2363 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
2364 DS.containsPlaceholderType());
2365 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
2366 // No initializer.
2367 Actions.ActOnUninitializedDecl(ThisDecl, DS.containsPlaceholderType());
2368
2369 if (ThisDecl) {
2370 if (!ThisDecl->isInvalidDecl()) {
2371 // Set the Decl for any late parsed attributes
2372 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2373 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2374
2375 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2376 LateParsedAttrs[i]->addDecl(ThisDecl);
2377 }
2378 Actions.FinalizeDeclaration(ThisDecl);
2379 DeclsInGroup.push_back(ThisDecl);
2380
2381 if (DeclaratorInfo.isFunctionDeclarator() &&
2382 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2383 DeclSpec::SCS_typedef)
2384 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2385 }
2386 LateParsedAttrs.clear();
2387
2388 DeclaratorInfo.complete(ThisDecl);
2389
2390 // If we don't have a comma, it is either the end of the list (a ';')
2391 // or an error, bail out.
2392 SourceLocation CommaLoc;
2393 if (!TryConsumeToken(tok::comma, CommaLoc))
2394 break;
2395
2396 if (Tok.isAtStartOfLine() &&
2397 !MightBeDeclarator(Declarator::MemberContext)) {
2398 // This comma was followed by a line-break and something which can't be
2399 // the start of a declarator. The comma was probably a typo for a
2400 // semicolon.
2401 Diag(CommaLoc, diag::err_expected_semi_declaration)
2402 << FixItHint::CreateReplacement(CommaLoc, ";");
2403 ExpectSemi = false;
2404 break;
2405 }
2406
2407 // Parse the next declarator.
2408 DeclaratorInfo.clear();
2409 VS.clear();
2410 BitfieldSize = true;
2411 Init = true;
2412 HasInitializer = false;
2413 DeclaratorInfo.setCommaLoc(CommaLoc);
2414
2415 // GNU attributes are allowed before the second and subsequent declarator.
2416 MaybeParseGNUAttributes(DeclaratorInfo);
2417
2418 ParseCXXMemberDeclaratorBeforeInitializer(DeclaratorInfo, VS, BitfieldSize,
2419 LateParsedAttrs);
2420 }
2421
2422 if (ExpectSemi &&
2423 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2424 // Skip to end of block or statement.
2425 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2426 // If we stopped at a ';', eat it.
2427 TryConsumeToken(tok::semi);
2428 return;
2429 }
2430
2431 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2432 }
2433
2434 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer or
2435 /// pure-specifier. Also detect and reject any attempted defaulted/deleted
2436 /// function definition. The location of the '=', if any, will be placed in
2437 /// EqualLoc.
2438 ///
2439 /// pure-specifier:
2440 /// '= 0'
2441 ///
2442 /// brace-or-equal-initializer:
2443 /// '=' initializer-expression
2444 /// braced-init-list
2445 ///
2446 /// initializer-clause:
2447 /// assignment-expression
2448 /// braced-init-list
2449 ///
2450 /// defaulted/deleted function-definition:
2451 /// '=' 'default'
2452 /// '=' 'delete'
2453 ///
2454 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2455 /// be a constant-expression.
ParseCXXMemberInitializer(Decl * D,bool IsFunction,SourceLocation & EqualLoc)2456 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2457 SourceLocation &EqualLoc) {
2458 assert((Tok.is(tok::equal) || Tok.is(tok::l_brace))
2459 && "Data member initializer not starting with '=' or '{'");
2460
2461 EnterExpressionEvaluationContext Context(Actions,
2462 Sema::PotentiallyEvaluated,
2463 D);
2464 if (TryConsumeToken(tok::equal, EqualLoc)) {
2465 if (Tok.is(tok::kw_delete)) {
2466 // In principle, an initializer of '= delete p;' is legal, but it will
2467 // never type-check. It's better to diagnose it as an ill-formed expression
2468 // than as an ill-formed deleted non-function member.
2469 // An initializer of '= delete p, foo' will never be parsed, because
2470 // a top-level comma always ends the initializer expression.
2471 const Token &Next = NextToken();
2472 if (IsFunction || Next.is(tok::semi) || Next.is(tok::comma) ||
2473 Next.is(tok::eof)) {
2474 if (IsFunction)
2475 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2476 << 1 /* delete */;
2477 else
2478 Diag(ConsumeToken(), diag::err_deleted_non_function);
2479 return ExprError();
2480 }
2481 } else if (Tok.is(tok::kw_default)) {
2482 if (IsFunction)
2483 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2484 << 0 /* default */;
2485 else
2486 Diag(ConsumeToken(), diag::err_default_special_members);
2487 return ExprError();
2488 }
2489
2490 }
2491 return ParseInitializer();
2492 }
2493
2494 /// ParseCXXMemberSpecification - Parse the class definition.
2495 ///
2496 /// member-specification:
2497 /// member-declaration member-specification[opt]
2498 /// access-specifier ':' member-specification[opt]
2499 ///
ParseCXXMemberSpecification(SourceLocation RecordLoc,SourceLocation AttrFixitLoc,ParsedAttributesWithRange & Attrs,unsigned TagType,Decl * TagDecl)2500 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
2501 SourceLocation AttrFixitLoc,
2502 ParsedAttributesWithRange &Attrs,
2503 unsigned TagType, Decl *TagDecl) {
2504 assert((TagType == DeclSpec::TST_struct ||
2505 TagType == DeclSpec::TST_interface ||
2506 TagType == DeclSpec::TST_union ||
2507 TagType == DeclSpec::TST_class) && "Invalid TagType!");
2508
2509 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2510 "parsing struct/union/class body");
2511
2512 // Determine whether this is a non-nested class. Note that local
2513 // classes are *not* considered to be nested classes.
2514 bool NonNestedClass = true;
2515 if (!ClassStack.empty()) {
2516 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
2517 if (S->isClassScope()) {
2518 // We're inside a class scope, so this is a nested class.
2519 NonNestedClass = false;
2520
2521 // The Microsoft extension __interface does not permit nested classes.
2522 if (getCurrentClass().IsInterface) {
2523 Diag(RecordLoc, diag::err_invalid_member_in_interface)
2524 << /*ErrorType=*/6
2525 << (isa<NamedDecl>(TagDecl)
2526 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
2527 : "(anonymous)");
2528 }
2529 break;
2530 }
2531
2532 if ((S->getFlags() & Scope::FnScope)) {
2533 // If we're in a function or function template declared in the
2534 // body of a class, then this is a local class rather than a
2535 // nested class.
2536 const Scope *Parent = S->getParent();
2537 if (Parent->isTemplateParamScope())
2538 Parent = Parent->getParent();
2539 if (Parent->isClassScope())
2540 break;
2541 }
2542 }
2543 }
2544
2545 // Enter a scope for the class.
2546 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2547
2548 // Note that we are parsing a new (potentially-nested) class definition.
2549 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
2550 TagType == DeclSpec::TST_interface);
2551
2552 if (TagDecl)
2553 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2554
2555 SourceLocation FinalLoc;
2556 bool IsFinalSpelledSealed = false;
2557
2558 // Parse the optional 'final' keyword.
2559 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2560 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
2561 assert((Specifier == VirtSpecifiers::VS_Final ||
2562 Specifier == VirtSpecifiers::VS_Sealed) &&
2563 "not a class definition");
2564 FinalLoc = ConsumeToken();
2565 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
2566
2567 if (TagType == DeclSpec::TST_interface)
2568 Diag(FinalLoc, diag::err_override_control_interface)
2569 << VirtSpecifiers::getSpecifierName(Specifier);
2570 else if (Specifier == VirtSpecifiers::VS_Final)
2571 Diag(FinalLoc, getLangOpts().CPlusPlus11
2572 ? diag::warn_cxx98_compat_override_control_keyword
2573 : diag::ext_override_control_keyword)
2574 << VirtSpecifiers::getSpecifierName(Specifier);
2575 else if (Specifier == VirtSpecifiers::VS_Sealed)
2576 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
2577
2578 // Parse any C++11 attributes after 'final' keyword.
2579 // These attributes are not allowed to appear here,
2580 // and the only possible place for them to appertain
2581 // to the class would be between class-key and class-name.
2582 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2583 }
2584
2585 if (Tok.is(tok::colon)) {
2586 ParseBaseClause(TagDecl);
2587
2588 if (!Tok.is(tok::l_brace)) {
2589 Diag(Tok, diag::err_expected_lbrace_after_base_specifiers);
2590
2591 if (TagDecl)
2592 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
2593 return;
2594 }
2595 }
2596
2597 assert(Tok.is(tok::l_brace));
2598 BalancedDelimiterTracker T(*this, tok::l_brace);
2599 T.consumeOpen();
2600
2601 if (TagDecl)
2602 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
2603 IsFinalSpelledSealed,
2604 T.getOpenLocation());
2605
2606 // C++ 11p3: Members of a class defined with the keyword class are private
2607 // by default. Members of a class defined with the keywords struct or union
2608 // are public by default.
2609 AccessSpecifier CurAS;
2610 if (TagType == DeclSpec::TST_class)
2611 CurAS = AS_private;
2612 else
2613 CurAS = AS_public;
2614 ParsedAttributes AccessAttrs(AttrFactory);
2615
2616 if (TagDecl) {
2617 // While we still have something to read, read the member-declarations.
2618 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2619 // Each iteration of this loop reads one member-declaration.
2620
2621 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
2622 Tok.is(tok::kw___if_not_exists))) {
2623 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
2624 continue;
2625 }
2626
2627 // Check for extraneous top-level semicolon.
2628 if (Tok.is(tok::semi)) {
2629 ConsumeExtraSemi(InsideStruct, TagType);
2630 continue;
2631 }
2632
2633 if (Tok.is(tok::annot_pragma_vis)) {
2634 HandlePragmaVisibility();
2635 continue;
2636 }
2637
2638 if (Tok.is(tok::annot_pragma_pack)) {
2639 HandlePragmaPack();
2640 continue;
2641 }
2642
2643 if (Tok.is(tok::annot_pragma_align)) {
2644 HandlePragmaAlign();
2645 continue;
2646 }
2647
2648 if (Tok.is(tok::annot_pragma_openmp)) {
2649 ParseOpenMPDeclarativeDirective();
2650 continue;
2651 }
2652
2653 if (Tok.is(tok::annot_pragma_ms_pointers_to_members)) {
2654 HandlePragmaMSPointersToMembers();
2655 continue;
2656 }
2657
2658 if (Tok.is(tok::annot_pragma_ms_pragma)) {
2659 HandlePragmaMSPragma();
2660 continue;
2661 }
2662
2663 // If we see a namespace here, a close brace was missing somewhere.
2664 if (Tok.is(tok::kw_namespace)) {
2665 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
2666 break;
2667 }
2668
2669 AccessSpecifier AS = getAccessSpecifierIfPresent();
2670 if (AS != AS_none) {
2671 // Current token is a C++ access specifier.
2672 CurAS = AS;
2673 SourceLocation ASLoc = Tok.getLocation();
2674 unsigned TokLength = Tok.getLength();
2675 ConsumeToken();
2676 AccessAttrs.clear();
2677 MaybeParseGNUAttributes(AccessAttrs);
2678
2679 SourceLocation EndLoc;
2680 if (TryConsumeToken(tok::colon, EndLoc)) {
2681 } else if (TryConsumeToken(tok::semi, EndLoc)) {
2682 Diag(EndLoc, diag::err_expected)
2683 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
2684 } else {
2685 EndLoc = ASLoc.getLocWithOffset(TokLength);
2686 Diag(EndLoc, diag::err_expected)
2687 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
2688 }
2689
2690 // The Microsoft extension __interface does not permit non-public
2691 // access specifiers.
2692 if (TagType == DeclSpec::TST_interface && CurAS != AS_public) {
2693 Diag(ASLoc, diag::err_access_specifier_interface)
2694 << (CurAS == AS_protected);
2695 }
2696
2697 if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc,
2698 AccessAttrs.getList())) {
2699 // found another attribute than only annotations
2700 AccessAttrs.clear();
2701 }
2702
2703 continue;
2704 }
2705
2706 // Parse all the comma separated declarators.
2707 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs.getList());
2708 }
2709
2710 T.consumeClose();
2711 } else {
2712 SkipUntil(tok::r_brace);
2713 }
2714
2715 // If attributes exist after class contents, parse them.
2716 ParsedAttributes attrs(AttrFactory);
2717 MaybeParseGNUAttributes(attrs);
2718
2719 if (TagDecl)
2720 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
2721 T.getOpenLocation(),
2722 T.getCloseLocation(),
2723 attrs.getList());
2724
2725 // C++11 [class.mem]p2:
2726 // Within the class member-specification, the class is regarded as complete
2727 // within function bodies, default arguments, and
2728 // brace-or-equal-initializers for non-static data members (including such
2729 // things in nested classes).
2730 if (TagDecl && NonNestedClass) {
2731 // We are not inside a nested class. This class and its nested classes
2732 // are complete and we can parse the delayed portions of method
2733 // declarations and the lexed inline method definitions, along with any
2734 // delayed attributes.
2735 SourceLocation SavedPrevTokLocation = PrevTokLocation;
2736 ParseLexedAttributes(getCurrentClass());
2737 ParseLexedMethodDeclarations(getCurrentClass());
2738
2739 // We've finished with all pending member declarations.
2740 Actions.ActOnFinishCXXMemberDecls();
2741
2742 ParseLexedMemberInitializers(getCurrentClass());
2743 ParseLexedMethodDefs(getCurrentClass());
2744 PrevTokLocation = SavedPrevTokLocation;
2745 }
2746
2747 if (TagDecl)
2748 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
2749 T.getCloseLocation());
2750
2751 // Leave the class scope.
2752 ParsingDef.Pop();
2753 ClassScope.Exit();
2754 }
2755
DiagnoseUnexpectedNamespace(NamedDecl * D)2756 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
2757 assert(Tok.is(tok::kw_namespace));
2758
2759 // FIXME: Suggest where the close brace should have gone by looking
2760 // at indentation changes within the definition body.
2761 Diag(D->getLocation(),
2762 diag::err_missing_end_of_definition) << D;
2763 Diag(Tok.getLocation(),
2764 diag::note_missing_end_of_definition_before) << D;
2765
2766 // Push '};' onto the token stream to recover.
2767 PP.EnterToken(Tok);
2768
2769 Tok.startToken();
2770 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
2771 Tok.setKind(tok::semi);
2772 PP.EnterToken(Tok);
2773
2774 Tok.setKind(tok::r_brace);
2775 }
2776
2777 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
2778 /// which explicitly initializes the members or base classes of a
2779 /// class (C++ [class.base.init]). For example, the three initializers
2780 /// after the ':' in the Derived constructor below:
2781 ///
2782 /// @code
2783 /// class Base { };
2784 /// class Derived : Base {
2785 /// int x;
2786 /// float f;
2787 /// public:
2788 /// Derived(float f) : Base(), x(17), f(f) { }
2789 /// };
2790 /// @endcode
2791 ///
2792 /// [C++] ctor-initializer:
2793 /// ':' mem-initializer-list
2794 ///
2795 /// [C++] mem-initializer-list:
2796 /// mem-initializer ...[opt]
2797 /// mem-initializer ...[opt] , mem-initializer-list
ParseConstructorInitializer(Decl * ConstructorDecl)2798 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
2799 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
2800
2801 // Poison the SEH identifiers so they are flagged as illegal in constructor initializers
2802 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
2803 SourceLocation ColonLoc = ConsumeToken();
2804
2805 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
2806 bool AnyErrors = false;
2807
2808 do {
2809 if (Tok.is(tok::code_completion)) {
2810 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
2811 MemInitializers);
2812 return cutOffParsing();
2813 } else {
2814 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
2815 if (!MemInit.isInvalid())
2816 MemInitializers.push_back(MemInit.get());
2817 else
2818 AnyErrors = true;
2819 }
2820
2821 if (Tok.is(tok::comma))
2822 ConsumeToken();
2823 else if (Tok.is(tok::l_brace))
2824 break;
2825 // If the next token looks like a base or member initializer, assume that
2826 // we're just missing a comma.
2827 else if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) {
2828 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
2829 Diag(Loc, diag::err_ctor_init_missing_comma)
2830 << FixItHint::CreateInsertion(Loc, ", ");
2831 } else {
2832 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2833 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
2834 << tok::comma;
2835 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2836 break;
2837 }
2838 } while (true);
2839
2840 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
2841 AnyErrors);
2842 }
2843
2844 /// ParseMemInitializer - Parse a C++ member initializer, which is
2845 /// part of a constructor initializer that explicitly initializes one
2846 /// member or base class (C++ [class.base.init]). See
2847 /// ParseConstructorInitializer for an example.
2848 ///
2849 /// [C++] mem-initializer:
2850 /// mem-initializer-id '(' expression-list[opt] ')'
2851 /// [C++0x] mem-initializer-id braced-init-list
2852 ///
2853 /// [C++] mem-initializer-id:
2854 /// '::'[opt] nested-name-specifier[opt] class-name
2855 /// identifier
ParseMemInitializer(Decl * ConstructorDecl)2856 Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
2857 // parse '::'[opt] nested-name-specifier[opt]
2858 CXXScopeSpec SS;
2859 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
2860 ParsedType TemplateTypeTy;
2861 if (Tok.is(tok::annot_template_id)) {
2862 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2863 if (TemplateId->Kind == TNK_Type_template ||
2864 TemplateId->Kind == TNK_Dependent_template_name) {
2865 AnnotateTemplateIdTokenAsType();
2866 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
2867 TemplateTypeTy = getTypeAnnotation(Tok);
2868 }
2869 }
2870 // Uses of decltype will already have been converted to annot_decltype by
2871 // ParseOptionalCXXScopeSpecifier at this point.
2872 if (!TemplateTypeTy && Tok.isNot(tok::identifier)
2873 && Tok.isNot(tok::annot_decltype)) {
2874 Diag(Tok, diag::err_expected_member_or_base_name);
2875 return true;
2876 }
2877
2878 IdentifierInfo *II = nullptr;
2879 DeclSpec DS(AttrFactory);
2880 SourceLocation IdLoc = Tok.getLocation();
2881 if (Tok.is(tok::annot_decltype)) {
2882 // Get the decltype expression, if there is one.
2883 ParseDecltypeSpecifier(DS);
2884 } else {
2885 if (Tok.is(tok::identifier))
2886 // Get the identifier. This may be a member name or a class name,
2887 // but we'll let the semantic analysis determine which it is.
2888 II = Tok.getIdentifierInfo();
2889 ConsumeToken();
2890 }
2891
2892
2893 // Parse the '('.
2894 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2895 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2896
2897 ExprResult InitList = ParseBraceInitializer();
2898 if (InitList.isInvalid())
2899 return true;
2900
2901 SourceLocation EllipsisLoc;
2902 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2903
2904 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
2905 TemplateTypeTy, DS, IdLoc,
2906 InitList.get(), EllipsisLoc);
2907 } else if(Tok.is(tok::l_paren)) {
2908 BalancedDelimiterTracker T(*this, tok::l_paren);
2909 T.consumeOpen();
2910
2911 // Parse the optional expression-list.
2912 ExprVector ArgExprs;
2913 CommaLocsTy CommaLocs;
2914 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
2915 SkipUntil(tok::r_paren, StopAtSemi);
2916 return true;
2917 }
2918
2919 T.consumeClose();
2920
2921 SourceLocation EllipsisLoc;
2922 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2923
2924 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
2925 TemplateTypeTy, DS, IdLoc,
2926 T.getOpenLocation(), ArgExprs,
2927 T.getCloseLocation(), EllipsisLoc);
2928 }
2929
2930 if (getLangOpts().CPlusPlus11)
2931 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
2932 else
2933 return Diag(Tok, diag::err_expected) << tok::l_paren;
2934 }
2935
2936 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
2937 ///
2938 /// exception-specification:
2939 /// dynamic-exception-specification
2940 /// noexcept-specification
2941 ///
2942 /// noexcept-specification:
2943 /// 'noexcept'
2944 /// 'noexcept' '(' constant-expression ')'
2945 ExceptionSpecificationType
tryParseExceptionSpecification(SourceRange & SpecificationRange,SmallVectorImpl<ParsedType> & DynamicExceptions,SmallVectorImpl<SourceRange> & DynamicExceptionRanges,ExprResult & NoexceptExpr)2946 Parser::tryParseExceptionSpecification(
2947 SourceRange &SpecificationRange,
2948 SmallVectorImpl<ParsedType> &DynamicExceptions,
2949 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
2950 ExprResult &NoexceptExpr) {
2951 ExceptionSpecificationType Result = EST_None;
2952
2953 // See if there's a dynamic specification.
2954 if (Tok.is(tok::kw_throw)) {
2955 Result = ParseDynamicExceptionSpecification(SpecificationRange,
2956 DynamicExceptions,
2957 DynamicExceptionRanges);
2958 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
2959 "Produced different number of exception types and ranges.");
2960 }
2961
2962 // If there's no noexcept specification, we're done.
2963 if (Tok.isNot(tok::kw_noexcept))
2964 return Result;
2965
2966 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
2967
2968 // If we already had a dynamic specification, parse the noexcept for,
2969 // recovery, but emit a diagnostic and don't store the results.
2970 SourceRange NoexceptRange;
2971 ExceptionSpecificationType NoexceptType = EST_None;
2972
2973 SourceLocation KeywordLoc = ConsumeToken();
2974 if (Tok.is(tok::l_paren)) {
2975 // There is an argument.
2976 BalancedDelimiterTracker T(*this, tok::l_paren);
2977 T.consumeOpen();
2978 NoexceptType = EST_ComputedNoexcept;
2979 NoexceptExpr = ParseConstantExpression();
2980 // The argument must be contextually convertible to bool. We use
2981 // ActOnBooleanCondition for this purpose.
2982 if (!NoexceptExpr.isInvalid())
2983 NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc,
2984 NoexceptExpr.get());
2985 T.consumeClose();
2986 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
2987 } else {
2988 // There is no argument.
2989 NoexceptType = EST_BasicNoexcept;
2990 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
2991 }
2992
2993 if (Result == EST_None) {
2994 SpecificationRange = NoexceptRange;
2995 Result = NoexceptType;
2996
2997 // If there's a dynamic specification after a noexcept specification,
2998 // parse that and ignore the results.
2999 if (Tok.is(tok::kw_throw)) {
3000 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3001 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3002 DynamicExceptionRanges);
3003 }
3004 } else {
3005 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3006 }
3007
3008 return Result;
3009 }
3010
diagnoseDynamicExceptionSpecification(Parser & P,const SourceRange & Range,bool IsNoexcept)3011 static void diagnoseDynamicExceptionSpecification(
3012 Parser &P, const SourceRange &Range, bool IsNoexcept) {
3013 if (P.getLangOpts().CPlusPlus11) {
3014 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
3015 P.Diag(Range.getBegin(), diag::warn_exception_spec_deprecated) << Range;
3016 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3017 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3018 }
3019 }
3020
3021 /// ParseDynamicExceptionSpecification - Parse a C++
3022 /// dynamic-exception-specification (C++ [except.spec]).
3023 ///
3024 /// dynamic-exception-specification:
3025 /// 'throw' '(' type-id-list [opt] ')'
3026 /// [MS] 'throw' '(' '...' ')'
3027 ///
3028 /// type-id-list:
3029 /// type-id ... [opt]
3030 /// type-id-list ',' type-id ... [opt]
3031 ///
ParseDynamicExceptionSpecification(SourceRange & SpecificationRange,SmallVectorImpl<ParsedType> & Exceptions,SmallVectorImpl<SourceRange> & Ranges)3032 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3033 SourceRange &SpecificationRange,
3034 SmallVectorImpl<ParsedType> &Exceptions,
3035 SmallVectorImpl<SourceRange> &Ranges) {
3036 assert(Tok.is(tok::kw_throw) && "expected throw");
3037
3038 SpecificationRange.setBegin(ConsumeToken());
3039 BalancedDelimiterTracker T(*this, tok::l_paren);
3040 if (T.consumeOpen()) {
3041 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3042 SpecificationRange.setEnd(SpecificationRange.getBegin());
3043 return EST_DynamicNone;
3044 }
3045
3046 // Parse throw(...), a Microsoft extension that means "this function
3047 // can throw anything".
3048 if (Tok.is(tok::ellipsis)) {
3049 SourceLocation EllipsisLoc = ConsumeToken();
3050 if (!getLangOpts().MicrosoftExt)
3051 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3052 T.consumeClose();
3053 SpecificationRange.setEnd(T.getCloseLocation());
3054 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3055 return EST_MSAny;
3056 }
3057
3058 // Parse the sequence of type-ids.
3059 SourceRange Range;
3060 while (Tok.isNot(tok::r_paren)) {
3061 TypeResult Res(ParseTypeName(&Range));
3062
3063 if (Tok.is(tok::ellipsis)) {
3064 // C++0x [temp.variadic]p5:
3065 // - In a dynamic-exception-specification (15.4); the pattern is a
3066 // type-id.
3067 SourceLocation Ellipsis = ConsumeToken();
3068 Range.setEnd(Ellipsis);
3069 if (!Res.isInvalid())
3070 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3071 }
3072
3073 if (!Res.isInvalid()) {
3074 Exceptions.push_back(Res.get());
3075 Ranges.push_back(Range);
3076 }
3077
3078 if (!TryConsumeToken(tok::comma))
3079 break;
3080 }
3081
3082 T.consumeClose();
3083 SpecificationRange.setEnd(T.getCloseLocation());
3084 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3085 Exceptions.empty());
3086 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
3087 }
3088
3089 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
3090 /// function declaration.
ParseTrailingReturnType(SourceRange & Range)3091 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
3092 assert(Tok.is(tok::arrow) && "expected arrow");
3093
3094 ConsumeToken();
3095
3096 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
3097 }
3098
3099 /// \brief We have just started parsing the definition of a new class,
3100 /// so push that class onto our stack of classes that is currently
3101 /// being parsed.
3102 Sema::ParsingClassState
PushParsingClass(Decl * ClassDecl,bool NonNestedClass,bool IsInterface)3103 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3104 bool IsInterface) {
3105 assert((NonNestedClass || !ClassStack.empty()) &&
3106 "Nested class without outer class");
3107 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
3108 return Actions.PushParsingClass();
3109 }
3110
3111 /// \brief Deallocate the given parsed class and all of its nested
3112 /// classes.
DeallocateParsedClasses(Parser::ParsingClass * Class)3113 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
3114 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3115 delete Class->LateParsedDeclarations[I];
3116 delete Class;
3117 }
3118
3119 /// \brief Pop the top class of the stack of classes that are
3120 /// currently being parsed.
3121 ///
3122 /// This routine should be called when we have finished parsing the
3123 /// definition of a class, but have not yet popped the Scope
3124 /// associated with the class's definition.
PopParsingClass(Sema::ParsingClassState state)3125 void Parser::PopParsingClass(Sema::ParsingClassState state) {
3126 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3127
3128 Actions.PopParsingClass(state);
3129
3130 ParsingClass *Victim = ClassStack.top();
3131 ClassStack.pop();
3132 if (Victim->TopLevelClass) {
3133 // Deallocate all of the nested classes of this class,
3134 // recursively: we don't need to keep any of this information.
3135 DeallocateParsedClasses(Victim);
3136 return;
3137 }
3138 assert(!ClassStack.empty() && "Missing top-level class?");
3139
3140 if (Victim->LateParsedDeclarations.empty()) {
3141 // The victim is a nested class, but we will not need to perform
3142 // any processing after the definition of this class since it has
3143 // no members whose handling was delayed. Therefore, we can just
3144 // remove this nested class.
3145 DeallocateParsedClasses(Victim);
3146 return;
3147 }
3148
3149 // This nested class has some members that will need to be processed
3150 // after the top-level class is completely defined. Therefore, add
3151 // it to the list of nested classes within its parent.
3152 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3153 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3154 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3155 }
3156
3157 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
3158 ///
3159 /// \return the parsed identifier on success, and 0 if the next token is not an
3160 /// attribute-token.
3161 ///
3162 /// C++11 [dcl.attr.grammar]p3:
3163 /// If a keyword or an alternative token that satisfies the syntactic
3164 /// requirements of an identifier is contained in an attribute-token,
3165 /// it is considered an identifier.
TryParseCXX11AttributeIdentifier(SourceLocation & Loc)3166 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3167 switch (Tok.getKind()) {
3168 default:
3169 // Identifiers and keywords have identifier info attached.
3170 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3171 Loc = ConsumeToken();
3172 return II;
3173 }
3174 return nullptr;
3175
3176 case tok::ampamp: // 'and'
3177 case tok::pipe: // 'bitor'
3178 case tok::pipepipe: // 'or'
3179 case tok::caret: // 'xor'
3180 case tok::tilde: // 'compl'
3181 case tok::amp: // 'bitand'
3182 case tok::ampequal: // 'and_eq'
3183 case tok::pipeequal: // 'or_eq'
3184 case tok::caretequal: // 'xor_eq'
3185 case tok::exclaim: // 'not'
3186 case tok::exclaimequal: // 'not_eq'
3187 // Alternative tokens do not have identifier info, but their spelling
3188 // starts with an alphabetical character.
3189 SmallString<8> SpellingBuf;
3190 StringRef Spelling = PP.getSpelling(Tok.getLocation(), SpellingBuf);
3191 if (isLetter(Spelling[0])) {
3192 Loc = ConsumeToken();
3193 return &PP.getIdentifierTable().get(Spelling);
3194 }
3195 return nullptr;
3196 }
3197 }
3198
IsBuiltInOrStandardCXX11Attribute(IdentifierInfo * AttrName,IdentifierInfo * ScopeName)3199 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3200 IdentifierInfo *ScopeName) {
3201 switch (AttributeList::getKind(AttrName, ScopeName,
3202 AttributeList::AS_CXX11)) {
3203 case AttributeList::AT_CarriesDependency:
3204 case AttributeList::AT_Deprecated:
3205 case AttributeList::AT_FallThrough:
3206 case AttributeList::AT_CXX11NoReturn: {
3207 return true;
3208 }
3209
3210 default:
3211 return false;
3212 }
3213 }
3214
3215 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3216 ///
3217 /// [C++11] attribute-argument-clause:
3218 /// '(' balanced-token-seq ')'
3219 ///
3220 /// [C++11] balanced-token-seq:
3221 /// balanced-token
3222 /// balanced-token-seq balanced-token
3223 ///
3224 /// [C++11] balanced-token:
3225 /// '(' balanced-token-seq ')'
3226 /// '[' balanced-token-seq ']'
3227 /// '{' balanced-token-seq '}'
3228 /// any token but '(', ')', '[', ']', '{', or '}'
ParseCXX11AttributeArgs(IdentifierInfo * AttrName,SourceLocation AttrNameLoc,ParsedAttributes & Attrs,SourceLocation * EndLoc,IdentifierInfo * ScopeName,SourceLocation ScopeLoc)3229 bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3230 SourceLocation AttrNameLoc,
3231 ParsedAttributes &Attrs,
3232 SourceLocation *EndLoc,
3233 IdentifierInfo *ScopeName,
3234 SourceLocation ScopeLoc) {
3235 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
3236 SourceLocation LParenLoc = Tok.getLocation();
3237
3238 // If the attribute isn't known, we will not attempt to parse any
3239 // arguments.
3240 if (!hasAttribute(AttrSyntax::CXX, ScopeName, AttrName,
3241 getTargetInfo().getTriple(), getLangOpts())) {
3242 // Eat the left paren, then skip to the ending right paren.
3243 ConsumeParen();
3244 SkipUntil(tok::r_paren);
3245 return false;
3246 }
3247
3248 if (ScopeName && ScopeName->getName() == "gnu")
3249 // GNU-scoped attributes have some special cases to handle GNU-specific
3250 // behaviors.
3251 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3252 ScopeLoc, AttributeList::AS_CXX11, nullptr);
3253 else {
3254 unsigned NumArgs =
3255 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3256 ScopeName, ScopeLoc, AttributeList::AS_CXX11);
3257
3258 const AttributeList *Attr = Attrs.getList();
3259 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3260 // If the attribute is a standard or built-in attribute and we are
3261 // parsing an argument list, we need to determine whether this attribute
3262 // was allowed to have an argument list (such as [[deprecated]]), and how
3263 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3264 if (Attr->getMaxArgs() && !NumArgs) {
3265 // The attribute was allowed to have arguments, but none were provided
3266 // even though the attribute parsed successfully. This is an error.
3267 // FIXME: This is a good place for a fixit which removes the parens.
3268 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3269 return false;
3270 } else if (!Attr->getMaxArgs()) {
3271 // The attribute parsed successfully, but was not allowed to have any
3272 // arguments. It doesn't matter whether any were provided -- the
3273 // presence of the argument list (even if empty) is diagnosed.
3274 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3275 << AttrName;
3276 return false;
3277 }
3278 }
3279 }
3280 return true;
3281 }
3282
3283 /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier.
3284 ///
3285 /// [C++11] attribute-specifier:
3286 /// '[' '[' attribute-list ']' ']'
3287 /// alignment-specifier
3288 ///
3289 /// [C++11] attribute-list:
3290 /// attribute[opt]
3291 /// attribute-list ',' attribute[opt]
3292 /// attribute '...'
3293 /// attribute-list ',' attribute '...'
3294 ///
3295 /// [C++11] attribute:
3296 /// attribute-token attribute-argument-clause[opt]
3297 ///
3298 /// [C++11] attribute-token:
3299 /// identifier
3300 /// attribute-scoped-token
3301 ///
3302 /// [C++11] attribute-scoped-token:
3303 /// attribute-namespace '::' identifier
3304 ///
3305 /// [C++11] attribute-namespace:
3306 /// identifier
ParseCXX11AttributeSpecifier(ParsedAttributes & attrs,SourceLocation * endLoc)3307 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
3308 SourceLocation *endLoc) {
3309 if (Tok.is(tok::kw_alignas)) {
3310 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
3311 ParseAlignmentSpecifier(attrs, endLoc);
3312 return;
3313 }
3314
3315 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
3316 && "Not a C++11 attribute list");
3317
3318 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3319
3320 ConsumeBracket();
3321 ConsumeBracket();
3322
3323 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3324
3325 while (Tok.isNot(tok::r_square)) {
3326 // attribute not present
3327 if (TryConsumeToken(tok::comma))
3328 continue;
3329
3330 SourceLocation ScopeLoc, AttrLoc;
3331 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
3332
3333 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3334 if (!AttrName)
3335 // Break out to the "expected ']'" diagnostic.
3336 break;
3337
3338 // scoped attribute
3339 if (TryConsumeToken(tok::coloncolon)) {
3340 ScopeName = AttrName;
3341 ScopeLoc = AttrLoc;
3342
3343 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3344 if (!AttrName) {
3345 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3346 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
3347 continue;
3348 }
3349 }
3350
3351 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
3352 bool AttrParsed = false;
3353
3354 if (StandardAttr &&
3355 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
3356 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
3357 << AttrName << SourceRange(SeenAttrs[AttrName]);
3358
3359 // Parse attribute arguments
3360 if (Tok.is(tok::l_paren))
3361 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
3362 ScopeName, ScopeLoc);
3363
3364 if (!AttrParsed)
3365 attrs.addNew(AttrName,
3366 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
3367 AttrLoc),
3368 ScopeName, ScopeLoc, nullptr, 0, AttributeList::AS_CXX11);
3369
3370 if (TryConsumeToken(tok::ellipsis))
3371 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
3372 << AttrName->getName();
3373 }
3374
3375 if (ExpectAndConsume(tok::r_square))
3376 SkipUntil(tok::r_square);
3377 if (endLoc)
3378 *endLoc = Tok.getLocation();
3379 if (ExpectAndConsume(tok::r_square))
3380 SkipUntil(tok::r_square);
3381 }
3382
3383 /// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
3384 ///
3385 /// attribute-specifier-seq:
3386 /// attribute-specifier-seq[opt] attribute-specifier
ParseCXX11Attributes(ParsedAttributesWithRange & attrs,SourceLocation * endLoc)3387 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
3388 SourceLocation *endLoc) {
3389 assert(getLangOpts().CPlusPlus11);
3390
3391 SourceLocation StartLoc = Tok.getLocation(), Loc;
3392 if (!endLoc)
3393 endLoc = &Loc;
3394
3395 do {
3396 ParseCXX11AttributeSpecifier(attrs, endLoc);
3397 } while (isCXX11AttributeSpecifier());
3398
3399 attrs.Range = SourceRange(StartLoc, *endLoc);
3400 }
3401
DiagnoseAndSkipCXX11Attributes()3402 void Parser::DiagnoseAndSkipCXX11Attributes() {
3403 // Start and end location of an attribute or an attribute list.
3404 SourceLocation StartLoc = Tok.getLocation();
3405 SourceLocation EndLoc = SkipCXX11Attributes();
3406
3407 if (EndLoc.isValid()) {
3408 SourceRange Range(StartLoc, EndLoc);
3409 Diag(StartLoc, diag::err_attributes_not_allowed)
3410 << Range;
3411 }
3412 }
3413
SkipCXX11Attributes()3414 SourceLocation Parser::SkipCXX11Attributes() {
3415 SourceLocation EndLoc;
3416
3417 if (!isCXX11AttributeSpecifier())
3418 return EndLoc;
3419
3420 do {
3421 if (Tok.is(tok::l_square)) {
3422 BalancedDelimiterTracker T(*this, tok::l_square);
3423 T.consumeOpen();
3424 T.skipToEnd();
3425 EndLoc = T.getCloseLocation();
3426 } else {
3427 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
3428 ConsumeToken();
3429 BalancedDelimiterTracker T(*this, tok::l_paren);
3430 if (!T.consumeOpen())
3431 T.skipToEnd();
3432 EndLoc = T.getCloseLocation();
3433 }
3434 } while (isCXX11AttributeSpecifier());
3435
3436 return EndLoc;
3437 }
3438
3439 /// ParseMicrosoftAttributes - Parse a Microsoft attribute [Attr]
3440 ///
3441 /// [MS] ms-attribute:
3442 /// '[' token-seq ']'
3443 ///
3444 /// [MS] ms-attribute-seq:
3445 /// ms-attribute[opt]
3446 /// ms-attribute ms-attribute-seq
ParseMicrosoftAttributes(ParsedAttributes & attrs,SourceLocation * endLoc)3447 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
3448 SourceLocation *endLoc) {
3449 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
3450
3451 while (Tok.is(tok::l_square)) {
3452 // FIXME: If this is actually a C++11 attribute, parse it as one.
3453 ConsumeBracket();
3454 SkipUntil(tok::r_square, StopAtSemi | StopBeforeMatch);
3455 if (endLoc) *endLoc = Tok.getLocation();
3456 ExpectAndConsume(tok::r_square);
3457 }
3458 }
3459
ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,AccessSpecifier & CurAS)3460 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
3461 AccessSpecifier& CurAS) {
3462 IfExistsCondition Result;
3463 if (ParseMicrosoftIfExistsCondition(Result))
3464 return;
3465
3466 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3467 if (Braces.consumeOpen()) {
3468 Diag(Tok, diag::err_expected) << tok::l_brace;
3469 return;
3470 }
3471
3472 switch (Result.Behavior) {
3473 case IEB_Parse:
3474 // Parse the declarations below.
3475 break;
3476
3477 case IEB_Dependent:
3478 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
3479 << Result.IsIfExists;
3480 // Fall through to skip.
3481
3482 case IEB_Skip:
3483 Braces.skipToEnd();
3484 return;
3485 }
3486
3487 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
3488 // __if_exists, __if_not_exists can nest.
3489 if ((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists))) {
3490 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
3491 continue;
3492 }
3493
3494 // Check for extraneous top-level semicolon.
3495 if (Tok.is(tok::semi)) {
3496 ConsumeExtraSemi(InsideStruct, TagType);
3497 continue;
3498 }
3499
3500 AccessSpecifier AS = getAccessSpecifierIfPresent();
3501 if (AS != AS_none) {
3502 // Current token is a C++ access specifier.
3503 CurAS = AS;
3504 SourceLocation ASLoc = Tok.getLocation();
3505 ConsumeToken();
3506 if (Tok.is(tok::colon))
3507 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
3508 else
3509 Diag(Tok, diag::err_expected) << tok::colon;
3510 ConsumeToken();
3511 continue;
3512 }
3513
3514 // Parse all the comma separated declarators.
3515 ParseCXXClassMemberDeclaration(CurAS, nullptr);
3516 }
3517
3518 Braces.consumeClose();
3519 }
3520