Coverage Report

Created: 2022-05-14 11:35

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Parse/ParseTemplate.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ParseTemplate.cpp - Template Parsing -----------------------------===//
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 parsing of C++ templates.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/ASTContext.h"
14
#include "clang/AST/DeclTemplate.h"
15
#include "clang/AST/ExprCXX.h"
16
#include "clang/Parse/ParseDiagnostic.h"
17
#include "clang/Parse/Parser.h"
18
#include "clang/Parse/RAIIObjectsForParser.h"
19
#include "clang/Sema/DeclSpec.h"
20
#include "clang/Sema/ParsedTemplate.h"
21
#include "clang/Sema/Scope.h"
22
#include "clang/Sema/SemaDiagnostic.h"
23
#include "llvm/Support/TimeProfiler.h"
24
using namespace clang;
25
26
/// Re-enter a possible template scope, creating as many template parameter
27
/// scopes as necessary.
28
/// \return The number of template parameter scopes entered.
29
760k
unsigned Parser::ReenterTemplateScopes(MultiParseScope &S, Decl *D) {
30
760k
  return Actions.ActOnReenterTemplateScope(D, [&] {
31
138k
    S.Enter(Scope::TemplateParamScope);
32
138k
    return Actions.getCurScope();
33
138k
  });
34
760k
}
35
36
/// Parse a template declaration, explicit instantiation, or
37
/// explicit specialization.
38
Decl *Parser::ParseDeclarationStartingWithTemplate(
39
    DeclaratorContext Context, SourceLocation &DeclEnd,
40
979k
    ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
41
979k
  ObjCDeclContextSwitch ObjCDC(*this);
42
43
979k
  if (Tok.is(tok::kw_template) && 
NextToken().isNot(tok::less)979k
) {
44
4.92k
    return ParseExplicitInstantiation(Context, SourceLocation(), ConsumeToken(),
45
4.92k
                                      DeclEnd, AccessAttrs, AS);
46
4.92k
  }
47
974k
  return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AccessAttrs,
48
974k
                                                  AS);
49
979k
}
50
51
/// Parse a template declaration or an explicit specialization.
52
///
53
/// Template declarations include one or more template parameter lists
54
/// and either the function or class template declaration. Explicit
55
/// specializations contain one or more 'template < >' prefixes
56
/// followed by a (possibly templated) declaration. Since the
57
/// syntactic form of both features is nearly identical, we parse all
58
/// of the template headers together and let semantic analysis sort
59
/// the declarations from the explicit specializations.
60
///
61
///       template-declaration: [C++ temp]
62
///         'export'[opt] 'template' '<' template-parameter-list '>' declaration
63
///
64
///       template-declaration: [C++2a]
65
///         template-head declaration
66
///         template-head concept-definition
67
///
68
///       TODO: requires-clause
69
///       template-head: [C++2a]
70
///         'template' '<' template-parameter-list '>'
71
///             requires-clause[opt]
72
///
73
///       explicit-specialization: [ C++ temp.expl.spec]
74
///         'template' '<' '>' declaration
75
Decl *Parser::ParseTemplateDeclarationOrSpecialization(
76
    DeclaratorContext Context, SourceLocation &DeclEnd,
77
1.18M
    ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
78
1.18M
  assert(Tok.isOneOf(tok::kw_export, tok::kw_template) &&
79
1.18M
         "Token does not start a template declaration.");
80
81
0
  MultiParseScope TemplateParamScopes(*this);
82
83
  // Tell the action that names should be checked in the context of
84
  // the declaration to come.
85
1.18M
  ParsingDeclRAIIObject
86
1.18M
    ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
87
88
  // Parse multiple levels of template headers within this template
89
  // parameter scope, e.g.,
90
  //
91
  //   template<typename T>
92
  //     template<typename U>
93
  //       class A<T>::B { ... };
94
  //
95
  // We parse multiple levels non-recursively so that we can build a
96
  // single data structure containing all of the template parameter
97
  // lists to easily differentiate between the case above and:
98
  //
99
  //   template<typename T>
100
  //   class A {
101
  //     template<typename U> class B;
102
  //   };
103
  //
104
  // In the first case, the action for declaring A<T>::B receives
105
  // both template parameter lists. In the second case, the action for
106
  // defining A<T>::B receives just the inner template parameter list
107
  // (and retrieves the outer template parameter list from its
108
  // context).
109
1.18M
  bool isSpecialization = true;
110
1.18M
  bool LastParamListWasEmpty = false;
111
1.18M
  TemplateParameterLists ParamLists;
112
1.18M
  TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
113
114
1.21M
  do {
115
    // Consume the 'export', if any.
116
1.21M
    SourceLocation ExportLoc;
117
1.21M
    TryConsumeToken(tok::kw_export, ExportLoc);
118
119
    // Consume the 'template', which should be here.
120
1.21M
    SourceLocation TemplateLoc;
121
1.21M
    if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
122
4
      Diag(Tok.getLocation(), diag::err_expected_template);
123
4
      return nullptr;
124
4
    }
125
126
    // Parse the '<' template-parameter-list '>'
127
1.21M
    SourceLocation LAngleLoc, RAngleLoc;
128
1.21M
    SmallVector<NamedDecl*, 4> TemplateParams;
129
1.21M
    if (ParseTemplateParameters(TemplateParamScopes,
130
1.21M
                                CurTemplateDepthTracker.getDepth(),
131
1.21M
                                TemplateParams, LAngleLoc, RAngleLoc)) {
132
      // Skip until the semi-colon or a '}'.
133
23
      SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
134
23
      TryConsumeToken(tok::semi);
135
23
      return nullptr;
136
23
    }
137
138
1.21M
    ExprResult OptionalRequiresClauseConstraintER;
139
1.21M
    if (!TemplateParams.empty()) {
140
1.14M
      isSpecialization = false;
141
1.14M
      ++CurTemplateDepthTracker;
142
143
1.14M
      if (TryConsumeToken(tok::kw_requires)) {
144
311
        OptionalRequiresClauseConstraintER =
145
311
            Actions.ActOnRequiresClause(ParseConstraintLogicalOrExpression(
146
311
                /*IsTrailingRequiresClause=*/false));
147
311
        if (!OptionalRequiresClauseConstraintER.isUsable()) {
148
          // Skip until the semi-colon or a '}'.
149
11
          SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
150
11
          TryConsumeToken(tok::semi);
151
11
          return nullptr;
152
11
        }
153
311
      }
154
1.14M
    } else {
155
69.0k
      LastParamListWasEmpty = true;
156
69.0k
    }
157
158
1.21M
    ParamLists.push_back(Actions.ActOnTemplateParameterList(
159
1.21M
        CurTemplateDepthTracker.getDepth(), ExportLoc, TemplateLoc, LAngleLoc,
160
1.21M
        TemplateParams, RAngleLoc, OptionalRequiresClauseConstraintER.get()));
161
1.21M
  } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
162
163
  // Parse the actual template declaration.
164
1.18M
  if (Tok.is(tok::kw_concept))
165
275
    return ParseConceptDefinition(
166
275
        ParsedTemplateInfo(&ParamLists, isSpecialization,
167
275
                           LastParamListWasEmpty),
168
275
        DeclEnd);
169
170
1.18M
  return ParseSingleDeclarationAfterTemplate(
171
1.18M
      Context,
172
1.18M
      ParsedTemplateInfo(&ParamLists, isSpecialization, LastParamListWasEmpty),
173
1.18M
      ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
174
1.18M
}
175
176
/// Parse a single declaration that declares a template,
177
/// template specialization, or explicit instantiation of a template.
178
///
179
/// \param DeclEnd will receive the source location of the last token
180
/// within this declaration.
181
///
182
/// \param AS the access specifier associated with this
183
/// declaration. Will be AS_none for namespace-scope declarations.
184
///
185
/// \returns the new declaration.
186
Decl *Parser::ParseSingleDeclarationAfterTemplate(
187
    DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
188
    ParsingDeclRAIIObject &DiagsFromTParams, SourceLocation &DeclEnd,
189
1.23M
    ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
190
1.23M
  assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
191
1.23M
         "Template information required");
192
193
1.23M
  if (Tok.is(tok::kw_static_assert)) {
194
    // A static_assert declaration may not be templated.
195
2
    Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
196
2
      << TemplateInfo.getSourceRange();
197
    // Parse the static_assert declaration to improve error recovery.
198
2
    return ParseStaticAssertDeclaration(DeclEnd);
199
2
  }
200
201
1.23M
  if (Context == DeclaratorContext::Member) {
202
    // We are parsing a member template.
203
215k
    DeclGroupPtrTy D = ParseCXXClassMemberDeclaration(
204
215k
        AS, AccessAttrs, TemplateInfo, &DiagsFromTParams);
205
206
215k
    if (!D || 
!D.get().isSingleDecl()207k
)
207
7.84k
      return nullptr;
208
207k
    return D.get().getSingleDecl();
209
215k
  }
210
211
1.01M
  ParsedAttributes prefixAttrs(AttrFactory);
212
1.01M
  MaybeParseCXX11Attributes(prefixAttrs);
213
214
1.01M
  if (Tok.is(tok::kw_using)) {
215
24.7k
    auto usingDeclPtr = ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
216
24.7k
                                                         prefixAttrs);
217
24.7k
    if (!usingDeclPtr || 
!usingDeclPtr.get().isSingleDecl()24.7k
)
218
49
      return nullptr;
219
24.7k
    return usingDeclPtr.get().getSingleDecl();
220
24.7k
  }
221
222
  // Parse the declaration specifiers, stealing any diagnostics from
223
  // the template parameters.
224
991k
  ParsingDeclSpec DS(*this, &DiagsFromTParams);
225
226
991k
  ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
227
991k
                             getDeclSpecContextFromDeclaratorContext(Context));
228
229
991k
  if (Tok.is(tok::semi)) {
230
462k
    ProhibitAttributes(prefixAttrs);
231
462k
    DeclEnd = ConsumeToken();
232
462k
    RecordDecl *AnonRecord = nullptr;
233
462k
    Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
234
462k
        getCurScope(), AS, DS,
235
462k
        TemplateInfo.TemplateParams ? 
*TemplateInfo.TemplateParams455k
236
462k
                                    : 
MultiTemplateParamsArg()6.62k
,
237
462k
        TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
238
462k
        AnonRecord);
239
462k
    assert(!AnonRecord &&
240
462k
           "Anonymous unions/structs should not be valid with template");
241
0
    DS.complete(Decl);
242
462k
    return Decl;
243
462k
  }
244
245
  // Move the attributes from the prefix into the DS.
246
529k
  if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
