Coverage Report

Created: 2021-08-24 07:12

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