Clang Project

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