Coverage Report

Created: 2019-07-24 05:18

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