Coverage Report

Created: 2024-01-17 10:31

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