Coverage Report

Created: 2022-07-16 07:03

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