Coverage Report

Created: 2022-01-22 13:19

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