clang 20.0.0git
ParseCXXInlineMethods.cpp
Go to the documentation of this file.
1//===--- ParseCXXInlineMethods.cpp - C++ class inline methods 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 for C++ class inline methods.
10//
11//===----------------------------------------------------------------------===//
12
15#include "clang/Parse/Parser.h"
17#include "clang/Sema/DeclSpec.h"
19#include "clang/Sema/Scope.h"
20
21using namespace clang;
22
23/// Parse the optional ("message") part of a deleted-function-body.
24StringLiteral *Parser::ParseCXXDeletedFunctionMessage() {
25 if (!Tok.is(tok::l_paren))
26 return nullptr;
27 StringLiteral *Message = nullptr;
28 BalancedDelimiterTracker BT{*this, tok::l_paren};
29 BT.consumeOpen();
30
31 if (isTokenStringLiteral()) {
33 if (Res.isUsable()) {
34 Message = Res.getAs<StringLiteral>();
35 Diag(Message->getBeginLoc(), getLangOpts().CPlusPlus26
36 ? diag::warn_cxx23_delete_with_message
37 : diag::ext_delete_with_message)
38 << Message->getSourceRange();
39 }
40 } else {
41 Diag(Tok.getLocation(), diag::err_expected_string_literal)
42 << /*Source='in'*/ 0 << "'delete'";
43 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
44 }
45
46 BT.consumeClose();
47 return Message;
48}
49
50/// If we've encountered '= delete' in a context where it is ill-formed, such
51/// as in the declaration of a non-function, also skip the ("message") part if
52/// it is present to avoid issuing further diagnostics.
53void Parser::SkipDeletedFunctionBody() {
54 if (!Tok.is(tok::l_paren))
55 return;
56
57 BalancedDelimiterTracker BT{*this, tok::l_paren};
58 BT.consumeOpen();
59
60 // Just skip to the end of the current declaration.
61 SkipUntil(tok::r_paren, tok::comma, StopAtSemi | StopBeforeMatch);
62 if (Tok.is(tok::r_paren))
63 BT.consumeClose();
64}
65
66/// ParseCXXInlineMethodDef - We parsed and verified that the specified
67/// Declarator is a well formed C++ inline method definition. Now lex its body
68/// and store its tokens for parsing after the C++ class is complete.
69NamedDecl *Parser::ParseCXXInlineMethodDef(
70 AccessSpecifier AS, const ParsedAttributesView &AccessAttrs,
71 ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo,
72 const VirtSpecifiers &VS, SourceLocation PureSpecLoc) {
73 assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
74 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try, tok::equal) &&
75 "Current token not a '{', ':', '=', or 'try'!");
76
77 MultiTemplateParamsArg TemplateParams(
78 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data()
79 : nullptr,
80 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
81
82 NamedDecl *FnD;
83 if (D.getDeclSpec().isFriendSpecified())
84 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
85 TemplateParams);
86 else {
87 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
88 TemplateParams, nullptr,
89 VS, ICIS_NoInit);
90 if (FnD) {
91 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
92 if (PureSpecLoc.isValid())
93 Actions.ActOnPureSpecifier(FnD, PureSpecLoc);
94 }
95 }
96
97 if (FnD)
98 HandleMemberFunctionDeclDelays(D, FnD);
99
100 D.complete(FnD);
101
102 if (TryConsumeToken(tok::equal)) {
103 if (!FnD) {
104 SkipUntil(tok::semi);
105 return nullptr;
106 }
107
108 bool Delete = false;
109 SourceLocation KWLoc;
110 SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1);
111 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
113 ? diag::warn_cxx98_compat_defaulted_deleted_function
114 : diag::ext_defaulted_deleted_function)
115 << 1 /* deleted */;
116 StringLiteral *Message = ParseCXXDeletedFunctionMessage();
117 Actions.SetDeclDeleted(FnD, KWLoc, Message);
118 Delete = true;
119 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
120 DeclAsFunction->setRangeEnd(KWEndLoc);
121 }
122 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
124 ? diag::warn_cxx98_compat_defaulted_deleted_function
125 : diag::ext_defaulted_deleted_function)
126 << 0 /* defaulted */;
127 Actions.SetDeclDefaulted(FnD, KWLoc);
128 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
129 DeclAsFunction->setRangeEnd(KWEndLoc);
130 }
131 } else {
132 llvm_unreachable("function definition after = not 'delete' or 'default'");
133 }
134
135 if (Tok.is(tok::comma)) {
136 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
137 << Delete;
138 SkipUntil(tok::semi);
139 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
140 Delete ? "delete" : "default")) {
141 SkipUntil(tok::semi);
142 }
143
144 return FnD;
145 }
146
147 if (SkipFunctionBodies && (!FnD || Actions.canSkipFunctionBody(FnD)) &&
148 trySkippingFunctionBody()) {
149 Actions.ActOnSkippedFunctionBody(FnD);
150 return FnD;
151 }
152
153 // In delayed template parsing mode, if we are within a class template
154 // or if we are about to parse function member template then consume
155 // the tokens and store them for parsing at the end of the translation unit.
156 if (getLangOpts().DelayedTemplateParsing &&
157 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Definition &&
158 !D.getDeclSpec().hasConstexprSpecifier() &&
159 !(FnD && FnD->getAsFunction() &&
161 ((Actions.CurContext->isDependentContext() ||
162 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
163 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
165
166 CachedTokens Toks;
167 LexTemplateFunctionForLateParsing(Toks);
168
169 if (FnD) {
170 FunctionDecl *FD = FnD->getAsFunction();
172 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
173 }
174
175 return FnD;
176 }
177
178 // Consume the tokens and store them for later parsing.
179
180 LexedMethod* LM = new LexedMethod(this, FnD);
181 getCurrentClass().LateParsedDeclarations.push_back(LM);
182 CachedTokens &Toks = LM->Toks;
183
185 // Consume everything up to (and including) the left brace of the
186 // function body.
187 if (ConsumeAndStoreFunctionPrologue(Toks)) {
188 // We didn't find the left-brace we expected after the
189 // constructor initializer.
190
191 // If we're code-completing and the completion point was in the broken
192 // initializer, we want to parse it even though that will fail.
193 if (PP.isCodeCompletionEnabled() &&
194 llvm::any_of(Toks, [](const Token &Tok) {
195 return Tok.is(tok::code_completion);
196 })) {
197 // If we gave up at the completion point, the initializer list was
198 // likely truncated, so don't eat more tokens. We'll hit some extra
199 // errors, but they should be ignored in code completion.
200 return FnD;
201 }
202
203 // We already printed an error, and it's likely impossible to recover,
204 // so don't try to parse this method later.
205 // Skip over the rest of the decl and back to somewhere that looks
206 // reasonable.
208 delete getCurrentClass().LateParsedDeclarations.back();
209 getCurrentClass().LateParsedDeclarations.pop_back();
210 return FnD;
211 } else {
212 // Consume everything up to (and including) the matching right brace.
213 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
214 }
215
216 // If we're in a function-try-block, we need to store all the catch blocks.
217 if (kind == tok::kw_try) {
218 while (Tok.is(tok::kw_catch)) {
219 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
220 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
221 }
222 }
223
224 if (FnD) {
225 FunctionDecl *FD = FnD->getAsFunction();
226 // Track that this function will eventually have a body; Sema needs
227 // to know this.
229 FD->setWillHaveBody(true);
230 } else {
231 // If semantic analysis could not build a function declaration,
232 // just throw away the late-parsed declaration.
233 delete getCurrentClass().LateParsedDeclarations.back();
234 getCurrentClass().LateParsedDeclarations.pop_back();
235 }
236
237 return FnD;
238}
239
240/// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
241/// specified Declarator is a well formed C++ non-static data member
242/// declaration. Now lex its initializer and store its tokens for parsing
243/// after the class is complete.
244void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
245 assert(Tok.isOneOf(tok::l_brace, tok::equal) &&
246 "Current token not a '{' or '='!");
247
248 LateParsedMemberInitializer *MI =
249 new LateParsedMemberInitializer(this, VarD);
250 getCurrentClass().LateParsedDeclarations.push_back(MI);
251 CachedTokens &Toks = MI->Toks;
252
254 if (kind == tok::equal) {
255 Toks.push_back(Tok);
256 ConsumeToken();
257 }
258
259 if (kind == tok::l_brace) {
260 // Begin by storing the '{' token.
261 Toks.push_back(Tok);
262 ConsumeBrace();
263
264 // Consume everything up to (and including) the matching right brace.
265 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
266 } else {
267 // Consume everything up to (but excluding) the comma or semicolon.
268 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
269 }
270
271 // Store an artificial EOF token to ensure that we don't run off the end of
272 // the initializer when we come to parse it.
273 Token Eof;
274 Eof.startToken();
275 Eof.setKind(tok::eof);
276 Eof.setLocation(Tok.getLocation());
277 Eof.setEofData(VarD);
278 Toks.push_back(Eof);
279}
280
281Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
282void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
283void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
284void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
285void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
286void Parser::LateParsedDeclaration::ParseLexedPragmas() {}
287
288Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
289 : Self(P), Class(C) {}
290
291Parser::LateParsedClass::~LateParsedClass() {
292 Self->DeallocateParsedClasses(Class);
293}
294
295void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
296 Self->ParseLexedMethodDeclarations(*Class);
297}
298
299void Parser::LateParsedClass::ParseLexedMemberInitializers() {
300 Self->ParseLexedMemberInitializers(*Class);
301}
302
303void Parser::LateParsedClass::ParseLexedMethodDefs() {
304 Self->ParseLexedMethodDefs(*Class);
305}
306
307void Parser::LateParsedClass::ParseLexedAttributes() {
308 Self->ParseLexedAttributes(*Class);
309}
310
311void Parser::LateParsedClass::ParseLexedPragmas() {
312 Self->ParseLexedPragmas(*Class);
313}
314
315void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
316 Self->ParseLexedMethodDeclaration(*this);
317}
318
319void Parser::LexedMethod::ParseLexedMethodDefs() {
320 Self->ParseLexedMethodDef(*this);
321}
322
323void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
324 Self->ParseLexedMemberInitializer(*this);
325}
326
327void Parser::LateParsedAttribute::ParseLexedAttributes() {
328 Self->ParseLexedAttribute(*this, true, false);
329}
330
331void Parser::LateParsedPragma::ParseLexedPragmas() {
332 Self->ParseLexedPragma(*this);
333}
334
335/// Utility to re-enter a possibly-templated scope while parsing its
336/// late-parsed components.
340 TemplateParameterDepthRAII CurTemplateDepthTracker;
341
342 ReenterTemplateScopeRAII(Parser &P, Decl *MaybeTemplated, bool Enter = true)
343 : P(P), Scopes(P), CurTemplateDepthTracker(P.TemplateParameterDepth) {
344 if (Enter) {
346 P.ReenterTemplateScopes(Scopes, MaybeTemplated));
347 }
348 }
349};
350
351/// Utility to re-enter a class scope while parsing its late-parsed components.
353 ParsingClass &Class;
354
356 : ReenterTemplateScopeRAII(P, Class.TagOrTemplate,
357 /*Enter=*/!Class.TopLevelClass),
358 Class(Class) {
359 // If this is the top-level class, we're still within its scope.
360 if (Class.TopLevelClass)
361 return;
362
363 // Re-enter the class scope itself.
366 Class.TagOrTemplate);
367 }
369 if (Class.TopLevelClass)
370 return;
371
373 Class.TagOrTemplate);
374 }
375};
376
377/// ParseLexedMethodDeclarations - We finished parsing the member
378/// specification of a top (non-nested) C++ class. Now go over the
379/// stack of method declarations with some parts for which parsing was
380/// delayed (such as default arguments) and parse them.
381void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
382 ReenterClassScopeRAII InClassScope(*this, Class);
383
384 for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations)
385 LateD->ParseLexedMethodDeclarations();
386}
387
388void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
389 // If this is a member template, introduce the template parameter scope.
390 ReenterTemplateScopeRAII InFunctionTemplateScope(*this, LM.Method);
391
392 // Start the delayed C++ method declaration
394
395 // Introduce the parameters into scope and parse their default
396 // arguments.
397 InFunctionTemplateScope.Scopes.Enter(Scope::FunctionPrototypeScope |
400 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
401 auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
402 // Introduce the parameter into scope.
403 bool HasUnparsed = Param->hasUnparsedDefaultArg();
405 std::unique_ptr<CachedTokens> Toks = std::move(LM.DefaultArgs[I].Toks);
406 if (Toks) {
407 ParenBraceBracketBalancer BalancerRAIIObj(*this);
408
409 // Mark the end of the default argument so that we know when to stop when
410 // we parse it later on.
411 Token LastDefaultArgToken = Toks->back();
412 Token DefArgEnd;
413 DefArgEnd.startToken();
414 DefArgEnd.setKind(tok::eof);
415 DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
416 DefArgEnd.setEofData(Param);
417 Toks->push_back(DefArgEnd);
418
419 // Parse the default argument from its saved token stream.
420 Toks->push_back(Tok); // So that the current token doesn't get lost
421 PP.EnterTokenStream(*Toks, true, /*IsReinject*/ true);
422
423 // Consume the previously-pushed token.
425
426 // Consume the '='.
427 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
428 SourceLocation EqualLoc = ConsumeToken();
429
430 // The argument isn't actually potentially evaluated unless it is
431 // used.
433 Actions,
435
436 ExprResult DefArgResult;
437 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
438 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
439 DefArgResult = ParseBraceInitializer();
440 } else
441 DefArgResult = ParseAssignmentExpression();
442 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult, Param);
443 if (DefArgResult.isInvalid()) {
444 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc,
445 /*DefaultArg=*/nullptr);
446 } else {
447 if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
448 // The last two tokens are the terminator and the saved value of
449 // Tok; the last token in the default argument is the one before
450 // those.
451 assert(Toks->size() >= 3 && "expected a token in default arg");
452 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
453 << SourceRange(Tok.getLocation(),
454 (*Toks)[Toks->size() - 3].getLocation());
455 }
456 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
457 DefArgResult.get());
458 }
459
460 // There could be leftover tokens (e.g. because of an error).
461 // Skip through until we reach the 'end of default argument' token.
462 while (Tok.isNot(tok::eof))
464
465 if (Tok.is(tok::eof) && Tok.getEofData() == Param)
467 } else if (HasUnparsed) {
468 assert(Param->hasInheritedDefaultArg());
469 FunctionDecl *Old;
470 if (const auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(LM.Method))
471 Old =
472 cast<FunctionDecl>(FunTmpl->getTemplatedDecl())->getPreviousDecl();
473 else
474 Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
475 if (Old) {
476 ParmVarDecl *OldParam = Old->getParamDecl(I);
477 assert(!OldParam->hasUnparsedDefaultArg());
478 if (OldParam->hasUninstantiatedDefaultArg())
479 Param->setUninstantiatedDefaultArg(
480 OldParam->getUninstantiatedDefaultArg());
481 else
482 Param->setDefaultArg(OldParam->getInit());
483 }
484 }
485 }
486
487 // Parse a delayed exception-specification, if there is one.
488 if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
489 ParenBraceBracketBalancer BalancerRAIIObj(*this);
490
491 // Add the 'stop' token.
492 Token LastExceptionSpecToken = Toks->back();
493 Token ExceptionSpecEnd;
494 ExceptionSpecEnd.startToken();
495 ExceptionSpecEnd.setKind(tok::eof);
496 ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
497 ExceptionSpecEnd.setEofData(LM.Method);
498 Toks->push_back(ExceptionSpecEnd);
499
500 // Parse the default argument from its saved token stream.
501 Toks->push_back(Tok); // So that the current token doesn't get lost
502 PP.EnterTokenStream(*Toks, true, /*IsReinject*/true);
503
504 // Consume the previously-pushed token.
506
507 // C++11 [expr.prim.general]p3:
508 // If a declaration declares a member function or member function
509 // template of a class X, the expression this is a prvalue of type
510 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
511 // and the end of the function-definition, member-declarator, or
512 // declarator.
513 CXXMethodDecl *Method;
514 FunctionDecl *FunctionToPush;
515 if (FunctionTemplateDecl *FunTmpl
516 = dyn_cast<FunctionTemplateDecl>(LM.Method))
517 FunctionToPush = FunTmpl->getTemplatedDecl();
518 else
519 FunctionToPush = cast<FunctionDecl>(LM.Method);
520 Method = dyn_cast<CXXMethodDecl>(FunctionToPush);
521
522 // Push a function scope so that tryCaptureVariable() can properly visit
523 // function scopes involving function parameters that are referenced inside
524 // the noexcept specifier e.g. through a lambda expression.
525 // Example:
526 // struct X {
527 // void ICE(int val) noexcept(noexcept([val]{}));
528 // };
529 // Setup the CurScope to match the function DeclContext - we have such
530 // assumption in IsInFnTryBlockHandler().
531 ParseScope FnScope(this, Scope::FnScope);
532 Sema::ContextRAII FnContext(Actions, FunctionToPush,
533 /*NewThisContext=*/false);
534 Sema::FunctionScopeRAII PopFnContext(Actions);
535 Actions.PushFunctionScope();
536
537 Sema::CXXThisScopeRAII ThisScope(
538 Actions, Method ? Method->getParent() : nullptr,
539 Method ? Method->getMethodQualifiers() : Qualifiers{},
540 Method && getLangOpts().CPlusPlus11);
541
542 // Parse the exception-specification.
543 SourceRange SpecificationRange;
544 SmallVector<ParsedType, 4> DynamicExceptions;
545 SmallVector<SourceRange, 4> DynamicExceptionRanges;
546 ExprResult NoexceptExpr;
547 CachedTokens *ExceptionSpecTokens;
548
550 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
551 DynamicExceptions,
552 DynamicExceptionRanges, NoexceptExpr,
553 ExceptionSpecTokens);
554
555 if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
556 Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
557
558 // Attach the exception-specification to the method.
559 Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
560 SpecificationRange,
561 DynamicExceptions,
562 DynamicExceptionRanges,
563 NoexceptExpr.isUsable()?
564 NoexceptExpr.get() : nullptr);
565
566 // There could be leftover tokens (e.g. because of an error).
567 // Skip through until we reach the original token position.
568 while (Tok.isNot(tok::eof))
570
571 // Clean up the remaining EOF token.
572 if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
574
575 delete Toks;
576 LM.ExceptionSpecTokens = nullptr;
577 }
578
579 InFunctionTemplateScope.Scopes.Exit();
580
581 // Finish the delayed C++ method declaration.
583}
584
585/// ParseLexedMethodDefs - We finished parsing the member specification of a top
586/// (non-nested) C++ class. Now go over the stack of lexed methods that were
587/// collected during its parsing and parse them all.
588void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
589 ReenterClassScopeRAII InClassScope(*this, Class);
590
591 for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
592 D->ParseLexedMethodDefs();
593}
594
595void Parser::ParseLexedMethodDef(LexedMethod &LM) {
596 // If this is a member template, introduce the template parameter scope.
597 ReenterTemplateScopeRAII InFunctionTemplateScope(*this, LM.D);
598
599 ParenBraceBracketBalancer BalancerRAIIObj(*this);
600
601 assert(!LM.Toks.empty() && "Empty body!");
602 Token LastBodyToken = LM.Toks.back();
603 Token BodyEnd;
604 BodyEnd.startToken();
605 BodyEnd.setKind(tok::eof);
606 BodyEnd.setLocation(LastBodyToken.getEndLoc());
607 BodyEnd.setEofData(LM.D);
608 LM.Toks.push_back(BodyEnd);
609 // Append the current token at the end of the new token stream so that it
610 // doesn't get lost.
611 LM.Toks.push_back(Tok);
612 PP.EnterTokenStream(LM.Toks, true, /*IsReinject*/true);
613
614 // Consume the previously pushed token.
615 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
616 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)
617 && "Inline method not starting with '{', ':' or 'try'");
618
619 // Parse the method body. Function body parsing code is similar enough
620 // to be re-used for method bodies as well.
621 ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
623 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
624
625 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
626
627 if (Tok.is(tok::kw_try)) {
628 ParseFunctionTryBlock(LM.D, FnScope);
629
630 while (Tok.isNot(tok::eof))
632
633 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
635 return;
636 }
637 if (Tok.is(tok::colon)) {
638 ParseConstructorInitializer(LM.D);
639
640 // Error recovery.
641 if (!Tok.is(tok::l_brace)) {
642 FnScope.Exit();
643 Actions.ActOnFinishFunctionBody(LM.D, nullptr);
644
645 while (Tok.isNot(tok::eof))
647
648 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
650 return;
651 }
652 } else
653 Actions.ActOnDefaultCtorInitializers(LM.D);
654
655 assert((Actions.getDiagnostics().hasErrorOccurred() ||
656 !isa<FunctionTemplateDecl>(LM.D) ||
657 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
658 < TemplateParameterDepth) &&
659 "TemplateParameterDepth should be greater than the depth of "
660 "current template being instantiated!");
661
662 ParseFunctionStatementBody(LM.D, FnScope);
663
664 while (Tok.isNot(tok::eof))
666
667 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
669
670 if (auto *FD = dyn_cast_or_null<FunctionDecl>(LM.D))
671 if (isa<CXXMethodDecl>(FD) ||
674}
675
676/// ParseLexedMemberInitializers - We finished parsing the member specification
677/// of a top (non-nested) C++ class. Now go over the stack of lexed data member
678/// initializers that were collected during its parsing and parse them all.
679void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
680 ReenterClassScopeRAII InClassScope(*this, Class);
681
682 if (!Class.LateParsedDeclarations.empty()) {
683 // C++11 [expr.prim.general]p4:
684 // Otherwise, if a member-declarator declares a non-static data member
685 // (9.2) of a class X, the expression this is a prvalue of type "pointer
686 // to X" within the optional brace-or-equal-initializer. It shall not
687 // appear elsewhere in the member-declarator.
688 // FIXME: This should be done in ParseLexedMemberInitializer, not here.
689 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
690 Qualifiers());
691
692 for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
693 D->ParseLexedMemberInitializers();
694 }
695
696 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
697}
698
699void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
700 if (!MI.Field || MI.Field->isInvalidDecl())
701 return;
702
703 ParenBraceBracketBalancer BalancerRAIIObj(*this);
704
705 // Append the current token at the end of the new token stream so that it
706 // doesn't get lost.
707 MI.Toks.push_back(Tok);
708 PP.EnterTokenStream(MI.Toks, true, /*IsReinject*/true);
709
710 // Consume the previously pushed token.
711 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
712
713 SourceLocation EqualLoc;
714
716
717 // The initializer isn't actually potentially evaluated unless it is
718 // used.
721
722 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
723 EqualLoc);
724
725 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc, Init);
726
727 // The next token should be our artificial terminating EOF token.
728 if (Tok.isNot(tok::eof)) {
729 if (!Init.isInvalid()) {
730 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
731 if (!EndLoc.isValid())
732 EndLoc = Tok.getLocation();
733 // No fixit; we can't recover as if there were a semicolon here.
734 Diag(EndLoc, diag::err_expected_semi_decl_list);
735 }
736
737 // Consume tokens until we hit the artificial EOF.
738 while (Tok.isNot(tok::eof))
740 }
741 // Make sure this is *our* artificial EOF token.
742 if (Tok.getEofData() == MI.Field)
744}
745
746/// Wrapper class which calls ParseLexedAttribute, after setting up the
747/// scope appropriately.
748void Parser::ParseLexedAttributes(ParsingClass &Class) {
749 ReenterClassScopeRAII InClassScope(*this, Class);
750
751 for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations)
752 LateD->ParseLexedAttributes();
753}
754
755/// Parse all attributes in LAs, and attach them to Decl D.
756void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
757 bool EnterScope, bool OnDefinition) {
758 assert(LAs.parseSoon() &&
759 "Attribute list should be marked for immediate parsing.");
760 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
761 if (D)
762 LAs[i]->addDecl(D);
763 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
764 delete LAs[i];
765 }
766 LAs.clear();
767}
768
769/// Finish parsing an attribute for which parsing was delayed.
770/// This will be called at the end of parsing a class declaration
771/// for each LateParsedAttribute. We consume the saved tokens and
772/// create an attribute with the arguments filled in. We add this
773/// to the Attribute list for the decl.
774void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
775 bool EnterScope, bool OnDefinition) {
776 // Create a fake EOF so that attribute parsing won't go off the end of the
777 // attribute.
778 Token AttrEnd;
779 AttrEnd.startToken();
780 AttrEnd.setKind(tok::eof);
781 AttrEnd.setLocation(Tok.getLocation());
782 AttrEnd.setEofData(LA.Toks.data());
783 LA.Toks.push_back(AttrEnd);
784
785 // Append the current token at the end of the new token stream so that it
786 // doesn't get lost.
787 LA.Toks.push_back(Tok);
788 PP.EnterTokenStream(LA.Toks, true, /*IsReinject=*/true);
789 // Consume the previously pushed token.
790 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
791
792 ParsedAttributes Attrs(AttrFactory);
793
794 if (LA.Decls.size() > 0) {
795 Decl *D = LA.Decls[0];
796 NamedDecl *ND = dyn_cast<NamedDecl>(D);
797 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
798
799 // Allow 'this' within late-parsed attributes.
800 Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
801 ND && ND->isCXXInstanceMember());
802
803 if (LA.Decls.size() == 1) {
804 // If the Decl is templatized, add template parameters to scope.
805 ReenterTemplateScopeRAII InDeclScope(*this, D, EnterScope);
806
807 // If the Decl is on a function, add function parameters to the scope.
808 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
809 if (HasFunScope) {
810 InDeclScope.Scopes.Enter(Scope::FnScope | Scope::DeclScope |
812 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
813 }
814
815 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, nullptr,
816 nullptr, SourceLocation(), ParsedAttr::Form::GNU(),
817 nullptr);
818
819 if (HasFunScope)
820 Actions.ActOnExitFunctionContext();
821 } else {
822 // If there are multiple decls, then the decl cannot be within the
823 // function scope.
824 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, nullptr,
825 nullptr, SourceLocation(), ParsedAttr::Form::GNU(),
826 nullptr);
827 }
828 } else {
829 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
830 }
831
832 if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
833 Attrs.begin()->isKnownToGCC())
834 Diag(Tok, diag::warn_attribute_on_function_definition)
835 << &LA.AttrName;
836
837 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
838 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
839
840 // Due to a parsing error, we either went over the cached tokens or
841 // there are still cached tokens left, so we skip the leftover tokens.
842 while (Tok.isNot(tok::eof))
844
845 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
847}
848
849void Parser::ParseLexedPragmas(ParsingClass &Class) {
850 ReenterClassScopeRAII InClassScope(*this, Class);
851
852 for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
853 D->ParseLexedPragmas();
854}
855
856void Parser::ParseLexedPragma(LateParsedPragma &LP) {
857 PP.EnterToken(Tok, /*IsReinject=*/true);
858 PP.EnterTokenStream(LP.toks(), /*DisableMacroExpansion=*/true,
859 /*IsReinject=*/true);
860
861 // Consume the previously pushed token.
862 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
863 assert(Tok.isAnnotation() && "Expected annotation token.");
864 switch (Tok.getKind()) {
865 case tok::annot_attr_openmp:
866 case tok::annot_pragma_openmp: {
867 AccessSpecifier AS = LP.getAccessSpecifier();
868 ParsedAttributes Attrs(AttrFactory);
869 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
870 break;
871 }
872 default:
873 llvm_unreachable("Unexpected token.");
874 }
875}
876
877/// ConsumeAndStoreUntil - Consume and store the token at the passed token
878/// container until the token 'T' is reached (which gets
879/// consumed/stored too, if ConsumeFinalToken).
880/// If StopAtSemi is true, then we will stop early at a ';' character.
881/// Returns true if token 'T1' or 'T2' was found.
882/// NOTE: This is a specialized version of Parser::SkipUntil.
883bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
884 CachedTokens &Toks,
885 bool StopAtSemi, bool ConsumeFinalToken) {
886 // We always want this function to consume at least one token if the first
887 // token isn't T and if not at EOF.
888 bool isFirstTokenConsumed = true;
889 while (true) {
890 // If we found one of the tokens, stop and return true.
891 if (Tok.is(T1) || Tok.is(T2)) {
892 if (ConsumeFinalToken) {
893 Toks.push_back(Tok);
895 }
896 return true;
897 }
898
899 switch (Tok.getKind()) {
900 case tok::eof:
901 case tok::annot_module_begin:
902 case tok::annot_module_end:
903 case tok::annot_module_include:
904 case tok::annot_repl_input_end:
905 // Ran out of tokens.
906 return false;
907
908 case tok::l_paren:
909 // Recursively consume properly-nested parens.
910 Toks.push_back(Tok);
911 ConsumeParen();
912 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
913 break;
914 case tok::l_square:
915 // Recursively consume properly-nested square brackets.
916 Toks.push_back(Tok);
917 ConsumeBracket();
918 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
919 break;
920 case tok::l_brace:
921 // Recursively consume properly-nested braces.
922 Toks.push_back(Tok);
923 ConsumeBrace();
924 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
925 break;
926
927 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
928 // Since the user wasn't looking for this token (if they were, it would
929 // already be handled), this isn't balanced. If there is a LHS token at a
930 // higher level, we will assume that this matches the unbalanced token
931 // and return it. Otherwise, this is a spurious RHS token, which we skip.
932 case tok::r_paren:
933 if (ParenCount && !isFirstTokenConsumed)
934 return false; // Matches something.
935 Toks.push_back(Tok);
936 ConsumeParen();
937 break;
938 case tok::r_square:
939 if (BracketCount && !isFirstTokenConsumed)
940 return false; // Matches something.
941 Toks.push_back(Tok);
942 ConsumeBracket();
943 break;
944 case tok::r_brace:
945 if (BraceCount && !isFirstTokenConsumed)
946 return false; // Matches something.
947 Toks.push_back(Tok);
948 ConsumeBrace();
949 break;
950
951 case tok::semi:
952 if (StopAtSemi)
953 return false;
954 [[fallthrough]];
955 default:
956 // consume this token.
957 Toks.push_back(Tok);
958 ConsumeAnyToken(/*ConsumeCodeCompletionTok*/true);
959 break;
960 }
961 isFirstTokenConsumed = false;
962 }
963}
964
965/// Consume tokens and store them in the passed token container until
966/// we've passed the try keyword and constructor initializers and have consumed
967/// the opening brace of the function body. The opening brace will be consumed
968/// if and only if there was no error.
969///
970/// \return True on error.
971bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
972 if (Tok.is(tok::kw_try)) {
973 Toks.push_back(Tok);
974 ConsumeToken();
975 }
976
977 if (Tok.isNot(tok::colon)) {
978 // Easy case, just a function body.
979
980 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
981 // brace: an opening one is the function body, while a closing one probably
982 // means we've reached the end of the class.
983 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
984 /*StopAtSemi=*/true,
985 /*ConsumeFinalToken=*/false);
986 if (Tok.isNot(tok::l_brace))
987 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
988
989 Toks.push_back(Tok);
990 ConsumeBrace();
991 return false;
992 }
993
994 Toks.push_back(Tok);
995 ConsumeToken();
996
997 // We can't reliably skip over a mem-initializer-id, because it could be
998 // a template-id involving not-yet-declared names. Given:
999 //
1000 // S ( ) : a < b < c > ( e )
1001 //
1002 // 'e' might be an initializer or part of a template argument, depending
1003 // on whether 'b' is a template.
1004
1005 // Track whether we might be inside a template argument. We can give
1006 // significantly better diagnostics if we know that we're not.
1007 bool MightBeTemplateArgument = false;
1008
1009 while (true) {
1010 // Skip over the mem-initializer-id, if possible.
1011 if (Tok.is(tok::kw_decltype)) {
1012 Toks.push_back(Tok);
1013 SourceLocation OpenLoc = ConsumeToken();
1014 if (Tok.isNot(tok::l_paren))
1015 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
1016 << "decltype";
1017 Toks.push_back(Tok);
1018 ConsumeParen();
1019 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
1020 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
1021 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
1022 return true;
1023 }
1024 }
1025 do {
1026 // Walk over a component of a nested-name-specifier.
1027 if (Tok.is(tok::coloncolon)) {
1028 Toks.push_back(Tok);
1029 ConsumeToken();
1030
1031 if (Tok.is(tok::kw_template)) {
1032 Toks.push_back(Tok);
1033 ConsumeToken();
1034 }
1035 }
1036
1037 if (Tok.is(tok::identifier)) {
1038 Toks.push_back(Tok);
1039 ConsumeToken();
1040 } else {
1041 break;
1042 }
1043 // Pack indexing
1044 if (Tok.is(tok::ellipsis) && NextToken().is(tok::l_square)) {
1045 Toks.push_back(Tok);
1046 SourceLocation OpenLoc = ConsumeToken();
1047 Toks.push_back(Tok);
1048 ConsumeBracket();
1049 if (!ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/true)) {
1050 Diag(Tok.getLocation(), diag::err_expected) << tok::r_square;
1051 Diag(OpenLoc, diag::note_matching) << tok::l_square;
1052 return true;
1053 }
1054 }
1055
1056 } while (Tok.is(tok::coloncolon));
1057
1058 if (Tok.is(tok::code_completion)) {
1059 Toks.push_back(Tok);
1060 ConsumeCodeCompletionToken();
1061 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype)) {
1062 // Could be the start of another member initializer (the ',' has not
1063 // been written yet)
1064 continue;
1065 }
1066 }
1067
1068 if (Tok.is(tok::comma)) {
1069 // The initialization is missing, we'll diagnose it later.
1070 Toks.push_back(Tok);
1071 ConsumeToken();
1072 continue;
1073 }
1074 if (Tok.is(tok::less))
1075 MightBeTemplateArgument = true;
1076
1077 if (MightBeTemplateArgument) {
1078 // We may be inside a template argument list. Grab up to the start of the
1079 // next parenthesized initializer or braced-init-list. This *might* be the
1080 // initializer, or it might be a subexpression in the template argument
1081 // list.
1082 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
1083 // if all angles are closed.
1084 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
1085 /*StopAtSemi=*/true,
1086 /*ConsumeFinalToken=*/false)) {
1087 // We're not just missing the initializer, we're also missing the
1088 // function body!
1089 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
1090 }
1091 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
1092 // We found something weird in a mem-initializer-id.
1094 return Diag(Tok.getLocation(), diag::err_expected_either)
1095 << tok::l_paren << tok::l_brace;
1096 else
1097 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
1098 }
1099
1100 tok::TokenKind kind = Tok.getKind();
1101 Toks.push_back(Tok);
1102 bool IsLParen = (kind == tok::l_paren);
1103 SourceLocation OpenLoc = Tok.getLocation();
1104
1105 if (IsLParen) {
1106 ConsumeParen();
1107 } else {
1108 assert(kind == tok::l_brace && "Must be left paren or brace here.");
1109 ConsumeBrace();
1110 // In C++03, this has to be the start of the function body, which
1111 // means the initializer is malformed; we'll diagnose it later.
1112 if (!getLangOpts().CPlusPlus11)
1113 return false;
1114
1115 const Token &PreviousToken = Toks[Toks.size() - 2];
1116 if (!MightBeTemplateArgument &&
1117 !PreviousToken.isOneOf(tok::identifier, tok::greater,
1118 tok::greatergreater)) {
1119 // If the opening brace is not preceded by one of these tokens, we are
1120 // missing the mem-initializer-id. In order to recover better, we need
1121 // to use heuristics to determine if this '{' is most likely the
1122 // beginning of a brace-init-list or the function body.
1123 // Check the token after the corresponding '}'.
1124 TentativeParsingAction PA(*this);
1125 if (SkipUntil(tok::r_brace) &&
1126 !Tok.isOneOf(tok::comma, tok::ellipsis, tok::l_brace)) {
1127 // Consider there was a malformed initializer and this is the start
1128 // of the function body. We'll diagnose it later.
1129 PA.Revert();
1130 return false;
1131 }
1132 PA.Revert();
1133 }
1134 }
1135
1136 // Grab the initializer (or the subexpression of the template argument).
1137 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
1138 // if we might be inside the braces of a lambda-expression.
1139 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
1140 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
1141 Diag(Tok, diag::err_expected) << CloseKind;
1142 Diag(OpenLoc, diag::note_matching) << kind;
1143 return true;
1144 }
1145
1146 // Grab pack ellipsis, if present.
1147 if (Tok.is(tok::ellipsis)) {
1148 Toks.push_back(Tok);
1149 ConsumeToken();
1150 }
1151
1152 // If we know we just consumed a mem-initializer, we must have ',' or '{'
1153 // next.
1154 if (Tok.is(tok::comma)) {
1155 Toks.push_back(Tok);
1156 ConsumeToken();
1157 } else if (Tok.is(tok::l_brace)) {
1158 // This is the function body if the ')' or '}' is immediately followed by
1159 // a '{'. That cannot happen within a template argument, apart from the
1160 // case where a template argument contains a compound literal:
1161 //
1162 // S ( ) : a < b < c > ( d ) { }
1163 // // End of declaration, or still inside the template argument?
1164 //
1165 // ... and the case where the template argument contains a lambda:
1166 //
1167 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
1168 // ( ) > ( ) { }
1169 //
1170 // FIXME: Disambiguate these cases. Note that the latter case is probably
1171 // going to be made ill-formed by core issue 1607.
1172 Toks.push_back(Tok);
1173 ConsumeBrace();
1174 return false;
1175 } else if (!MightBeTemplateArgument) {
1176 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
1177 << tok::comma;
1178 }
1179 }
1180}
1181
1182/// Consume and store tokens from the '?' to the ':' in a conditional
1183/// expression.
1184bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
1185 // Consume '?'.
1186 assert(Tok.is(tok::question));
1187 Toks.push_back(Tok);
1188 ConsumeToken();
1189
1190 while (Tok.isNot(tok::colon)) {
1191 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
1192 /*StopAtSemi=*/true,
1193 /*ConsumeFinalToken=*/false))
1194 return false;
1195
1196 // If we found a nested conditional, consume it.
1197 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
1198 return false;
1199 }
1200
1201 // Consume ':'.
1202 Toks.push_back(Tok);
1203 ConsumeToken();
1204 return true;
1205}
1206
1207/// ConsumeAndStoreInitializer - Consume and store the token at the passed token
1208/// container until the end of the current initializer expression (either a
1209/// default argument or an in-class initializer for a non-static data member).
1210///
1211/// Returns \c true if we reached the end of something initializer-shaped,
1212/// \c false if we bailed out.
1213bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
1214 CachedInitKind CIK) {
1215 // We always want this function to consume at least one token if not at EOF.
1216 bool IsFirstToken = true;
1217
1218 // Number of possible unclosed <s we've seen so far. These might be templates,
1219 // and might not, but if there were none of them (or we know for sure that
1220 // we're within a template), we can avoid a tentative parse.
1221 unsigned AngleCount = 0;
1222 unsigned KnownTemplateCount = 0;
1223
1224 while (true) {
1225 switch (Tok.getKind()) {
1226 case tok::comma:
1227 // If we might be in a template, perform a tentative parse to check.
1228 if (!AngleCount)
1229 // Not a template argument: this is the end of the initializer.
1230 return true;
1231 if (KnownTemplateCount)
1232 goto consume_token;
1233
1234 // We hit a comma inside angle brackets. This is the hard case. The
1235 // rule we follow is:
1236 // * For a default argument, if the tokens after the comma form a
1237 // syntactically-valid parameter-declaration-clause, in which each
1238 // parameter has an initializer, then this comma ends the default
1239 // argument.
1240 // * For a default initializer, if the tokens after the comma form a
1241 // syntactically-valid init-declarator-list, then this comma ends
1242 // the default initializer.
1243 {
1244 TentativeParsingAction TPA(*this, /*Unannotated=*/true);
1246
1247 TPResult Result = TPResult::Error;
1248 ConsumeToken();
1249 switch (CIK) {
1250 case CIK_DefaultInitializer:
1251 Result = TryParseInitDeclaratorList();
1252 // If we parsed a complete, ambiguous init-declarator-list, this
1253 // is only syntactically-valid if it's followed by a semicolon.
1254 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1255 Result = TPResult::False;
1256 break;
1257
1258 case CIK_DefaultArgument:
1259 bool InvalidAsDeclaration = false;
1260 Result = TryParseParameterDeclarationClause(
1261 &InvalidAsDeclaration, /*VersusTemplateArg=*/true);
1262 // If this is an expression or a declaration with a missing
1263 // 'typename', assume it's not a declaration.
1264 if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1265 Result = TPResult::False;
1266 break;
1267 }
1268
1269 // Put the token stream back and undo any annotations we performed
1270 // after the comma. They may reflect a different parse than the one
1271 // we will actually perform at the end of the class.
1272 TPA.Revert();
1273
1274 // If what follows could be a declaration, it is a declaration.
1275 if (Result != TPResult::False && Result != TPResult::Error)
1276 return true;
1277 }
1278
1279 // Keep going. We know we're inside a template argument list now.
1280 ++KnownTemplateCount;
1281 goto consume_token;
1282
1283 case tok::eof:
1284 case tok::annot_module_begin:
1285 case tok::annot_module_end:
1286 case tok::annot_module_include:
1287 case tok::annot_repl_input_end:
1288 // Ran out of tokens.
1289 return false;
1290
1291 case tok::less:
1292 // FIXME: A '<' can only start a template-id if it's preceded by an
1293 // identifier, an operator-function-id, or a literal-operator-id.
1294 ++AngleCount;
1295 goto consume_token;
1296
1297 case tok::question:
1298 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1299 // that is *never* the end of the initializer. Skip to the ':'.
1300 if (!ConsumeAndStoreConditional(Toks))
1301 return false;
1302 break;
1303
1304 case tok::greatergreatergreater:
1305 if (!getLangOpts().CPlusPlus11)
1306 goto consume_token;
1307 if (AngleCount) --AngleCount;
1308 if (KnownTemplateCount) --KnownTemplateCount;
1309 [[fallthrough]];
1310 case tok::greatergreater:
1311 if (!getLangOpts().CPlusPlus11)
1312 goto consume_token;
1313 if (AngleCount) --AngleCount;
1314 if (KnownTemplateCount) --KnownTemplateCount;
1315 [[fallthrough]];
1316 case tok::greater:
1317 if (AngleCount) --AngleCount;
1318 if (KnownTemplateCount) --KnownTemplateCount;
1319 goto consume_token;
1320
1321 case tok::kw_template:
1322 // 'template' identifier '<' is known to start a template argument list,
1323 // and can be used to disambiguate the parse.
1324 // FIXME: Support all forms of 'template' unqualified-id '<'.
1325 Toks.push_back(Tok);
1326 ConsumeToken();
1327 if (Tok.is(tok::identifier)) {
1328 Toks.push_back(Tok);
1329 ConsumeToken();
1330 if (Tok.is(tok::less)) {
1331 ++AngleCount;
1332 ++KnownTemplateCount;
1333 Toks.push_back(Tok);
1334 ConsumeToken();
1335 }
1336 }
1337 break;
1338
1339 case tok::kw_operator:
1340 // If 'operator' precedes other punctuation, that punctuation loses
1341 // its special behavior.
1342 Toks.push_back(Tok);
1343 ConsumeToken();
1344 switch (Tok.getKind()) {
1345 case tok::comma:
1346 case tok::greatergreatergreater:
1347 case tok::greatergreater:
1348 case tok::greater:
1349 case tok::less:
1350 Toks.push_back(Tok);
1351 ConsumeToken();
1352 break;
1353 default:
1354 break;
1355 }
1356 break;
1357
1358 case tok::l_paren:
1359 // Recursively consume properly-nested parens.
1360 Toks.push_back(Tok);
1361 ConsumeParen();
1362 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1363 break;
1364 case tok::l_square:
1365 // Recursively consume properly-nested square brackets.
1366 Toks.push_back(Tok);
1367 ConsumeBracket();
1368 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1369 break;
1370 case tok::l_brace:
1371 // Recursively consume properly-nested braces.
1372 Toks.push_back(Tok);
1373 ConsumeBrace();
1374 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1375 break;
1376
1377 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1378 // Since the user wasn't looking for this token (if they were, it would
1379 // already be handled), this isn't balanced. If there is a LHS token at a
1380 // higher level, we will assume that this matches the unbalanced token
1381 // and return it. Otherwise, this is a spurious RHS token, which we
1382 // consume and pass on to downstream code to diagnose.
1383 case tok::r_paren:
1384 if (CIK == CIK_DefaultArgument)
1385 return true; // End of the default argument.
1386 if (ParenCount && !IsFirstToken)
1387 return false;
1388 Toks.push_back(Tok);
1389 ConsumeParen();
1390 continue;
1391 case tok::r_square:
1392 if (BracketCount && !IsFirstToken)
1393 return false;
1394 Toks.push_back(Tok);
1395 ConsumeBracket();
1396 continue;
1397 case tok::r_brace:
1398 if (BraceCount && !IsFirstToken)
1399 return false;
1400 Toks.push_back(Tok);
1401 ConsumeBrace();
1402 continue;
1403
1404 case tok::code_completion:
1405 Toks.push_back(Tok);
1406 ConsumeCodeCompletionToken();
1407 break;
1408
1409 case tok::string_literal:
1410 case tok::wide_string_literal:
1411 case tok::utf8_string_literal:
1412 case tok::utf16_string_literal:
1413 case tok::utf32_string_literal:
1414 Toks.push_back(Tok);
1415 ConsumeStringToken();
1416 break;
1417 case tok::semi:
1418 if (CIK == CIK_DefaultInitializer)
1419 return true; // End of the default initializer.
1420 [[fallthrough]];
1421 default:
1422 consume_token:
1423 Toks.push_back(Tok);
1424 ConsumeToken();
1425 break;
1426 }
1427 IsFirstToken = false;
1428 }
1429}
StringRef P
const Decl * D
Defines the C++ template declaration subclasses.
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ....
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2239
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1334
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition: DeclBase.h:1108
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:882
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:246
@ IDNS_OrdinaryFriend
This declaration is a friend function.
Definition: DeclBase.h:152
DeclContext * getDeclContext()
Definition: DeclBase.h:451
bool hasErrorOccurred() const
Definition: Diagnostic.h:866
RAII object that enters a new expression evaluation context.
Represents a function declaration or definition.
Definition: Decl.h:1935
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
QualType getReturnType() const
Definition: Decl.h:2720
void setWillHaveBody(bool V=true)
Definition: Decl.h:2562
Declaration of a template function.
Definition: DeclTemplate.h:959
This represents a decl that may have a name.
Definition: Decl.h:253
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition: Decl.cpp:1951
RAII object that makes sure paren/bracket/brace count is correct after declaration/statement parsing,...
Represents a parameter to a function.
Definition: Decl.h:1725
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1854
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1858
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3017
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:956
Introduces zero or more scopes for parsing.
Definition: Parser.h:1209
void Enter(unsigned ScopeFlags)
Definition: Parser.h:1217
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:58
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition: Parser.cpp:81
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition: Parser.h:548
void EnterScope(unsigned ScopeFlags)
EnterScope - Start a new scope.
Definition: Parser.cpp:420
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition: Parser.h:576
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:556
Scope * getCurScope() const
Definition: Parser.h:502
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
Definition: Parser.h:1294
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
Definition: ParseDecl.cpp:2239
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast=NotTypeCast)
Parse an expr that doesn't include (top-level) commas.
Definition: ParseExpr.cpp:171
const LangOptions & getLangOpts() const
Definition: Parser.h:495
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition: Parser.h:1275
@ StopAtSemi
Stop skipping at semicolon.
Definition: Parser.h:1273
ExprResult ParseUnevaluatedStringLiteralExpression()
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:872
unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D)
Re-enter the template scopes for a declaration that might be a template.
A class for parsing a declarator.
void EnterToken(const Token &Tok, bool IsReinject)
Enters a token in the token stream to be lexed next.
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
The collection of all-type qualifiers we support.
Definition: Type.h:324
Represents a struct/union/class.
Definition: Decl.h:4148
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:203
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
@ FunctionPrototypeScope
This is a scope that corresponds to the parameters within a function prototype.
Definition: Scope.h:85
@ CompoundStmtScope
This is a compound statement scope.
Definition: Scope.h:134
@ ClassScope
The scope of a struct/union/class definition.
Definition: Scope.h:69
@ FunctionDeclarationScope
This is a scope that corresponds to the parameters within a function prototype for a function declara...
Definition: Scope.h:91
@ FnScope
This indicates that the scope corresponds to a function, which means that labels are set here.
Definition: Scope.h:51
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8041
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3003
Records and restores the CurFPFeatures state on entry/exit of compound statements.
Definition: Sema.h:13562
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:12118
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:15876
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc, Expr *DefaultArg)
ActOnParamDefaultArgumentError - Parsing or semantic analysis of the default argument for the paramet...
void ActOnFinishDelayedMemberInitializers(Decl *Record)
void ActOnExitFunctionContext()
Definition: SemaDecl.cpp:1455
NamedDecl * ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle)
ActOnCXXMemberDeclarator - This is invoked when a C++ class member declarator is parsed.
bool IsInsideALocalClassWithinATemplateFunction()
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
Definition: SemaDecl.cpp:1431
void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg)
ActOnParamDefaultArgument - Check whether the default argument provided for a function parameter is w...
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnFinishDelayedCXXMethodDeclaration - We have finished processing the delayed method declaration f...
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:528
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2178
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15352
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:15458
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15382
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1043
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don't care about...
Definition: SemaDecl.cpp:15858
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, ExprResult Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15886
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
void actOnDelayedExceptionSpecification(Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr)
Add an exception-specification to the given member or friend function (or function template).
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class,...
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:16402
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
A trivial tuple used to represent a source range.
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
SourceLocation getEndLoc() const
Definition: Token.h:159
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:132
void setKind(tok::TokenKind K)
Definition: Token.h:95
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:99
tok::TokenKind getKind() const
Definition: Token.h:94
void setEofData(const void *D)
Definition: Token.h:204
void setLocation(SourceLocation L)
Definition: Token.h:140
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:101
bool isNot(tok::TokenKind K) const
Definition: Token.h:100
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:121
const void * getEofData() const
Definition: Token.h:200
void startToken()
Reset all flags to cleared.
Definition: Token.h:177
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2811
const Expr * getInit() const
Definition: Decl.h:1319
Represents a C++11 virt-specifier-seq.
Definition: DeclSpec.h:2783
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:70
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus26
Definition: LangStandard.h:61
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
@ Result
The result type of a method or function.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:123
Utility to re-enter a class scope while parsing its late-parsed components.
ReenterClassScopeRAII(Parser &P, ParsingClass &Class)
Utility to re-enter a possibly-templated scope while parsing its late-parsed components.
ReenterTemplateScopeRAII(Parser &P, Decl *MaybeTemplated, bool Enter=true)
TemplateParameterDepthRAII CurTemplateDepthTracker
An RAII helper that pops function a function scope on exit.
Definition: Sema.h:928