Coverage Report

Created: 2020-02-18 08:44

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