247
35.4k
    ProhibitAttributes(prefixAttrs);
248
493k
  else
249
493k
    DS.takeAttributesFrom(prefixAttrs);
250
251
  // Parse the declarator.
252
529k
  ParsingDeclarator DeclaratorInfo(*this, DS, (DeclaratorContext)Context);
253
529k
  if (TemplateInfo.TemplateParams)
254
493k
    DeclaratorInfo.setTemplateParameterLists(*TemplateInfo.TemplateParams);
255
256
  // Turn off usual access checking for template specializations and
257
  // instantiations.
258
  // C++20 [temp.spec] 13.9/6.
259
  // This disables the access checking rules for function template explicit
260
  // instantiation and explicit specialization:
261
  // - parameter-list;
262
  // - template-argument-list;
263
  // - noexcept-specifier;
264
  // - dynamic-exception-specifications (deprecated in C++11, removed since
265
  //   C++17).
266
529k
  bool IsTemplateSpecOrInst =
267
529k
      (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
268
529k
       
TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization493k
);
269
529k
  SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
270
271
529k
  ParseDeclarator(DeclaratorInfo);
272
273
529k
  if (IsTemplateSpecOrInst)
274
40.8k
    SAC.done();
275
276
  // Error parsing the declarator?
277
529k
  if (!DeclaratorInfo.hasName()) {
278
    // If so, skip until the semi-colon or a }.
279
44
    SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
280
44
    if (Tok.is(tok::semi))
281
34
      ConsumeToken();
282
44
    return nullptr;
283
44
  }
284
285
529k
  llvm::TimeTraceScope TimeScope("ParseTemplate", [&]() {
286
1
    return std::string(DeclaratorInfo.getIdentifier() != nullptr
287
1
                           ? DeclaratorInfo.getIdentifier()->getName()
288
1
                           : 
"<unknown>"0
);
289
1
  });
290
291
529k
  LateParsedAttrList LateParsedAttrs(true);
292
529k
  if (DeclaratorInfo.isFunctionDeclarator()) {
293
477k
    if (Tok.is(tok::kw_requires))
294
56
      ParseTrailingRequiresClause(DeclaratorInfo);
295
296
477k
    MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
297
477k
  }
298
299
529k
  if (DeclaratorInfo.isFunctionDeclarator() &&
300
529k
      
isStartOfFunctionDefinition(DeclaratorInfo)477k
) {
301
302
    // Function definitions are only allowed at file scope and in C++ classes.
303
    // The C++ inline method definition case is handled elsewhere, so we only
304
    // need to handle the file scope definition case.
305
403k
    if (Context != DeclaratorContext::File) {
306
3
      Diag(Tok, diag::err_function_definition_not_allowed);
307
3
      SkipMalformedDecl();
308
3
      return nullptr;
309
3
    }
310
311
403k
    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
312
      // Recover by ignoring the 'typedef'. This was probably supposed to be
313
      // the 'typename' keyword, which we should have already suggested adding
314
      // if it's appropriate.
315
6
      Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
316
6
        << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
317
6
      DS.ClearStorageClassSpecs();
318
6
    }
319
320
403k
    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
321
14
      if (DeclaratorInfo.getName().getKind() !=
322
14
          UnqualifiedIdKind::IK_TemplateId) {
323
        // If the declarator-id is not a template-id, issue a diagnostic and
324
        // recover by ignoring the 'template' keyword.
325
7
        Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
326
7
        return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
327
7
                                       &LateParsedAttrs);
328
7
      } else {
329
7
        SourceLocation LAngleLoc
330
7
          = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
331
7
        Diag(DeclaratorInfo.getIdentifierLoc(),
332
7
             diag::err_explicit_instantiation_with_definition)
333
7
            << SourceRange(TemplateInfo.TemplateLoc)
334
7
            << FixItHint::CreateInsertion(LAngleLoc, "<>");
335
336
        // Recover as if it were an explicit specialization.
337
7
        TemplateParameterLists FakedParamLists;
338
7
        FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
339
7
            0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
340
7
            LAngleLoc, nullptr));
341
342
7
        return ParseFunctionDefinition(
343
7
            DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
344
7
                                               /*isSpecialization=*/true,
345
7
                                               /*lastParameterListWasEmpty=*/true),
346
7
            &LateParsedAttrs);
347
7
      }
348
14
    }
349
403k
    return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
350
403k
                                   &LateParsedAttrs);
351
403k
  }
352
353
  // Parse this declaration.
354
125k
  Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
355
125k
                                                   TemplateInfo);
356
357
125k
  if (Tok.is(tok::comma)) {
358
3
    Diag(Tok, diag::err_multiple_template_declarators)
359
3
      << (int)TemplateInfo.Kind;
360
3
    SkipUntil(tok::semi);
361
3
    return ThisDecl;
362
3
  }
363
364
  // Eat the semi colon after the declaration.
365
125k
  ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
366
125k
  if (LateParsedAttrs.size() > 0)
367
8
    ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
368
125k
  DeclaratorInfo.complete(ThisDecl);
369
125k
  return ThisDecl;
370
125k
}
371
372
/// \brief Parse a single declaration that declares a concept.
373
///
374
/// \param DeclEnd will receive the source location of the last token
375
/// within this declaration.
376
///
377
/// \returns the new declaration.
378
Decl *
379
Parser::ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
380
275
                               SourceLocation &DeclEnd) {
381
275
  assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
382
275
         "Template information required");
383
0
  assert(Tok.is(tok::kw_concept) &&
384
275
         "ParseConceptDefinition must be called when at a 'concept' keyword");
385
386
0
  ConsumeToken(); // Consume 'concept'
387
388
275
  SourceLocation BoolKWLoc;
389
275
  if (TryConsumeToken(tok::kw_bool, BoolKWLoc))
390
1
    Diag(Tok.getLocation(), diag::ext_concept_legacy_bool_keyword) <<
391
1
        FixItHint::CreateRemoval(SourceLocation(BoolKWLoc));
392
393
275
  DiagnoseAndSkipCXX11Attributes();
394
395
275
  CXXScopeSpec SS;
396
275
  if (ParseOptionalCXXScopeSpecifier(
397
275
          SS, /*ObjectType=*/nullptr,
398
275
          /*ObjectHasErrors=*/false, /*EnteringContext=*/false,
399
275
          /*MayBePseudoDestructor=*/nullptr,
400
275
          /*IsTypename=*/false, /*LastII=*/nullptr, /*OnlyNamespace=*/true) ||
401
275
      SS.isInvalid()) {
402
1
    SkipUntil(tok::semi);
403
1
    return nullptr;
404
1
  }
405
406
274
  if (SS.isNotEmpty())
407
1
    Diag(SS.getBeginLoc(),
408
1
         diag::err_concept_definition_not_identifier);
409
410
274
  UnqualifiedId Result;
411
274
  if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
412
274
                         /*ObjectHadErrors=*/false, /*EnteringContext=*/false,
413
274
                         /*AllowDestructorName=*/false,
414
274
                         /*AllowConstructorName=*/false,
415
274
                         /*AllowDeductionGuide=*/false,
416
274
                         /*TemplateKWLoc=*/nullptr, Result)) {
417
0
    SkipUntil(tok::semi);
418
0
    return nullptr;
419
0
  }
420
421
274
  if (Result.getKind() != UnqualifiedIdKind::IK_Identifier) {
422
2
    Diag(Result.getBeginLoc(), diag::err_concept_definition_not_identifier);
423
2
    SkipUntil(tok::semi);
424
2
    return nullptr;
425
2
  }
426
427
272
  IdentifierInfo *Id = Result.Identifier;
428
272
  SourceLocation IdLoc = Result.getBeginLoc();
429
430
272
  DiagnoseAndSkipCXX11Attributes();
431
432
272
  if (!TryConsumeToken(tok::equal)) {
433
0
    Diag(Tok.getLocation(), diag::err_expected) << tok::equal;
434
0
    SkipUntil(tok::semi);
435
0
    return nullptr;
436
0
  }
437
438
272
  ExprResult ConstraintExprResult =
439
272
      Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
440
272
  if (ConstraintExprResult.isInvalid()) {
441
8
    SkipUntil(tok::semi);
442
8
    return nullptr;
443
8
  }
444
445
264
  DeclEnd = Tok.getLocation();
446
264
  ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
447
264
  Expr *ConstraintExpr = ConstraintExprResult.get();
448
264
  return Actions.ActOnConceptDefinition(getCurScope(),
449
264
                                        *TemplateInfo.TemplateParams,
450
264
                                        Id, IdLoc, ConstraintExpr);
451
272
}
452
453
/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
454
/// angle brackets. Depth is the depth of this template-parameter-list, which
455
/// is the number of template headers directly enclosing this template header.
456
/// TemplateParams is the current list of template parameters we're building.
457
/// The template parameter we parse will be added to this list. LAngleLoc and
458
/// RAngleLoc will receive the positions of the '<' and '>', respectively,
459
/// that enclose this template parameter list.
460
///
461
/// \returns true if an error occurred, false otherwise.
462
bool Parser::ParseTemplateParameters(
463
    MultiParseScope &TemplateScopes, unsigned Depth,
464
    SmallVectorImpl<NamedDecl *> &TemplateParams, SourceLocation &LAngleLoc,
465
1.23M
    SourceLocation &RAngleLoc) {
466
  // Get the template parameter list.
467
1.23M
  if (!TryConsumeToken(tok::less, LAngleLoc)) {
468
34
    Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
469
34
    return true;
470
34
  }
471
472
  // Try to parse the template parameter list.
473
1.23M
  bool Failed = false;
474
  // FIXME: Missing greatergreatergreater support.
475
1.23M
  if (!Tok.is(tok::greater) && 
!Tok.is(tok::greatergreater)1.16M
) {
476
1.16M
    TemplateScopes.Enter(Scope::TemplateParamScope);
477
1.16M
    Failed = ParseTemplateParameterList(Depth, TemplateParams);
478
1.16M
  }
479
480
1.23M
  if (Tok.is(tok::greatergreater)) {
481
    // No diagnostic required here: a template-parameter-list can only be
482
    // followed by a declaration or, for a template template parameter, the
483
    // 'class' keyword. Therefore, the second '>' will be diagnosed later.
484
    // This matters for elegant diagnosis of:
485
    //   template<template<typename>> struct S;
486
12
    Tok.setKind(tok::greater);
487
12
    RAngleLoc = Tok.getLocation();
488
12
    Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
489
1.23M
  } else if (!TryConsumeToken(tok::greater, RAngleLoc) && 
Failed9
) {
490
0
    Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
491
0
    return true;
492
0
  }
493
1.23M
  return false;
494
1.23M
}
495
496
/// ParseTemplateParameterList - Parse a template parameter list. If
497
/// the parsing fails badly (i.e., closing bracket was left out), this
498
/// will try to put the token stream in a reasonable position (closing
499
/// a statement, etc.) and return false.
500
///
501
///       template-parameter-list:    [C++ temp]
502
///         template-parameter
503
///         template-parameter-list ',' template-parameter
504
bool
505
Parser::ParseTemplateParameterList(const unsigned Depth,
506
1.16M
                             SmallVectorImpl<NamedDecl*> &TemplateParams) {
507
2.07M
  while (true) {
508
509
2.07M
    if (NamedDecl *TmpParam
510
2.07M
          = ParseTemplateParameter(Depth, TemplateParams.size())) {
511
2.07M
      TemplateParams.push_back(TmpParam);
512
2.07M
    } else {
513
      // If we failed to parse a template parameter, skip until we find
514
      // a comma or closing brace.
515
19
      SkipUntil(tok::comma, tok::greater, tok::greatergreater,
516
19
                StopAtSemi | StopBeforeMatch);
517
19
    }
518
519
    // Did we find a comma or the end of the template parameter list?
520
2.07M
    if (Tok.is(tok::comma)) {
521
915k
      ConsumeToken();
522
1.16M
    } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
523
      // Don't consume this... that's done by template parser.
524
1.16M
      break;
525
1.16M
    } else {
526
      // Somebody probably forgot to close the template. Skip ahead and
527
      // try to get out of the expression. This error is currently
528
      // subsumed by whatever goes on in ParseTemplateParameter.
529
25
      Diag(Tok.getLocation(), diag::err_expected_comma_greater);
530
25
      SkipUntil(tok::comma, tok::greater, tok::greatergreater,
531
25
                StopAtSemi | StopBeforeMatch);
532
25
      return false;
533
25
    }
534
2.07M
  }
