Coverage Report

Created: 2020-09-15 12:33

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