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