535
1.16M
  return true;
536
1.16M
}
537
538
/// Determine whether the parser is at the start of a template
539
/// type parameter.
540
2.07M
Parser::TPResult Parser::isStartOfTemplateTypeParameter() {
541
2.07M
  if (Tok.is(tok::kw_class)) {
542
    // "class" may be the start of an elaborated-type-specifier or a
543
    // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
544
1.76M
    switch (NextToken().getKind()) {
545
57.4k
    case tok::equal:
546
66.2k
    case tok::comma:
547
75.6k
    case tok::greater:
548
75.6k
    case tok::greatergreater:
549
204k
    case tok::ellipsis:
550
204k
      return TPResult::True;
551
552
1.56M
    case tok::identifier:
553
      // This may be either a type-parameter or an elaborated-type-specifier.
554
      // We have to look further.
555
1.56M
      break;
556
557
0
    default:
558
0
      return TPResult::False;
559
1.76M
    }
560
561
1.56M
    switch (GetLookAheadToken(2).getKind()) {
562
44.2k
    case tok::equal:
563
782k
    case tok::comma:
564
1.56M
    case tok::greater:
565
1.56M
    case tok::greatergreater:
566
1.56M
      return TPResult::True;
567
568
13
    default:
569
13
      return TPResult::False;
570
1.56M
    }
571
1.56M
  }
572
573
313k
  if (TryAnnotateTypeConstraint())
574
0
    return TPResult::Error;
575
576
313k
  if (isTypeConstraintAnnotation() &&
577
      // Next token might be 'auto' or 'decltype', indicating that this
578
      // type-constraint is in fact part of a placeholder-type-specifier of a
579
      // non-type template parameter.
580
313k
      
!GetLookAheadToken(108
Tok.is(tok::annot_cxxscope)108
?
29
:
199
)
581
108
           .isOneOf(tok::kw_auto, tok::kw_decltype))
582
105
    return TPResult::True;
583
584
  // 'typedef' is a reasonably-common typo/thinko for 'typename', and is
585
  // ill-formed otherwise.
586
313k
  if (Tok.isNot(tok::kw_typename) && 
Tok.isNot(tok::kw_typedef)232k
)
587
232k
    return TPResult::False;
588
589
  // C++ [temp.param]p2:
590
  //   There is no semantic difference between class and typename in a
591
  //   template-parameter. typename followed by an unqualified-id
592
  //   names a template type parameter. typename followed by a
593
  //   qualified-id denotes the type in a non-type
594
  //   parameter-declaration.
595
80.8k
  Token Next = NextToken();
596
597
  // If we have an identifier, skip over it.
598
80.8k
  if (Next.getKind() == tok::identifier)
599
72.1k
    Next = GetLookAheadToken(2);
600
601
80.8k
  switch (Next.getKind()) {
602
4.14k
  case tok::equal:
603
19.9k
  case tok::comma:
604
67.2k
  case tok::greater:
605
67.2k
  case tok::greatergreater:
606
71.5k
  case tok::ellipsis:
607
71.5k
    return TPResult::True;
608
609
6
  case tok::kw_typename:
610
6
  case tok::kw_typedef:
611
6
  case tok::kw_class:
612
    // These indicate that a comma was missed after a type parameter, not that
613
    // we have found a non-type parameter.
614
6
    return TPResult::True;
615
616
9.26k
  default:
617
9.26k
    return TPResult::False;
618
80.8k
  }
619
80.8k
}
620
621
/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
622
///
623
///       template-parameter: [C++ temp.param]
624
///         type-parameter
625
///         parameter-declaration
626
///
627
///       type-parameter: (See below)
628
///         type-parameter-key ...[opt] identifier[opt]
629
///         type-parameter-key identifier[opt] = type-id
630
/// (C++2a) type-constraint ...[opt] identifier[opt]
631
/// (C++2a) type-constraint identifier[opt] = type-id
632
///         'template' '<' template-parameter-list '>' type-parameter-key
633
///               ...[opt] identifier[opt]
634
///         'template' '<' template-parameter-list '>' type-parameter-key
635
///               identifier[opt] '=' id-expression
636
///
637
///       type-parameter-key:
638
///         class
639
///         typename
640
///
641
2.07M
NamedDecl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
642
643
2.07M
  switch (isStartOfTemplateTypeParameter()) {
644
1.83M
  case TPResult::True:
645
    // Is there just a typo in the input code? ('typedef' instead of
646
    // 'typename')
647
1.83M
    if (Tok.is(tok::kw_typedef)) {
648
5
      Diag(Tok.getLocation(), diag::err_expected_template_parameter);
649
650
5
      Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
651
5
          << FixItHint::CreateReplacement(CharSourceRange::getCharRange(
652
5
                                              Tok.getLocation(),
653
5
                                              Tok.getEndLoc()),
654
5
                                          "typename");
655
656
5
      Tok.setKind(tok::kw_typename);
657
5
    }
658
659
1.83M
    return ParseTypeParameter(Depth, Position);
660
241k
  case TPResult::False:
661
241k
    break;
662
663
0
  case TPResult::Error: {
664
    // We return an invalid parameter as opposed to null to avoid having bogus
665
    // diagnostics about an empty template parameter list.
666
    // FIXME: Fix ParseTemplateParameterList to better handle nullptr results
667
    //  from here.
668
    // Return a NTTP as if there was an error in a scope specifier, the user
669
    // probably meant to write the type of a NTTP.
670
0
    DeclSpec DS(getAttrFactory());
671
0
    DS.SetTypeSpecError();
672
0
    Declarator D(DS, DeclaratorContext::TemplateParam);
673
0
    D.SetIdentifier(nullptr, Tok.getLocation());
674
0
    D.setInvalidType(true);
675
0
    NamedDecl *ErrorParam = Actions.ActOnNonTypeTemplateParameter(
676
0
        getCurScope(), D, Depth, Position, /*EqualLoc=*/SourceLocation(),
677
0
        /*DefaultArg=*/nullptr);
678
0
    ErrorParam->setInvalidDecl(true);
679
0
    SkipUntil(tok::comma, tok::greater, tok::greatergreater,
680
0
              StopAtSemi | StopBeforeMatch);
681
0
    return ErrorParam;
682
0
  }
683
684
0
  case TPResult::Ambiguous:
685
0
    llvm_unreachable("template param classification can't be ambiguous");
686
2.07M
  }
687
688
241k
  if (Tok.is(tok::kw_template))
689
18.8k
    return ParseTemplateTemplateParameter(Depth, Position);
690
691
  // If it's none of the above, then it must be a parameter declaration.
692
  // NOTE: This will pick up errors in the closure of the template parameter
693
  // list (e.g., template < ; Check here to implement >> style closures.
694
223k
  return ParseNonTypeTemplateParameter(Depth, Position);
695
241k
}
696
697
/// Check whether the current token is a template-id annotation denoting a
698
/// type-constraint.
699
349k
bool Parser::isTypeConstraintAnnotation() {
700
349k
  const Token &T = Tok.is(tok::annot_cxxscope) ? 
NextToken()35.6k
:
Tok313k
;
701
349k
  if (T.isNot(tok::annot_template_id))
702
349k
    return false;
703
288
  const auto *ExistingAnnot =
704
288
      static_cast<TemplateIdAnnotation *>(T.getAnnotationValue());
705
288
  return ExistingAnnot->Kind == TNK_Concept_template;
706
349k
}
707
708
/// Try parsing a type-constraint at the current location.
709
///
710
///     type-constraint:
711
///       nested-name-specifier[opt] concept-name
712
///       nested-name-specifier[opt] concept-name
713
///           '<' template-argument-list[opt] '>'[opt]
714
///
715
/// \returns true if an error occurred, and false otherwise.
716
470k
bool Parser::TryAnnotateTypeConstraint() {
717
470k
  if (!getLangOpts().CPlusPlus20)
718
465k
    return false;
719
5.51k
  CXXScopeSpec SS;
720
5.51k
  bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
721
5.51k
  if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
722
5.51k
                                     /*ObjectHasErrors=*/false,
723
5.51k
                                     /*EnteringContext=*/false,
724
5.51k
                                     /*MayBePseudoDestructor=*/nullptr,
725
                                     // If this is not a type-constraint, then
726
                                     // this scope-spec is part of the typename
727
                                     // of a non-type template parameter
728
5.51k
                                     /*IsTypename=*/true, /*LastII=*/nullptr,
729
                                     // We won't find concepts in
730
                                     // non-namespaces anyway, so might as well
731
                                     // parse this correctly for possible type
732
                                     // names.
733
5.51k
                                     /*OnlyNamespace=*/false))
734
0
    return true;
735
736
5.51k
  if (Tok.is(tok::identifier)) {
737
485
    UnqualifiedId PossibleConceptName;
738
485
    PossibleConceptName.setIdentifier(Tok.getIdentifierInfo(),
739
485
                                      Tok.getLocation());
740
741
485
    TemplateTy PossibleConcept;
742
485
    bool MemberOfUnknownSpecialization = false;
743
485
    auto TNK = Actions.isTemplateName(getCurScope(), SS,
744
485
                                      /*hasTemplateKeyword=*/false,
745
485
                                      PossibleConceptName,
746
485
                                      /*ObjectType=*/ParsedType(),
747
485
                                      /*EnteringContext=*/false,
748
485
                                      PossibleConcept,
749
485
                                      MemberOfUnknownSpecialization,
750
485
                                      /*Disambiguation=*/true);
751
485
    if (MemberOfUnknownSpecialization || 
!PossibleConcept473
||
752
485
        
TNK != TNK_Concept_template208
) {
753
331
      if (SS.isNotEmpty())
754
30
        AnnotateScopeToken(SS, !WasScopeAnnotation);
755
331
      return false;
756
331
    }
757
758
    // At this point we're sure we're dealing with a constrained parameter. It
759
    // may or may not have a template parameter list following the concept
760
    // name.
761
154
    if (AnnotateTemplateIdToken(PossibleConcept, TNK, SS,
762
154
                                   /*TemplateKWLoc=*/SourceLocation(),
763
154
                                   PossibleConceptName,
764
154
                                   /*AllowTypeAnnotation=*/false,
765
154
                                   /*TypeConstraint=*/true))
766
0
      return true;
767
154
  }
768
769
5.18k
  if (SS.isNotEmpty())
770
82
    AnnotateScopeToken(SS, !WasScopeAnnotation);
771
5.18k
  return false;
772
5.51k
}
773
774
/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
775
/// Other kinds of template parameters are parsed in
776
/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
777
///
778
///       type-parameter:     [C++ temp.param]
779
///         'class' ...[opt][C++0x] identifier[opt]
780
///         'class' identifier[opt] '=' type-id
781
///         'typename' ...[opt][C++0x] identifier[opt]
782
///         'typename' identifier[opt] '=' type-id
783
1.83M
NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
784
1.83M
  assert((Tok.isOneOf(tok::kw_class, tok::kw_typename) ||
785
1.83M
          isTypeConstraintAnnotation()) &&
786
1.83M
         "A type-parameter starts with 'class', 'typename' or a "
787
1.83M
         "type-constraint");
788
789
0
  CXXScopeSpec TypeConstraintSS;
790
1.83M
  TemplateIdAnnotation *TypeConstraint = nullptr;
791
1.83M
  bool TypenameKeyword = false;
792
1.83M
  SourceLocation KeyLoc;
793
1.83M
  ParseOptionalCXXScopeSpecifier(TypeConstraintSS, /*ObjectType=*/nullptr,
794
1.83M
                                 /*ObjectHasErrors=*/false,
795
1.83M
                                 /*EnteringContext*/ false);
796
1.83M
  if (Tok.is(tok::annot_template_id)) {
797
    // Consume the 'type-constraint'.
798
105
    TypeConstraint =
799
105
        static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
800
105
    assert(TypeConstraint->Kind == TNK_Concept_template &&
801
105
           "stray non-concept template-id annotation");
802
0
    KeyLoc = ConsumeAnnotationToken();
803
1.83M
  } else {
804
1.83M
    assert(TypeConstraintSS.isEmpty() &&
805
1.83M
           "expected type constraint after scope specifier");
806
807
    // Consume the 'class' or 'typename' keyword.
808
0
    TypenameKeyword = Tok.is(tok::kw_typename);
809
1.83M
    KeyLoc = ConsumeToken();
810
1.83M
  }
811
812
  // Grab the ellipsis (if given).
813
0
  SourceLocation EllipsisLoc;
814
1.83M
  if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
815
133k
    Diag(EllipsisLoc,
816
133k
         getLangOpts().CPlusPlus11
817
133k
           ? 
diag::warn_cxx98_compat_variadic_templates133k
818
133k
           : 
diag::ext_variadic_templates46
);
819
133k
  }
820
821
  // Grab the template parameter name (if given)
822
1.83M
  SourceLocation NameLoc = Tok.getLocation();
823
1.83M
  IdentifierInfo *ParamName = nullptr;
824
1.83M
  if (Tok.is(tok::identifier)) {
825
1.73M
    ParamName = Tok.getIdentifierInfo();
826
1.73M
    ConsumeToken();
827
1.73M
  } else 
if (104k
Tok.isOneOf(tok::equal, tok::comma, tok::greater,
828
104k
                         tok::greatergreater)) {
829
    // Unnamed template parameter. Don't have to do anything here, just
830
    // don't consume this token.
831
104k
  } else {
832
0
    Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
833
0
    return nullptr;
834
0
  }
835
836
  // Recover from misplaced ellipsis.
837
1.83M
  bool AlreadyHasEllipsis = EllipsisLoc.isValid();
838
1.83M
  if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
839
4
    DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
840
841
  // Grab a default argument (if available).
842
  // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
843
  // we introduce the type parameter into the local scope.
844
1.83M
  SourceLocation EqualLoc;
845
1.83M
  ParsedType DefaultArg;
846
1.83M
  if (TryConsumeToken(tok::equal, EqualLoc))
847
105k
    DefaultArg =
848
105k
        ParseTypeName(/*Range=*/nullptr, DeclaratorContext::TemplateTypeArg)
849
105k
            .get();
850
851
1.83M
  NamedDecl *NewDecl = Actions.ActOnTypeParameter(getCurScope(),
852
1.83M
                                                  TypenameKeyword, EllipsisLoc,
853
1.83M
                                                  KeyLoc, ParamName, NameLoc,
854
1.83M
                                                  Depth, Position, EqualLoc,
855
1.83M
                                                  DefaultArg,
856
1.83M
                                                  TypeConstraint != nullptr);
857
858
1.83M
  if (TypeConstraint) {
859
105
    Actions.ActOnTypeConstraint(TypeConstraintSS, TypeConstraint,
860
105
                                cast<TemplateTypeParmDecl>(NewDecl),
861
105
                                EllipsisLoc);
862
105
  }
863
864
1.83M
  return NewDecl;
865
1.83M
}
866
867
/// ParseTemplateTemplateParameter - Handle the parsing of template
868
/// template parameters.
869
///
870
///       type-parameter:    [C++ temp.param]
871
///         'template' '<' template-parameter-list '>' type-parameter-key
872
///                  ...[opt] identifier[opt]
873
///         'template' '<' template-parameter-list '>' type-parameter-key
874
///                  identifier[opt] = id-expression
875
///       type-parameter-key:
876
///         'class'
877
///         'typename'       [C++1z]
878
NamedDecl *
879
18.8k
Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
880
18.8k
  assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
881
882
  // Handle the template <...> part.
883
0
  SourceLocation TemplateLoc = ConsumeToken();
884
18.8k
  SmallVector<NamedDecl*,8> TemplateParams;
885
18.8k
  SourceLocation LAngleLoc, RAngleLoc;
886
18.8k
  {
887
18.8k
    MultiParseScope TemplateParmScope(*this);
888
18.8k
    if (ParseTemplateParameters(TemplateParmScope, Depth + 1, TemplateParams,
889
18.8k
                                LAngleLoc, RAngleLoc)) {
890
11
      return nullptr;
891
11
    }
892
18.8k
  }
893
894
  // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
895
  // Generate a meaningful error if the user forgot to put class before the
896
  // identifier, comma, or greater. Provide a fixit if the identifier, comma,
897
  // or greater appear immediately or after 'struct'. In the latter case,
898
  // replace the keyword with 'class'.
899
18.8k
  if (!TryConsumeToken(tok::kw_class)) {
900
113
    bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
901
113
    const Token &Next = Tok.is(tok::kw_struct) ? 
NextToken()5
:
Tok108
;
902
113
    if (Tok.is(tok::kw_typename)) {
903
78
      Diag(Tok.getLocation(),
904
78
           getLangOpts().CPlusPlus17
905
78
               ? 
diag::warn_cxx14_compat_template_template_param_typename63
906
78
               : 
diag::ext_template_template_param_typename15
)
907
78
        << (!getLangOpts().CPlusPlus17
908
78
                ? 
FixItHint::CreateReplacement(Tok.getLocation(), "class")15
909
78
                : 
FixItHint()63
);
910
78
    } else 
if (35
Next.isOneOf(tok::identifier, tok::comma, tok::greater,
911
35
                            tok::greatergreater, tok::ellipsis)) {
912
32
      Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
913
32
          << getLangOpts().CPlusPlus17
914
32
          << (Replace
915
32
                  ? 
FixItHint::CreateReplacement(Tok.getLocation(), "class")5
916
32
                  : 
FixItHint::CreateInsertion(Tok.getLocation(), "class ")27
);
917
32
    } else
918
3
      Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
919
3
          << getLangOpts().CPlusPlus17;
920
921
113
    if (Replace)
922
83
      ConsumeToken();
923
113
  }
924
925
  // Parse the ellipsis, if given.
926
18.8k
  SourceLocation EllipsisLoc;
927
18.8k
  if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
928
104
    Diag(EllipsisLoc,
929
104
         getLangOpts().CPlusPlus11
930
104
           ? 
diag::warn_cxx98_compat_variadic_templates102
931
104
           : 
diag::ext_variadic_templates2
);
932
933
  // Get the identifier, if given.
934
18.8k
  SourceLocation NameLoc = Tok.getLocation();
935
18.8k
  IdentifierInfo *ParamName = nullptr;
936
18.8k
  if (Tok.is(tok::identifier)) {
937
16.3k
    ParamName = Tok.getIdentifierInfo();
938
16.3k
    ConsumeToken();
939
16.3k
  } else 
if (2.50k
Tok.isOneOf(tok::equal, tok::comma, tok::greater,
940
2.50k
                         tok::greatergreater)) {
941
    // Unnamed template parameter. Don't have to do anything here, just
942
    // don't consume this token.
943
2.49k
  } else {
944
3
    Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
945
3
    return nullptr;
946
3
  }
947
948
  // Recover from misplaced ellipsis.
949
18.8k
  bool AlreadyHasEllipsis = EllipsisLoc.isValid();
950
18.8k
  if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
951
4
    DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
952
953
18.8k
  TemplateParameterList *ParamList =
954
18.8k
    Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
955
18.8k
                                       TemplateLoc, LAngleLoc,
956
18.8k
                                       TemplateParams,
957
18.8k
                                       RAngleLoc, nullptr);
958
959
  // Grab a default argument (if available).
960
  // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
961
  // we introduce the template parameter into the local scope.
962
18.8k
  SourceLocation EqualLoc;
963
18.8k
  ParsedTemplateArgument DefaultArg;
964
18.8k
  if (TryConsumeToken(tok::equal, EqualLoc)) {
965
8.94k
    DefaultArg = ParseTemplateTemplateArgument();
966
8.94k
    if (DefaultArg.isInvalid()) {
967
9
      Diag(Tok.getLocation(),
968
9
           diag::err_default_template_template_parameter_not_template);
969
9
      SkipUntil(tok::comma, tok::greater, tok::greatergreater,
970
9
                StopAtSemi | StopBeforeMatch);
971
9
    }
972
8.94k
  }
973
974
18.8k
  return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
975
18.8k
                                                ParamList, EllipsisLoc,
976
18.8k
                                                ParamName, NameLoc, Depth,
977
18.8k
                                                Position, EqualLoc, DefaultArg);
978
18.8k
}
979
980
/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
981
/// template parameters (e.g., in "template<int Size> class array;").
982
///
983
///       template-parameter:
984
///         ...
985
///         parameter-declaration
986
NamedDecl *
987
223k
Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
988
  // Parse the declaration-specifiers (i.e., the type).
989
  // FIXME: The type should probably be restricted in some way... Not all
990
  // declarators (parts of declarators?) are accepted for parameters.
991
223k
  DeclSpec DS(AttrFactory);
992
223k
  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
993
223k
                             DeclSpecContext::DSC_template_param);
994
995
  // Parse this as a typename.
996
223k
  Declarator ParamDecl(DS, DeclaratorContext::TemplateParam);
997
223k
  ParseDeclarator(ParamDecl);
998
223k
  if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
999
5
    Diag(Tok.getLocation(), diag::err_expected_template_parameter);
1000
5
    return nullptr;
1001
5
  }
1002
1003
  // Recover from misplaced ellipsis.
1004
223k
  SourceLocation EllipsisLoc;
1005
223k
  if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1006
4
    DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
1007
1008
  // If there is a default value, parse it.
1009
  // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
1010
  // we introduce the template parameter into the local scope.
1011
223k
  SourceLocation EqualLoc;
1012
223k
  ExprResult DefaultArg;
1013
223k
  if (TryConsumeToken(tok::equal, EqualLoc)) {
1014
68.8k
    if (Tok.is(tok::l_paren) && 
NextToken().is(tok::l_brace)596
) {
1015
3
      Diag(Tok.getLocation(), diag::err_stmt_expr_in_default_arg) << 1;
1016
3
      SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
1017
68.8k
    } else {
1018
      // C++ [temp.param]p15:
1019
      //   When parsing a default template-argument for a non-type
1020
      //   template-parameter, the first non-nested > is taken as the
1021
      //   end of the template-parameter-list rather than a greater-than
1022
      //   operator.
1023
68.8k
      GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
1024
68.8k
      EnterExpressionEvaluationContext ConstantEvaluated(
1025
68.8k
          Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1026
68.8k
      DefaultArg =
1027
68.8k
          Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
1028
68.8k
      if (DefaultArg.isInvalid())
1029
17
        SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
1030
68.8k
    }
1031
68.8k
  }
1032
1033
  // Create the parameter.
1034
223k
  return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
1035
223k
                                               Depth, Position, EqualLoc,
1036
223k
                                               DefaultArg.get());
1037
223k
}
1038
1039
void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
1040
                                       SourceLocation CorrectLoc,
1041
                                       bool AlreadyHasEllipsis,
1042
31
                                       bool IdentifierHasName) {
1043
31
  FixItHint Insertion;
1044
31
  if (!AlreadyHasEllipsis)
1045
19
    Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
1046
31
  Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
1047
31
      << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
1048
31
      << !IdentifierHasName;
1049
31
}
1050
1051
void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
1052
23
                                                   Declarator &D) {
1053
23
  assert(EllipsisLoc.isValid());
1054
0
  bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
1055
23
  if (!AlreadyHasEllipsis)
1056
15
    D.setEllipsisLoc(EllipsisLoc);
1057
23
  DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
1058
23
                            AlreadyHasEllipsis, D.hasName());
1059
23
}
1060
1061
/// Parses a '>' at the end of a template list.
1062
///
1063
/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
1064
/// to determine if these tokens were supposed to be a '>' followed by
1065
/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
1066
///
1067
/// \param RAngleLoc the location of the consumed '>'.
1068
///
1069
/// \param ConsumeLastToken if true, the '>' is consumed.
1070
///
1071
/// \param ObjCGenericList if true, this is the '>' closing an Objective-C
1072
/// type parameter or type argument list, rather than a C++ template parameter
1073
/// or argument list.
1074
///
1075
/// \returns true, if current token does not start with '>', false otherwise.
1076
bool Parser::ParseGreaterThanInTemplateList(SourceLocation LAngleLoc,
1077
                                            SourceLocation &RAngleLoc,
1078
                                            bool ConsumeLastToken,
1079
2.92M
                                            bool ObjCGenericList) {
1080
  // What will be left once we've consumed the '>'.
1081
2.92M
  tok::TokenKind RemainingToken;
1082
2.92M
  const char *ReplacementStr = "> >";
1083
2.92M
  bool MergeWithNextToken = false;
1084
1085
2.92M
  switch (Tok.getKind()) {
1086
46
  default:
1087
46
    Diag(getEndOfPreviousToken(), diag::err_expected) << tok::greater;
1088
46
    Diag(LAngleLoc, diag::note_matching) << tok::less;
1089
46
    return true;
1090
1091
2.91M
  case tok::greater:
1092
    // Determine the location of the '>' token. Only consume this token
1093
    // if the caller asked us to.
1094
2.91M
    RAngleLoc = Tok.getLocation();
1095
2.91M
    if (ConsumeLastToken)
1096
131k
      ConsumeToken();
1097
2.91M
    return false;
1098
1099
17.8k
  case tok::greatergreater:
1100
17.8k
    RemainingToken = tok::greater;
1101
17.8k
    break;
1102
1103
14
  case tok::greatergreatergreater:
1104
14
    RemainingToken = tok::greatergreater;
1105
14
    break;
1106
1107
36
  case tok::greaterequal:
1108
36
    RemainingToken = tok::equal;
1109
36
    ReplacementStr = "> =";
1110
1111
    // Join two adjacent '=' tokens into one, for cases like:
1112
    //   void (*p)() = f<int>;
1113
    //   return f<int>==p;
1114
36
    if (NextToken().is(tok::equal) &&
1115
36
        
areTokensAdjacent(Tok, NextToken())19
) {
1116
19
      RemainingToken = tok::equalequal;
1117
19
      MergeWithNextToken = true;
1118
19
    }
1119
36
    break;
1120
1121
25
  case tok::greatergreaterequal:
1122
25
    RemainingToken = tok::greaterequal;
1123
25
    break;
1124
2.92M
  }
1125
1126
  // This template-id is terminated by a token that starts with a '>'.
1127
  // Outside C++11 and Objective-C, this is now error recovery.
1128
  //
1129
  // C++11 allows this when the token is '>>', and in CUDA + C++11 mode, we
1130
  // extend that treatment to also apply to the '>>>' token.
1131
  //
1132
  // Objective-C allows this in its type parameter / argument lists.
1133
1134
17.9k
  SourceLocation TokBeforeGreaterLoc = PrevTokLocation;
1135
17.9k
  SourceLocation TokLoc = Tok.getLocation();
1136
17.9k
  Token Next = NextToken();
1137
1138
  // Whether splitting the current token after the '>' would undesirably result
1139
  // in the remaining token pasting with the token after it. This excludes the
1140
  // MergeWithNextToken cases, which we've already handled.
1141
17.9k
  bool PreventMergeWithNextToken =
1142
17.9k
      (RemainingToken == tok::greater ||
1143
17.9k
       
RemainingToken == tok::greatergreater75
) &&
1144
17.9k
      (Next.isOneOf(tok::greater, tok::greatergreater,
1145
17.8k
                    tok::greatergreatergreater, tok::equal, tok::greaterequal,
1146
17.8k
                    tok::greatergreaterequal, tok::equalequal)) &&
1147
17.9k
      
areTokensAdjacent(Tok, Next)2.73k
;
1148
1149
  // Diagnose this situation as appropriate.
1150
17.9k
  if (!ObjCGenericList) {
1151
    // The source range of the replaced token(s).
1152
16.9k
    CharSourceRange ReplacementRange = CharSourceRange::getCharRange(
1153
16.9k
        TokLoc, Lexer::AdvanceToTokenCharacter(TokLoc, 2, PP.getSourceManager(),
1154
16.9k
                                               getLangOpts()));
1155
1156
    // A hint to put a space between the '>>'s. In order to make the hint as
1157
    // clear as possible, we include the characters either side of the space in
1158
    // the replacement, rather than just inserting a space at SecondCharLoc.
1159
16.9k
    FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
1160
16.9k
                                                   ReplacementStr);
1161
1162
    // A hint to put another space after the token, if it would otherwise be
1163
    // lexed differently.
1164
16.9k
    FixItHint Hint2;
1165
16.9k
    if (PreventMergeWithNextToken)
1166
2.69k
      Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
1167
1168
16.9k
    unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
1169
16.9k
    if (getLangOpts().CPlusPlus11 &&
1170
16.9k
        
(16.9k
Tok.is(tok::greatergreater)16.9k
||
Tok.is(tok::greatergreatergreater)55
))
1171
16.8k
      DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
1172
81
    else if (Tok.is(tok::greaterequal))
1173
36
      DiagId = diag::err_right_angle_bracket_equal_needs_space;
1174
16.9k
    Diag(TokLoc, DiagId) << Hint1 << Hint2;
1175
16.9k
  }
1176
1177
  // Find the "length" of the resulting '>' token. This is not always 1, as it
1178
  // can contain escaped newlines.
1179
17.9k
  unsigned GreaterLength = Lexer::getTokenPrefixLength(
1180
17.9k
      TokLoc, 1, PP.getSourceManager(), getLangOpts());
1181
1182
  // Annotate the source buffer to indicate that we split the token after the
1183
  // '>'. This allows us to properly find the end of, and extract the spelling
1184
  // of, the '>' token later.
1185
17.9k
  RAngleLoc = PP.SplitToken(TokLoc, GreaterLength);
1186
1187
  // Strip the initial '>' from the token.
1188
17.9k
  bool CachingTokens = PP.IsPreviousCachedToken(Tok);
1189
1190
17.9k
  Token Greater = Tok;
1191
17.9k
  Greater.setLocation(RAngleLoc);
1192
17.9k
  Greater.setKind(tok::greater);
1193
17.9k
  Greater.setLength(GreaterLength);
1194
1195
17.9k
  unsigned OldLength = Tok.getLength();
1196
17.9k
  if (MergeWithNextToken) {
1197
19
    ConsumeToken();
1198
19
    OldLength += Tok.getLength();
1199
19
  }
1200
1201
17.9k
  Tok.setKind(RemainingToken);
1202
17.9k
  Tok.setLength(OldLength - GreaterLength);
1203
1204
  // Split the second token if lexing it normally would lex a different token
1205
  // (eg, the fifth token in 'A<B>>>' should re-lex as '>', not '>>').
1206
17.9k
  SourceLocation AfterGreaterLoc = TokLoc.getLocWithOffset(GreaterLength);
1207
17.9k
  if (PreventMergeWithNextToken)
1208
2.69k
    AfterGreaterLoc = PP.SplitToken(AfterGreaterLoc, Tok.getLength());
1209
17.9k
  Tok.setLocation(AfterGreaterLoc);
1210
1211
  // Update the token cache to match what we just did if necessary.
1212
17.9k
  if (CachingTokens) {
1213
    // If the previous cached token is being merged, delete it.
1214
12.8k
    if (MergeWithNextToken)
1215
19
      PP.ReplacePreviousCachedToken({});
1216
1217
12.8k
    if (ConsumeLastToken)
1218
965
      PP.ReplacePreviousCachedToken({Greater, Tok});
1219
11.8k
    else
1220
11.8k
      PP.ReplacePreviousCachedToken({Greater});
1221
12.8k
  }
1222
1223
17.9k
  if (ConsumeLastToken) {
1224
965
    PrevTokLocation = RAngleLoc;
1225
16.9k
  } else {
1226
16.9k
    PrevTokLocation = TokBeforeGreaterLoc;
1227
16.9k
    PP.EnterToken(Tok, /*IsReinject=*/true);
1228
16.9k
    Tok = Greater;
1229
16.9k
  }
1230
1231
17.9k
  return false;
1232
2.92M
}
1233
1234
/// Parses a template-id that after the template name has
1235
/// already been parsed.
1236
///
1237
/// This routine takes care of parsing the enclosed template argument
1238
/// list ('<' template-parameter-list [opt] '>') and placing the
1239
/// results into a form that can be transferred to semantic analysis.
1240
///
1241
/// \param ConsumeLastToken if true, then we will consume the last
1242
/// token that forms the template-id. Otherwise, we will leave the
1243
/// last token in the stream (e.g., so that it can be replaced with an
1244
/// annotation token).
1245
bool Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
1246
                                              SourceLocation &LAngleLoc,
1247
                                              TemplateArgList &TemplateArgs,
1248
                                              SourceLocation &RAngleLoc,
1249
2.69M
                                              TemplateTy Template) {
1250
2.69M
  assert(Tok.is(tok::less) && "Must have already parsed the template-name");
1251
1252
  // Consume the '<'.
1253
0
  LAngleLoc = ConsumeToken();
1254
1255
  // Parse the optional template-argument-list.
1256
2.69M
  bool Invalid = false;
1257
2.69M
  {
1258
2.69M
    GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
1259
2.69M
    if (!Tok.isOneOf(tok::greater, tok::greatergreater,
1260
2.69M
                     tok::greatergreatergreater, tok::greaterequal,
1261
2.69M
                     tok::greatergreaterequal))
1262
2.68M
      Invalid = ParseTemplateArgumentList(TemplateArgs, Template, LAngleLoc);
1263
1264
2.69M
    if (Invalid) {
1265
      // Try to find the closing '>'.
1266
315
      if (getLangOpts().CPlusPlus11)
1267
305
        SkipUntil(tok::greater, tok::greatergreater,
1268
305
                  tok::greatergreatergreater, StopAtSemi | StopBeforeMatch);
1269
10
      else
1270
10
        SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
1271
315
    }
1272
2.69M
  }
1273
1274
2.69M
  return ParseGreaterThanInTemplateList(LAngleLoc, RAngleLoc, ConsumeLastToken,
1275
2.69M
                                        /*ObjCGenericList=*/false) ||
1276
2.69M
         
Invalid2.69M
;
1277
2.69M
}
1278
1279
/// Replace the tokens that form a simple-template-id with an
1280
/// annotation token containing the complete template-id.
1281
///
1282
/// The first token in the stream must be the name of a template that
1283
/// is followed by a '<'. This routine will parse the complete
1284
/// simple-template-id and replace the tokens with a single annotation
1285
/// token with one of two different kinds: if the template-id names a
1286
/// type (and \p AllowTypeAnnotation is true), the annotation token is
1287
/// a type annotation that includes the optional nested-name-specifier
1288
/// (\p SS). Otherwise, the annotation token is a template-id
1289
/// annotation that does not include the optional
1290
/// nested-name-specifier.
1291
///
1292
/// \param Template  the declaration of the template named by the first
1293
/// token (an identifier), as returned from \c Action::isTemplateName().
1294
///
1295
/// \param TNK the kind of template that \p Template
1296
/// refers to, as returned from \c Action::isTemplateName().
1297
///
1298
/// \param SS if non-NULL, the nested-name-specifier that precedes
1299
/// this template name.
1300
///
1301
/// \param TemplateKWLoc if valid, specifies that this template-id
1302
/// annotation was preceded by the 'template' keyword and gives the
1303
/// location of that keyword. If invalid (the default), then this
1304
/// template-id was not preceded by a 'template' keyword.
1305
///
1306
/// \param AllowTypeAnnotation if true (the default), then a
1307
/// simple-template-id that refers to a class template, template
1308
/// template parameter, or other template that produces a type will be
1309
/// replaced with a type annotation token. Otherwise, the
1310
/// simple-template-id is always replaced with a template-id
1311
/// annotation token.
1312
///
1313
/// \param TypeConstraint if true, then this is actually a type-constraint,
1314
/// meaning that the template argument list can be omitted (and the template in
1315
/// question must be a concept).
1316
///
1317
/// If an unrecoverable parse error occurs and no annotation token can be
1318
/// formed, this function returns true.
1319
///
1320
bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
1321
                                     CXXScopeSpec &SS,
1322
                                     SourceLocation TemplateKWLoc,
1323
                                     UnqualifiedId &TemplateName,
1324
                                     bool AllowTypeAnnotation,
1325
2.69M
                                     bool TypeConstraint) {
1326
2.69M
  assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
1327
0
  assert((Tok.is(tok::less) || TypeConstraint) &&
1328
2.69M
         "Parser isn't at the beginning of a template-id");
1329
0
  assert(!(TypeConstraint && AllowTypeAnnotation) && "type-constraint can't be "
1330
2.69M
                                                     "a type annotation");
1331
0
  assert((!TypeConstraint || TNK == TNK_Concept_template) && "type-constraint "
1332
2.69M
         "must accompany a concept name");
1333
0
  assert((Template || TNK == TNK_Non_template) && "missing template name");
1334
1335
  // Consume the template-name.
1336
0
  SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
1337
1338
  // Parse the enclosed template argument list.
1339
2.69M
  SourceLocation LAngleLoc, RAngleLoc;
1340
2.69M
  TemplateArgList TemplateArgs;
1341
2.69M
  bool ArgsInvalid = false;
1342
2.69M
  if (!TypeConstraint || 
Tok.is(tok::less)192
) {
1343
2.69M
    ArgsInvalid = ParseTemplateIdAfterTemplateName(
1344
2.69M
        false, LAngleLoc, TemplateArgs, RAngleLoc, Template);
1345
    // If we couldn't recover from invalid arguments, don't form an annotation
1346
    // token -- we don't know how much to annotate.
1347
    // FIXME: This can lead to duplicate diagnostics if we retry parsing this
1348
    // template-id in another context. Try to annotate anyway?
1349
2.69M
    if (RAngleLoc.isInvalid())
1350
32
      return true;
1351
2.69M
  }
1352
1353
2.69M
  ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1354
1355
  // Build the annotation token.
1356
2.69M
  if (TNK == TNK_Type_template && 
AllowTypeAnnotation2.50M
) {
1357
0
    TypeResult Type = ArgsInvalid
1358
0
                          ? TypeError()
1359
0
                          : Actions.ActOnTemplateIdType(
1360
0
                                getCurScope(), SS, TemplateKWLoc, Template,
1361
0
                                TemplateName.Identifier, TemplateNameLoc,
1362
0
                                LAngleLoc, TemplateArgsPtr, RAngleLoc);
1363
1364
0
    Tok.setKind(tok::annot_typename);
1365
0
    setTypeAnnotation(Tok, Type);
1366
0
    if (SS.isNotEmpty())
1367
0
      Tok.setLocation(SS.getBeginLoc());
1368
0
    else if (TemplateKWLoc.isValid())
1369
0
      Tok.setLocation(TemplateKWLoc);
1370
0
    else
1371
0
      Tok.setLocation(TemplateNameLoc);
1372
2.69M
  } else {
1373
    // Build a template-id annotation token that can be processed
1374
    // later.
1375
2.69M
    Tok.setKind(tok::annot_template_id);
1376
1377
2.69M
    IdentifierInfo *TemplateII =
1378
2.69M
        TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1379
2.69M
            ? 
TemplateName.Identifier2.69M
1380
2.69M
            : 
nullptr61
;
1381
1382
2.69M
    OverloadedOperatorKind OpKind =
1383
2.69M
        TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1384
2.69M
            ? 
OO_None2.69M
1385
2.69M
            : 
TemplateName.OperatorFunctionId.Operator61
;
1386
1387
2.69M
    TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
1388
2.69M
        TemplateKWLoc, TemplateNameLoc, TemplateII, OpKind, Template, TNK,
1389
2.69M
        LAngleLoc, RAngleLoc, TemplateArgs, ArgsInvalid, TemplateIds);
1390
1391
2.69M
    Tok.setAnnotationValue(TemplateId);
1392
2.69M
    if (TemplateKWLoc.isValid())
1393
18.0k
      Tok.setLocation(TemplateKWLoc);
1394
2.67M
    else
1395
2.67M
      Tok.setLocation(TemplateNameLoc);
1396
2.69M
  }
1397
1398
  // Common fields for the annotation token
1399
2.69M
  Tok.setAnnotationEndLoc(RAngleLoc);
1400
1401
  // In case the tokens were cached, have Preprocessor replace them with the
1402
  // annotation token.
1403
2.69M
  PP.AnnotateCachedTokens(Tok);
1404
2.69M
  return false;
1405
2.69M
}
1406
1407
/// Replaces a template-id annotation token with a type
1408
/// annotation token.
1409
///
1410
/// If there was a failure when forming the type from the template-id,
1411
/// a type annotation token will still be created, but will have a
1412
/// NULL type pointer to signify an error.
1413
///
1414
/// \param SS The scope specifier appearing before the template-id, if any.
1415
///
1416
/// \param IsClassName Is this template-id appearing in a context where we
1417
/// know it names a class, such as in an elaborated-type-specifier or
1418
/// base-specifier? ('typename' and 'template' are unneeded and disallowed
1419
/// in those contexts.)
1420
void Parser::AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS,
1421
1.19M
                                           bool IsClassName) {
1422
1.19M
  assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1423
1424
0
  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1425
1.19M
  assert(TemplateId->mightBeType() &&
1426
1.19M
         "Only works for type and dependent templates");
1427
1428
0
  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1429
1.19M
                                     TemplateId->NumArgs);
1430
1431
1.19M
  TypeResult Type =
1432
1.19M
      TemplateId->isInvalid()
1433
1.19M
          ? 
TypeError()146
1434
1.19M
          : Actions.ActOnTemplateIdType(
1435
1.19M
                getCurScope(), SS, TemplateId->TemplateKWLoc,
1436
1.19M
                TemplateId->Template, TemplateId->Name,
1437
1.19M
                TemplateId->TemplateNameLoc, TemplateId->LAngleLoc,
1438
1.19M
                TemplateArgsPtr, TemplateId->RAngleLoc,
1439
1.19M
                /*IsCtorOrDtorName*/ false, IsClassName);
1440
  // Create the new "type" annotation token.
1441
1.19M
  Tok.setKind(tok::annot_typename);
1442
1.19M
  setTypeAnnotation(Tok, Type);
1443
1.19M
  if (SS.isNotEmpty()) // it was a C++ qualified type name.
1444
48.2k
    Tok.setLocation(SS.getBeginLoc());
1445
  // End location stays the same
1446
1447
  // Replace the template-id annotation token, and possible the scope-specifier
1448
  // that precedes it, with the typename annotation token.
1449
1.19M
  PP.AnnotateCachedTokens(Tok);
1450
1.19M
}
1451
1452
/// Determine whether the given token can end a template argument.
1453
224k
static bool isEndOfTemplateArgument(Token Tok) {
1454
  // FIXME: Handle '>>>'.
1455
224k
  return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater,
1456
224k
                     tok::greatergreatergreater);
1457
224k
}
1458
1459
/// Parse a C++ template template argument.
1460
731k
ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1461
731k
  if (!Tok.is(tok::identifier) && 
!Tok.is(tok::coloncolon)713k
&&
1462
731k
      
!Tok.is(tok::annot_cxxscope)713k
)
1463
499k
    return ParsedTemplateArgument();
1464
1465
  // C++0x [temp.arg.template]p1:
1466
  //   A template-argument for a template template-parameter shall be the name
1467
  //   of a class template or an alias template, expressed as id-expression.
1468
  //
1469
  // We parse an id-expression that refers to a class template or alias
1470
  // template. The grammar we parse is:
1471
  //
1472
  //   nested-name-specifier[opt] template[opt] identifier ...[opt]
1473
  //
1474
  // followed by a token that terminates a template argument, such as ',',
1475
  // '>', or (in some cases) '>>'.
1476
232k
  CXXScopeSpec SS; // nested-name-specifier, if present
1477
232k
  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1478
232k
                                 /*ObjectHasErrors=*/false,
1479
232k
                                 /*EnteringContext=*/false);
1480
1481
232k
  ParsedTemplateArgument Result;
1482
232k
  SourceLocation EllipsisLoc;
1483
232k
  if (SS.isSet() && 
Tok.is(tok::kw_template)213k
) {
1484
    // Parse the optional 'template' keyword following the
1485
    // nested-name-specifier.
1486
485
    SourceLocation TemplateKWLoc = ConsumeToken();
1487
1488
485
    if (Tok.is(tok::identifier)) {
1489
      // We appear to have a dependent template name.
1490
485
      UnqualifiedId Name;
1491
485
      Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1492
485
      ConsumeToken(); // the identifier
1493
1494
485
      TryConsumeToken(tok::ellipsis, EllipsisLoc);
1495
1496
      // If the next token signals the end of a template argument, then we have
1497
      // a (possibly-dependent) template name that could be a template template
1498
      // argument.
1499
485
      TemplateTy Template;
1500
485
      if (isEndOfTemplateArgument(Tok) &&
1501
485
          Actions.ActOnTemplateName(getCurScope(), SS, TemplateKWLoc, Name,
1502
485
                                    /*ObjectType=*/nullptr,
1503
485
                                    /*EnteringContext=*/false, Template))
1504
485
        Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1505
485
    }
1506
231k
  } else if (Tok.is(tok::identifier)) {
1507
    // We may have a (non-dependent) template name.
1508
224k
    TemplateTy Template;
1509
224k
    UnqualifiedId Name;
1510
224k
    Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1511
224k
    ConsumeToken(); // the identifier
1512
1513
224k
    TryConsumeToken(tok::ellipsis, EllipsisLoc);
1514
1515
224k
    if (isEndOfTemplateArgument(Tok)) {
1516
165k
      bool MemberOfUnknownSpecialization;
1517
165k
      TemplateNameKind TNK = Actions.isTemplateName(
1518
165k
          getCurScope(), SS,
1519
165k
          /*hasTemplateKeyword=*/false, Name,
1520
165k
          /*ObjectType=*/nullptr,
1521
165k
          /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
1522
165k
      if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1523
        // We have an id-expression that refers to a class template or
1524
        // (C++0x) alias template.
1525
18.1k
        Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1526
18.1k
      }
1527
165k
    }
1528
224k
  }
1529
1530
  // If this is a pack expansion, build it as such.
1531
232k
  if (EllipsisLoc.isValid() && 
!Result.isInvalid()3.97k
)
1532
21
    Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1533
1534
232k
  return Result;
1535
731k
}
1536
1537
/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1538
///
1539
///       template-argument: [C++ 14.2]
1540
///         constant-expression
1541
///         type-id
1542
///         id-expression
1543
4.28M
ParsedTemplateArgument Parser::ParseTemplateArgument() {
1544
  // C++ [temp.arg]p2:
1545
  //   In a template-argument, an ambiguity between a type-id and an
1546
  //   expression is resolved to a type-id, regardless of the form of
1547
  //   the corresponding template-parameter.
1548
  //
1549
  // Therefore, we initially try to parse a type-id - and isCXXTypeId might look
1550
  // up and annotate an identifier as an id-expression during disambiguation,
1551
  // so enter the appropriate context for a constant expression template
1552
  // argument before trying to disambiguate.
1553
1554
4.28M
  EnterExpressionEvaluationContext EnterConstantEvaluated(
1555
4.28M
    Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated,
1556
4.28M
    /*LambdaContextDecl=*/nullptr,
1557
4.28M
    /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
1558
4.28M
  if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1559
3.55M
    TypeResult TypeArg = ParseTypeName(
1560
3.55M
        /*Range=*/nullptr, DeclaratorContext::TemplateArg);
1561
3.55M
    return Actions.ActOnTemplateTypeArgument(TypeArg);
1562
3.55M
  }
1563
1564
  // Try to parse a template template argument.
1565
723k
  {
1566
723k
    TentativeParsingAction TPA(*this);
1567
1568
723k
    ParsedTemplateArgument TemplateTemplateArgument
1569
723k
      = ParseTemplateTemplateArgument();
1570
723k
    if (!TemplateTemplateArgument.isInvalid()) {
1571
9.70k
      TPA.Commit();
1572
9.70k
      return TemplateTemplateArgument;
1573
9.70k
    }
1574
1575
    // Revert this tentative parse to parse a non-type template argument.
1576
713k
    TPA.Revert();
1577
713k
  }
1578
1579
  // Parse a non-type template argument.
1580
0
  SourceLocation Loc = Tok.getLocation();
1581
713k
  ExprResult ExprArg = ParseConstantExpressionInExprEvalContext(MaybeTypeCast);
1582
713k
  if (ExprArg.isInvalid() || 
!ExprArg.get()713k
) {
1583
137
    return ParsedTemplateArgument();
1584
137
  }
1585
1586
713k
  return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1587
713k
                                ExprArg.get(), Loc);
1588
713k
}
1589
1590
/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1591
/// (C++ [temp.names]). Returns true if there was an error.
1592
///
1593
///       template-argument-list: [C++ 14.2]
1594
///         template-argument
1595
///         template-argument-list ',' template-argument
1596
///
1597
/// \param Template is only used for code completion, and may be null.
1598
bool Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
1599
                                       TemplateTy Template,
1600
2.68M
                                       SourceLocation OpenLoc) {
1601
1602
2.68M
  ColonProtectionRAIIObject ColonProtection(*this, false);
1603
1604
2.68M
  auto RunSignatureHelp = [&] {
1605
6
    if (!Template)
1606
0
      return QualType();
1607
6
    CalledSignatureHelp = true;
1608
6
    return Actions.ProduceTemplateArgumentSignatureHelp(Template, TemplateArgs,
1609
6
                                                        OpenLoc);
1610
6
  };
1611
1612
4.28M
  do {
1613
4.28M
    PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
1614
4.28M
    ParsedTemplateArgument Arg = ParseTemplateArgument();
1615
4.28M
    SourceLocation EllipsisLoc;
1616
4.28M
    if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1617
154k
      Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1618
1619
4.28M
    if (Arg.isInvalid()) {
1620
315
      if (PP.isCodeCompletionReached() && 
!CalledSignatureHelp6
)
1621
0
        RunSignatureHelp();
1622
315
      return true;
1623
315
    }
1624
1625
    // Save this template argument.
1626
4.28M
    TemplateArgs.push_back(Arg);
1627
1628
    // If the next token is a comma, consume it and keep reading
1629
    // arguments.
1630
4.28M
  } while (TryConsumeToken(tok::comma));
1631
1632
2.68M
  return false;
1633
2.68M
}
1634
1635
/// Parse a C++ explicit template instantiation
1636
/// (C++ [temp.explicit]).
1637
///
1638
///       explicit-instantiation:
1639
///         'extern' [opt] 'template' declaration
1640
///
1641
/// Note that the 'extern' is a GNU extension and C++11 feature.
1642
Decl *Parser::ParseExplicitInstantiation(DeclaratorContext Context,
1643
                                         SourceLocation ExternLoc,
1644
                                         SourceLocation TemplateLoc,
1645
                                         SourceLocation &DeclEnd,
1646
                                         ParsedAttributes &AccessAttrs,
1647
42.0k
                                         AccessSpecifier AS) {
1648
  // This isn't really required here.
1649
42.0k
  ParsingDeclRAIIObject
1650
42.0k
    ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1651
1652
42.0k
  return ParseSingleDeclarationAfterTemplate(
1653
42.0k
      Context, ParsedTemplateInfo(ExternLoc, TemplateLoc),
1654
42.0k
      ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
1655
42.0k
}
1656
1657
9
SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1658
9
  if (TemplateParams)
1659
8
    return getTemplateParamsRange(TemplateParams->data(),
1660
8
                                  TemplateParams->size());
1661
1662
1
  SourceRange R(TemplateLoc);
1663
1
  if (ExternLoc.isValid())
1664
0
    R.setBegin(ExternLoc);
1665
1
  return R;
1666
9
}
1667
1668
420
void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1669
420
  ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1670
420
}
1671
1672
/// Late parse a C++ function template in Microsoft mode.
1673
420
void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1674
420
  if (!LPT.D)
1675
0
     return;
1676
1677
  // Destroy TemplateIdAnnotations when we're done, if possible.
1678
420
  DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
1679
1680
  // Get the FunctionDecl.
1681
420
  FunctionDecl *FunD = LPT.D->getAsFunction();
1682
  // Track template parameter depth.
1683
420
  TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1684
1685
  // To restore the context after late parsing.
1686
420
  Sema::ContextRAII GlobalSavedContext(
1687
420
      Actions, Actions.Context.getTranslationUnitDecl());
1688
1689
420
  MultiParseScope Scopes(*this);
1690
1691
  // Get the list of DeclContexts to reenter.
1692
420
  SmallVector<DeclContext*, 4> DeclContextsToReenter;
1693
1.26k
  for (DeclContext *DC = FunD; DC && !DC->isTranslationUnit();
1694
845
       DC = DC->getLexicalParent())
1695
845
    DeclContextsToReenter.push_back(DC);
1696
1697
  // Reenter scopes from outermost to innermost.
1698
845
  for (DeclContext *DC : reverse(DeclContextsToReenter)) {
1699
845
    CurTemplateDepthTracker.addDepth(
1700
845
        ReenterTemplateScopes(Scopes, cast<Decl>(DC)));
1701
845
    Scopes.Enter(Scope::DeclScope);
1702
    // We'll reenter the function context itself below.
1703
845
    if (DC != FunD)
1704
425
      Actions.PushDeclContext(Actions.getCurScope(), DC);
1705
845
  }
1706
1707
420
  assert(!LPT.Toks.empty() && "Empty body!");
1708
1709
  // Append the current token at the end of the new token stream so that it
1710
  // doesn't get lost.
1711
0
  LPT.Toks.push_back(Tok);
1712
420
  PP.EnterTokenStream(LPT.Toks, true, /*IsReinject*/true);
1713
1714
  // Consume the previously pushed token.
1715
420
  ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1716
420
  assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1717
420
         "Inline method not starting with '{', ':' or 'try'");
1718
1719
  // Parse the method body. Function body parsing code is similar enough
1720
  // to be re-used for method bodies as well.
1721
0
  ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
1722
420
                               Scope::CompoundStmtScope);
1723
1724
  // Recreate the containing function DeclContext.
1725
420
  Sema::ContextRAII FunctionSavedContext(Actions, FunD->getLexicalParent());
1726
1727
420
  Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1728
1729
420
  if (Tok.is(tok::kw_try)) {
1730
0
    ParseFunctionTryBlock(LPT.D, FnScope);
1731
420
  } else {
1732
420
    if (Tok.is(tok::colon))
1733
15
      ParseConstructorInitializer(LPT.D);
1734
405
    else
1735
405
      Actions.ActOnDefaultCtorInitializers(LPT.D);
1736
1737
420
    if (Tok.is(tok::l_brace)) {
1738
420
      assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1739
420
              cast<FunctionTemplateDecl>(LPT.D)
1740
420
                      ->getTemplateParameters()
1741
420
                      ->getDepth() == TemplateParameterDepth - 1) &&
1742
420
             "TemplateParameterDepth should be greater than the depth of "
1743
420
             "current template being instantiated!");
1744
0
      ParseFunctionStatementBody(LPT.D, FnScope);
1745
420
      Actions.UnmarkAsLateParsedTemplate(FunD);
1746
420
    } else
1747
0
      Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1748
420
  }
1749
420
}
1750
1751
/// Lex a delayed template function for late parsing.
1752
625
void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1753
625
  tok::TokenKind kind = Tok.getKind();
1754
625
  if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1755
    // Consume everything up to (and including) the matching right brace.
1756
625
    ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1757
625
  }
1758
1759
  // If we're in a function-try-block, we need to store all the catch blocks.
1760
625
  if (kind == tok::kw_try) {
1761
0
    while (Tok.is(tok::kw_catch)) {
1762
0
      ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1763
0
      ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1764
0
    }
1765
0
  }
1766
625
}
1767
1768
/// We've parsed something that could plausibly be intended to be a template
1769
/// name (\p LHS) followed by a '<' token, and the following code can't possibly
1770
/// be an expression. Determine if this is likely to be a template-id and if so,
1771
/// diagnose it.
1772
17
bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
1773
17
  TentativeParsingAction TPA(*this);
1774
  // FIXME: We could look at the token sequence in a lot more detail here.
1775
17
  if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater,
1776
17
                StopAtSemi | StopBeforeMatch)) {
1777
17
    TPA.Commit();
1778
1779
17
    SourceLocation Greater;
1780
17
    ParseGreaterThanInTemplateList(Less, Greater, true, false);
1781
17
    Actions.diagnoseExprIntendedAsTemplateName(getCurScope(), LHS,
1782
17
                                               Less, Greater);
1783
17
    return true;
1784
17
  }
1785
1786
  // There's no matching '>' token, this probably isn't supposed to be
1787
  // interpreted as a template-id. Parse it as an (ill-formed) comparison.
1788
0
  TPA.Revert();
1789
0
  return false;
1790
17
}
1791
1792
194k
void Parser::checkPotentialAngleBracket(ExprResult &PotentialTemplateName) {
1793
194k
  assert(Tok.is(tok::less) && "not at a potential angle bracket");
1794
1795
0
  bool DependentTemplateName = false;
1796
194k
  if (!Actions.mightBeIntendedToBeTemplateName(PotentialTemplateName,
1797
194k
                                               DependentTemplateName))
1798
15.0k
    return;
1799
1800
  // OK, this might be a name that the user intended to be parsed as a
1801
  // template-name, followed by a '<' token. Check for some easy cases.
1802
1803
  // If we have potential_template<>, then it's supposed to be a template-name.
1804
179k
  if (NextToken().is(tok::greater) ||
1805
179k
      
(179k
getLangOpts().CPlusPlus11179k
&&
1806
179k
       
NextToken().isOneOf(tok::greatergreater, tok::greatergreatergreater)169k
)) {
1807
1
    SourceLocation Less = ConsumeToken();
1808
1
    SourceLocation Greater;
1809
1
    ParseGreaterThanInTemplateList(Less, Greater, true, false);
1810
1
    Actions.diagnoseExprIntendedAsTemplateName(
1811
1
        getCurScope(), PotentialTemplateName, Less, Greater);
1812
    // FIXME: Perform error recovery.
1813
1
    PotentialTemplateName = ExprError();
1814
1
    return;
1815
1
  }
1816
1817
  // If we have 'potential_template<type-id', assume it's supposed to be a
1818
  // template-name if there's a matching '>' later on.
1819
179k
  {
1820
    // FIXME: Avoid the tentative parse when NextToken() can't begin a type.
1821
179k
    TentativeParsingAction TPA(*this);
1822
179k
    SourceLocation Less = ConsumeToken();
1823
179k
    if (isTypeIdUnambiguously() &&
1824
179k
        
diagnoseUnknownTemplateId(PotentialTemplateName, Less)14
) {
1825
14
      TPA.Commit();
1826
      // FIXME: Perform error recovery.
1827
14
      PotentialTemplateName = ExprError();
1828
14
      return;
1829
14
    }
1830
179k
    TPA.Revert();
1831
179k
  }
1832
1833
  // Otherwise, remember that we saw this in case we see a potentially-matching
1834
  // '>' token later on.
1835
0
  AngleBracketTracker::Priority Priority =
1836
179k
      (DependentTemplateName ? 
AngleBracketTracker::DependentName3.06k
1837
179k
                             : 
AngleBracketTracker::PotentialTypo176k
) |
1838
179k
      (Tok.hasLeadingSpace() ? 
AngleBracketTracker::SpaceBeforeLess165k
1839
179k
                             : 
AngleBracketTracker::NoSpaceBeforeLess14.6k
);
1840
179k
  AngleBrackets.add(*this, PotentialTemplateName.get(), Tok.getLocation(),
1841
179k
                    Priority);
1842
179k
}
1843
1844
bool Parser::checkPotentialAngleBracketDelimiter(
1845
63
    const AngleBracketTracker::Loc &LAngle, const Token &OpToken) {
1846
  // If a comma in an expression context is followed by a type that can be a
1847
  // template argument and cannot be an expression, then this is ill-formed,
1848
  // but might be intended to be part of a template-id.
1849
63
  if (OpToken.is(tok::comma) && 
isTypeIdUnambiguously()7
&&
1850
63
      
diagnoseUnknownTemplateId(LAngle.TemplateName, LAngle.LessLoc)3
) {
1851
3
    AngleBrackets.clear(*this);
1852
3
    return true;
1853
3
  }
1854
1855
  // If a context that looks like a template-id is followed by '()', then
1856
  // this is ill-formed, but might be intended to be a template-id
1857
  // followed by '()'.
1858
60
  if (OpToken.is(tok::greater) && 
Tok.is(tok::l_paren)56
&&
1859
60
      
NextToken().is(tok::r_paren)21
) {
1860
15
    Actions.diagnoseExprIntendedAsTemplateName(
1861
15
        getCurScope(), LAngle.TemplateName, LAngle.LessLoc,
1862
15
        OpToken.getLocation());
1863
15
    AngleBrackets.clear(*this);
1864
15
    return true;
1865
15
  }
1866
1867
  // After a '>' (etc), we're no longer potentially in a construct that's
1868
  // intended to be treated as a template-id.
1869
45
  if (OpToken.is(tok::greater) ||
1870
45
      
(4
getLangOpts().CPlusPlus114
&&
1871
4
       OpToken.isOneOf(tok::greatergreater, tok::greatergreatergreater)))
1872
41
    AngleBrackets.clear(*this);
1873
45
  return false;
1874
60
}