clang 24.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
16#include "clang/Parse/Parser.h"
18#include "clang/Sema/DeclSpec.h"
20#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Scope.h"
22#include "llvm/ADT/ScopeExit.h"
23
24using namespace clang;
25
26StringLiteral *Parser::ParseCXXDeletedFunctionMessage() {
27 if (!Tok.is(tok::l_paren))
28 return nullptr;
29 StringLiteral *Message = nullptr;
30 BalancedDelimiterTracker BT{*this, tok::l_paren};
31 BT.consumeOpen();
32
33 if (isTokenStringLiteral()) {
35 if (Res.isUsable()) {
36 Message = Res.getAs<StringLiteral>();
37 DiagCompat(Message->getBeginLoc(), diag_compat::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
50void Parser::SkipDeletedFunctionBody() {
51 if (!Tok.is(tok::l_paren))
52 return;
53
54 BalancedDelimiterTracker BT{*this, tok::l_paren};
55 BT.consumeOpen();
56
57 // Just skip to the end of the current declaration.
58 SkipUntil(tok::r_paren, tok::comma, StopAtSemi | StopBeforeMatch);
59 if (Tok.is(tok::r_paren))
60 BT.consumeClose();
61}
62
63NamedDecl *Parser::ParseCXXInlineMethodDef(
64 AccessSpecifier AS, const ParsedAttributesView &AccessAttrs,
65 ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo,
66 const VirtSpecifiers &VS, SourceLocation PureSpecLoc) {
67 assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
68 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try, tok::equal) &&
69 "Current token not a '{', ':', '=', or 'try'!");
70
71 MultiTemplateParamsArg TemplateParams(
72 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data()
73 : nullptr,
74 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
75
76 NamedDecl *FnD;
78 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
79 TemplateParams);
80 else {
81 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
82 TemplateParams, nullptr,
83 VS, ICIS_NoInit);
84 if (FnD) {
85 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
86 if (PureSpecLoc.isValid())
87 Actions.ActOnPureSpecifier(FnD, PureSpecLoc);
88 }
89 }
90
91 if (FnD)
92 HandleMemberFunctionDeclDelays(D, FnD);
93
94 D.complete(FnD);
95
96 if (TryConsumeToken(tok::equal)) {
97 if (!FnD) {
98 SkipUntil(tok::semi);
99 return nullptr;
100 }
101
102 bool Delete = false;
103 SourceLocation KWLoc;
104 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
105 DiagCompat(KWLoc, diag_compat::defaulted_deleted_function)
106 << 1 /* deleted */;
107 StringLiteral *Message = ParseCXXDeletedFunctionMessage();
108 Actions.SetDeclDeleted(FnD, KWLoc, Message);
109 Delete = true;
110 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
111 DeclAsFunction->setRangeEnd(PrevTokLocation);
112 }
113 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
114 DiagCompat(KWLoc, diag_compat::defaulted_deleted_function)
115 << 0 /* defaulted */;
116 Actions.SetDeclDefaulted(FnD, KWLoc);
117 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
118 DeclAsFunction->setRangeEnd(PrevTokLocation);
119 }
120 } else {
121 llvm_unreachable("function definition after = not 'delete' or 'default'");
122 }
123
124 if (Tok.is(tok::comma)) {
125 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
126 << Delete;
127 SkipUntil(tok::semi);
128 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
129 Delete ? "delete" : "default") &&
130 !isLikelyAtStartOfNewDeclaration()) {
131 SkipUntil(tok::semi);
132 }
133
134 return FnD;
135 }
136
137 if (SkipFunctionBodies && (!FnD || Actions.canSkipFunctionBody(FnD)) &&
138 trySkippingFunctionBody()) {
139 Actions.ActOnSkippedFunctionBody(FnD);
140 return FnD;
141 }
142
143 // In delayed template parsing mode, if we are within a class template
144 // or if we are about to parse function member template then consume
145 // the tokens and store them for parsing at the end of the translation unit.
146 if (getLangOpts().DelayedTemplateParsing &&
149 !(FnD && FnD->getAsFunction() &&
151 ((Actions.CurContext->isDependentContext() ||
152 (TemplateInfo.Kind != ParsedTemplateKind::NonTemplate &&
153 TemplateInfo.Kind != ParsedTemplateKind::ExplicitSpecialization)) &&
154 !Actions.IsInsideALocalClassWithinATemplateFunction())) {
155
156 CachedTokens Toks;
157 LexTemplateFunctionForLateParsing(Toks);
158
159 if (FnD) {
160 FunctionDecl *FD = FnD->getAsFunction();
161 Actions.CheckForFunctionRedefinition(FD);
162 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
163 }
164
165 return FnD;
166 }
167
168 // Consume the tokens and store them for later parsing.
169
170 LexedMethod* LM = new LexedMethod(this, FnD);
171 getCurrentClass().LateParsedDeclarations.push_back(LM);
172 CachedTokens &Toks = LM->Toks;
173
174 tok::TokenKind kind = Tok.getKind();
175 // Consume everything up to (and including) the left brace of the
176 // function body.
177 if (ConsumeAndStoreFunctionPrologue(Toks)) {
178 // We didn't find the left-brace we expected after the
179 // constructor initializer.
180
181 // If we're code-completing and the completion point was in the broken
182 // initializer, we want to parse it even though that will fail.
183 if (PP.isCodeCompletionEnabled() &&
184 llvm::any_of(Toks, [](const Token &Tok) {
185 return Tok.is(tok::code_completion);
186 })) {
187 // If we gave up at the completion point, the initializer list was
188 // likely truncated, so don't eat more tokens. We'll hit some extra
189 // errors, but they should be ignored in code completion.
190 return FnD;
191 }
192
193 // We already printed an error, and it's likely impossible to recover,
194 // so don't try to parse this method later.
195 // Skip over the rest of the decl and back to somewhere that looks
196 // reasonable.
198 delete getCurrentClass().LateParsedDeclarations.back();
199 getCurrentClass().LateParsedDeclarations.pop_back();
200 return FnD;
201 } else {
202 // Consume everything up to (and including) the matching right brace.
203 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
204 }
205
206 // If we're in a function-try-block, we need to store all the catch blocks.
207 if (kind == tok::kw_try) {
208 while (Tok.is(tok::kw_catch)) {
209 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
210 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
211 }
212 }
213
214 if (FnD) {
215 FunctionDecl *FD = FnD->getAsFunction();
216 // Track that this function will eventually have a body; Sema needs
217 // to know this.
218 Actions.CheckForFunctionRedefinition(FD);
219 FD->setWillHaveBody(true);
220 } else {
221 // If semantic analysis could not build a function declaration,
222 // just throw away the late-parsed declaration.
223 delete getCurrentClass().LateParsedDeclarations.back();
224 getCurrentClass().LateParsedDeclarations.pop_back();
225 }
226
227 return FnD;
228}
229
230void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
231 assert(Tok.isOneOf(tok::l_brace, tok::equal) &&
232 "Current token not a '{' or '='!");
233
234 LateParsedMemberInitializer *MI =
235 new LateParsedMemberInitializer(this, VarD);
236 getCurrentClass().LateParsedDeclarations.push_back(MI);
237 CachedTokens &Toks = MI->Toks;
238
239 tok::TokenKind kind = Tok.getKind();
240 if (kind == tok::equal) {
241 Toks.push_back(Tok);
242 ConsumeToken();
243 }
244
245 if (kind == tok::l_brace) {
246 // Begin by storing the '{' token.
247 Toks.push_back(Tok);
248 ConsumeBrace();
249
250 // Consume everything up to (and including) the matching right brace.
251 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
252 } else {
253 // Consume everything up to (but excluding) the comma or semicolon.
254 ConsumeAndStoreInitializer(Toks, CachedInitKind::DefaultInitializer);
255 }
256
257 // Store an artificial EOF token to ensure that we don't run off the end of
258 // the initializer when we come to parse it.
259 Token Eof = Token::createEof(Tok.getLocation(), VarD);
260 Toks.push_back(Eof);
261}
262
269
270Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
271 : Self(P), Class(C) {}
272
273Parser::LateParsedClass::~LateParsedClass() {
274 Self->DeallocateParsedClasses(Class);
275}
276
278 Self->ParseLexedMethodDeclarations(*Class);
279}
280
282 Self->ParseLexedMemberInitializers(*Class);
283}
284
286 Self->ParseLexedMethodDefs(*Class);
287}
288
290 Self->ParseLexedAttributes(*Class);
291}
292
294 Self->ParseLexedPragmas(*Class);
295}
296
298 Self->ParseLexedMethodDeclaration(*this);
299}
300
302 Self->ParseLexedMethodDef(*this);
303}
304
306 Self->ParseLexedMemberInitializer(*this);
307}
308
310 Self->ParseLexedAttribute(*this, true, false);
311}
312
314
316 Self->ParseLexedPragma(*this);
317}
318
322 TemplateParameterDepthRAII CurTemplateDepthTracker;
323
324 ReenterTemplateScopeRAII(Parser &P, Decl *MaybeTemplated, bool Enter = true)
325 : P(P), Scopes(P), CurTemplateDepthTracker(P.TemplateParameterDepth) {
326 if (Enter) {
328 P.ReenterTemplateScopes(Scopes, MaybeTemplated));
329 }
330 }
331};
332
334 ParsingClass &Class;
335
337 : ReenterTemplateScopeRAII(P, Class.TagOrTemplate,
338 /*Enter=*/!Class.TopLevelClass),
339 Class(Class) {
340 // If this is the top-level class, we're still within its scope.
341 if (Class.TopLevelClass)
342 return;
343
344 // Re-enter the class scope itself.
346 P.Actions.ActOnStartDelayedMemberDeclarations(P.getCurScope(),
347 Class.TagOrTemplate);
348 }
350 if (Class.TopLevelClass)
351 return;
352
353 P.Actions.ActOnFinishDelayedMemberDeclarations(P.getCurScope(),
354 Class.TagOrTemplate);
355 }
356};
357
358void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
359 ReenterClassScopeRAII InClassScope(*this, Class);
360
361 for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations)
363}
364
365void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
366 // If this is a member template, introduce the template parameter scope.
367 ReenterTemplateScopeRAII InFunctionTemplateScope(*this, LM.Method);
368
369 // Start the delayed C++ method declaration
371
372 // Introduce the parameters into scope and parse their default
373 // arguments.
374 InFunctionTemplateScope.Scopes.Enter(Scope::FunctionPrototypeScope |
377
378 // Delayed default arguments or exception specifications may contain lambdas,
379 // struct S {
380 // void ICE(int x, int = sizeof([x] { return x; }()));
381 // }
382 //
383 // struct X {
384 // void ICE(int val) noexcept(noexcept([val]{}));
385 // };
386 // Lambda capture handling in tryCaptureVariable() expects an enclosing
387 // function scope in Sema's FunctionScopes stack.
388 Sema::FunctionScopeRAII PopFnContext(Actions);
389 Actions.PushFunctionScope();
390
391 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
392 auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
393 // Introduce the parameter into scope.
394 bool HasUnparsed = Param->hasUnparsedDefaultArg();
396 std::unique_ptr<CachedTokens> Toks = std::move(LM.DefaultArgs[I].Toks);
397 if (Toks) {
398 ParenBraceBracketBalancer BalancerRAIIObj(*this);
399
400 // Mark the end of the default argument so that we know when to stop when
401 // we parse it later on.
402 Token LastDefaultArgToken = Toks->back();
403 Token DefArgEnd =
404 Token::createEof(LastDefaultArgToken.getEndLoc(), Param);
405 Toks->push_back(DefArgEnd);
406
407 // Parse the default argument from its saved token stream.
408 Toks->push_back(Tok); // So that the current token doesn't get lost
409 PP.EnterTokenStream(*Toks, true, /*IsReinject*/ true);
410
411 // Consume the previously-pushed token.
412 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
413
414 // Consume the '='.
415 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
416 SourceLocation EqualLoc = ConsumeToken();
417
418 // The argument isn't actually potentially evaluated unless it is
419 // used.
421 Actions,
423
424 ExprResult DefArgResult;
425 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
426 Diag(Tok, diag::compat_cxx11_generalized_initializer_lists);
427 DefArgResult = ParseBraceInitializer();
428 } else
429 DefArgResult = ParseAssignmentExpression();
430 if (DefArgResult.isInvalid()) {
431 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc,
432 /*DefaultArg=*/nullptr);
433 } else {
434 if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
435 // The last two tokens are the terminator and the saved value of
436 // Tok; the last token in the default argument is the one before
437 // those.
438 assert(Toks->size() >= 3 && "expected a token in default arg");
439 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
440 << SourceRange(Tok.getLocation(),
441 (*Toks)[Toks->size() - 3].getLocation());
442 }
443 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
444 DefArgResult.get());
445 }
446
447 // There could be leftover tokens (e.g. because of an error).
448 // Skip through until we reach the 'end of default argument' token.
449 while (Tok.isNot(tok::eof))
451
452 if (Tok.is(tok::eof) && Tok.getEofData() == Param)
454 } else if (HasUnparsed) {
455 assert(Param->hasInheritedDefaultArg());
456 FunctionDecl *Old;
457 if (const auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(LM.Method))
458 Old =
459 cast<FunctionDecl>(FunTmpl->getTemplatedDecl())->getPreviousDecl();
460 else
461 Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
462 if (Old) {
463 ParmVarDecl *OldParam = Old->getParamDecl(I);
464 assert(!OldParam->hasUnparsedDefaultArg());
465 if (OldParam->hasUninstantiatedDefaultArg())
466 Param->setUninstantiatedDefaultArg(
467 OldParam->getUninstantiatedDefaultArg());
468 else
469 Param->setDefaultArg(OldParam->getInit());
470 }
471 }
472 }
473
474 // Parse a delayed exception-specification, if there is one.
475 if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
476 ParenBraceBracketBalancer BalancerRAIIObj(*this);
477
478 // Add the 'stop' token.
479 Token LastExceptionSpecToken = Toks->back();
480 Token ExceptionSpecEnd =
481 Token::createEof(LastExceptionSpecToken.getEndLoc(), LM.Method);
482 Toks->push_back(ExceptionSpecEnd);
483
484 // Parse the default argument from its saved token stream.
485 Toks->push_back(Tok); // So that the current token doesn't get lost
486 PP.EnterTokenStream(*Toks, true, /*IsReinject*/true);
487
488 // Consume the previously-pushed token.
489 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
490
491 // C++11 [expr.prim.general]p3:
492 // If a declaration declares a member function or member function
493 // template of a class X, the expression this is a prvalue of type
494 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
495 // and the end of the function-definition, member-declarator, or
496 // declarator.
497 CXXMethodDecl *Method;
498 FunctionDecl *FunctionToPush;
499 if (FunctionTemplateDecl *FunTmpl
500 = dyn_cast<FunctionTemplateDecl>(LM.Method))
501 FunctionToPush = FunTmpl->getTemplatedDecl();
502 else
503 FunctionToPush = cast<FunctionDecl>(LM.Method);
504 Method = dyn_cast<CXXMethodDecl>(FunctionToPush);
505
506 // Setup the CurScope to match the function DeclContext - we have such
507 // assumption in IsInFnTryBlockHandler().
508 ParseScope FnScope(this, Scope::FnScope);
509 Sema::ContextRAII FnContext(Actions, FunctionToPush,
510 /*NewThisContext=*/false);
511
512 Sema::CXXThisScopeRAII ThisScope(
513 Actions, Method ? Method->getParent() : nullptr,
514 Method ? Method->getMethodQualifiers() : Qualifiers{},
516
517 // Parse the exception-specification.
518 SourceRange SpecificationRange;
519 SmallVector<ParsedType, 4> DynamicExceptions;
520 SmallVector<SourceRange, 4> DynamicExceptionRanges;
521 ExprResult NoexceptExpr;
522 CachedTokens *ExceptionSpecTokens;
523
525 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
526 DynamicExceptions,
527 DynamicExceptionRanges, NoexceptExpr,
528 ExceptionSpecTokens);
529
530 if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
531 Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
532
533 // Attach the exception-specification to the method.
534 Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
535 SpecificationRange,
536 DynamicExceptions,
537 DynamicExceptionRanges,
538 NoexceptExpr.isUsable()?
539 NoexceptExpr.get() : nullptr);
540
541 // There could be leftover tokens (e.g. because of an error).
542 // Skip through until we reach the original token position.
543 while (Tok.isNot(tok::eof))
545
546 // Clean up the remaining EOF token.
547 if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
549
550 delete Toks;
551 LM.ExceptionSpecTokens = nullptr;
552 }
553
554 InFunctionTemplateScope.Scopes.Exit();
555
556 // Finish the delayed C++ method declaration.
557 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
558}
559
560void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
561 ReenterClassScopeRAII InClassScope(*this, Class);
562
563 for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
565}
566
567void Parser::ParseLexedMethodDef(LexedMethod &LM) {
568 // If this is a member template, introduce the template parameter scope.
569 ReenterTemplateScopeRAII InFunctionTemplateScope(*this, LM.D);
570
571 ParenBraceBracketBalancer BalancerRAIIObj(*this);
572
573 assert(!LM.Toks.empty() && "Empty body!");
574 Token LastBodyToken = LM.Toks.back();
575 Token BodyEnd = Token::createEof(LastBodyToken.getEndLoc(), LM.D);
576 LM.Toks.push_back(BodyEnd);
577 // Append the current token at the end of the new token stream so that it
578 // doesn't get lost.
579 LM.Toks.push_back(Tok);
580 PP.EnterTokenStream(LM.Toks, true, /*IsReinject*/true);
581
582 // Consume the previously pushed token.
583 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
584 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)
585 && "Inline method not starting with '{', ':' or 'try'");
586
587 // Parse the method body. Function body parsing code is similar enough
588 // to be re-used for method bodies as well.
591 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
592
593 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
594
595 llvm::scope_exit _([&]() {
596 while (Tok.isNot(tok::eof))
598
599 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
601
602 if (auto *FD = dyn_cast_or_null<FunctionDecl>(LM.D))
603 if (isa<CXXMethodDecl>(FD) ||
605 Actions.ActOnFinishInlineFunctionDef(FD);
606 });
607
608 assert((Actions.getDiagnostics().hasErrorOccurred() ||
610 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
611 < TemplateParameterDepth) &&
612 "TemplateParameterDepth should be greater than the depth of "
613 "current template being instantiated!");
614
615 ParseFunctionBody(LM.D, FnScope);
616}
617
618void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
619 ReenterClassScopeRAII InClassScope(*this, Class);
620
621 if (!Class.LateParsedDeclarations.empty()) {
622 // C++11 [expr.prim.general]p4:
623 // Otherwise, if a member-declarator declares a non-static data member
624 // (9.2) of a class X, the expression this is a prvalue of type "pointer
625 // to X" within the optional brace-or-equal-initializer. It shall not
626 // appear elsewhere in the member-declarator.
627 // FIXME: This should be done in ParseLexedMemberInitializer, not here.
628 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
629 Qualifiers());
630
631 for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
633 }
634
635 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
636}
637
638void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
639 if (!MI.Field || MI.Field->isInvalidDecl())
640 return;
641
642 ParenBraceBracketBalancer BalancerRAIIObj(*this);
643
644 // Append the current token at the end of the new token stream so that it
645 // doesn't get lost.
646 MI.Toks.push_back(Tok);
647 PP.EnterTokenStream(MI.Toks, true, /*IsReinject*/true);
648
649 // Consume the previously pushed token.
650 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
651
652 SourceLocation EqualLoc;
653
654 Actions.ActOnStartCXXInClassMemberInitializer();
655
656 // The initializer isn't actually potentially evaluated unless it is
657 // used.
658 EnterExpressionEvaluationContext Eval(
660
661 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
662 EqualLoc);
663
664 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc, Init);
665
666 // The next token should be our artificial terminating EOF token.
667 if (Tok.isNot(tok::eof)) {
668 if (!Init.isInvalid()) {
669 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
670 if (!EndLoc.isValid())
671 EndLoc = Tok.getLocation();
672 // No fixit; we can't recover as if there were a semicolon here.
673 Diag(EndLoc, diag::err_expected_semi_decl_list);
674 }
675
676 // Consume tokens until we hit the artificial EOF.
677 while (Tok.isNot(tok::eof))
679 }
680 // Make sure this is *our* artificial EOF token.
681 if (Tok.getEofData() == MI.Field)
683}
684
685void Parser::ParseLexedAttributes(ParsingClass &Class) {
686 ReenterClassScopeRAII InClassScope(*this, Class);
687
688 for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations)
689 LateD->ParseLexedAttributes();
690}
691
692void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
693 bool EnterScope, bool OnDefinition,
694 ParsedAttributes *OutAttrs) {
695 assert(LAs.parseSoon() &&
696 "Attribute list should be marked for immediate parsing.");
697 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
698 if (D)
699 LAs[i]->addDecl(D);
700 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition, OutAttrs);
701 delete LAs[i];
702 }
703 LAs.clear();
704}
705
706/// Collect the references to parameters in \p Attrs' arguments.
707static void collectParamRefs(const ParsedAttributes &Attrs,
710 for (const ParsedAttr &AL : Attrs)
711 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I)
712 if (AL.isArgExpr(I))
713 Worklist.push_back(AL.getArgAsExpr(I));
714 while (!Worklist.empty()) {
715 const Stmt *S = Worklist.pop_back_val();
716 if (!S)
717 continue;
718 if (const auto *DRE = dyn_cast<DeclRefExpr>(S);
719 DRE && isa<ParmVarDecl>(DRE->getDecl()))
720 Refs.push_back(DRE);
721 llvm::append_range(Worklist, S->children());
722 }
723}
724
725bool Parser::checkLateAttributeParamRefs(
726 const LateParsedAttribute &LPA, ArrayRef<const DeclRefExpr *> ParamRefs,
727 bool ReenteredProtoParams) {
728 auto IsPointeeParam = [&](const ParmVarDecl *PVD) {
729 return ReenteredProtoParams && llvm::is_contained(LPA.ProtoParams, PVD);
730 };
731
732 // In a C++ class, attributes were always late parsed and a pointee's
733 // parameters were not in scope, so a name that now binds to one used to bind
734 // to whatever else it names outside the prototype. Rather than silently
735 // change its meaning, reject the attribute as ambiguous.
736 if (getLangOpts().CPlusPlus && getCurScope()->isClassScope()) {
737 for (const DeclRefExpr *DRE : ParamRefs) {
738 const auto *PVD = cast<ParmVarDecl>(DRE->getDecl());
739 if (!IsPointeeParam(PVD))
740 continue;
741 LookupResult R(Actions, PVD->getDeclName(), DRE->getLocation(),
743 if (!Actions.LookupName(R, getCurScope()) || R.isAmbiguous())
744 continue;
745 Diag(DRE->getLocation(), diag::err_ambiguous_reference)
746 << PVD->getDeclName();
747 Diag(PVD->getLocation(), diag::note_ambiguous_candidate) << PVD;
748 for (const NamedDecl *Other : R)
749 Diag(Other->getLocation(), diag::note_ambiguous_candidate) << Other;
750 return true;
751 }
752 }
753
754 // A name binds the same way in a template, but instantiation cannot yet map a
755 // pointee's parameters, which are instantiated with the declaration's type
756 // and not kept. Reject the attribute rather than instantiate it wrongly.
757 // FIXME: Map these parameters during template instantiation.
758 if (Actions.CurContext->isDependentContext() ||
759 getCurScope()->getTemplateParamParent() ||
760 Actions.getCurGenericLambda()) {
761 for (const DeclRefExpr *DRE : ParamRefs) {
762 const auto *PVD = cast<ParmVarDecl>(DRE->getDecl());
763 if (!IsPointeeParam(PVD))
764 continue;
765 Diag(DRE->getLocation(), diag::err_late_attribute_param_in_template)
766 << &LPA.AttrName << PVD;
767 return true;
768 }
769 }
770 return false;
771}
772
773void Parser::ParseLexedAttribute(LateParsedAttribute &LPA, bool EnterScope,
774 bool OnDefinition,
775 ParsedAttributes *OutAttrs) {
776 ParsedAttributes Attrs(AttrFactory);
777
778 if (LPA.Decls.size() > 0) {
779 Decl *D = LPA.Decls[0];
780 bool HasFuncScope = EnterScope && LPA.Decls.size() == 1 &&
782 bool IsCPlusPlus = getLangOpts().CPlusPlus;
783
784 NamedDecl *ND = dyn_cast<NamedDecl>(D);
785 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
786
787 // Allow 'this' within late-parsed attributes.
788 Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
789 IsCPlusPlus && ND &&
790 ND->isCXXInstanceMember());
791
792 // If the Decl is templatized, add template parameters to the scope.
793 ReenterTemplateScopeRAII InDeclScope(*this, D, IsCPlusPlus && EnterScope);
794
795 // If the Decl is on a function, add function parameters to the scope.
796 if (HasFuncScope) {
797 InDeclScope.Scopes.Enter(Scope::FnScope | Scope::DeclScope |
799 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
800 }
801
802 // For a function pointer field or variable, the arguments may name a
803 // parameter of the pointee. Re-enter them in a prototype scope nested as it
804 // was when the attribute was written, so they shadow any outer declaration
805 // of the same name. In a C struct, ActOnIdExpression finds the struct's
806 // members only while its scope is innermost, so add the parameters to that
807 // scope instead; it lets them shadow a member of the same name.
808 bool HasProtoParams = !HasFuncScope && !LPA.ProtoParams.empty();
809 bool InCStruct = !IsCPlusPlus && getCurScope()->isClassScope();
810 ParseScope ProtoScope(this,
812 HasProtoParams && !InCStruct);
813 if (HasProtoParams)
814 Actions.ActOnReenterFunctionPrototypeParams(Actions.getCurScope(),
815 LPA.ProtoParams);
816
817 ParsedAttributes Parsed = ParseLexedAttributeTokens(LPA);
818
819 if (HasProtoParams && InCStruct)
820 Actions.ActOnExitFunctionPrototypeParams(Actions.getCurScope(),
821 LPA.ProtoParams);
822 ProtoScope.Exit();
823
824 SmallVector<const DeclRefExpr *, 4> ParamRefs;
825 collectParamRefs(Parsed, ParamRefs);
826 if (!ParamRefs.empty() &&
827 checkLateAttributeParamRefs(LPA, ParamRefs, HasProtoParams))
828 Parsed.clear();
829 Attrs.takeAllAppendingFrom(Parsed);
830
831 if (HasFuncScope)
832 Actions.ActOnExitFunctionContext();
833 } else {
834 Diag(LPA.AttrNameLoc, diag::warn_attribute_no_decl)
835 << LPA.AttrName.getName();
836 }
837
838 if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
839 Attrs.begin()->isKnownToGCC())
840 Diag(Tok, diag::warn_attribute_on_function_definition) << &LPA.AttrName;
841
842 for (auto *D : LPA.Decls)
843 Actions.ActOnFinishDelayedAttribute(getCurScope(), D, Attrs);
844
845 if (OutAttrs)
846 OutAttrs->takeAllAppendingFrom(Attrs);
847}
848
849void Parser::ParseLexedPragmas(ParsingClass &Class) {
850 ReenterClassScopeRAII InClassScope(*this, Class);
851
852 for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
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
877bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
878 CachedTokens &Toks,
879 bool StopAtSemi, bool ConsumeFinalToken) {
880 // We always want this function to consume at least one token if the first
881 // token isn't T and if not at EOF.
882 bool isFirstTokenConsumed = true;
883 while (true) {
884 // If we found one of the tokens, stop and return true.
885 if (Tok.is(T1) || Tok.is(T2)) {
886 if (ConsumeFinalToken) {
887 Toks.push_back(Tok);
889 }
890 return true;
891 }
892
893 switch (Tok.getKind()) {
894 case tok::eof:
895 case tok::annot_module_begin:
896 case tok::annot_module_end:
897 case tok::annot_module_include:
898 // Ran out of tokens.
899 return false;
900
901 case tok::annot_pragma_openacc:
902 case tok::annot_pragma_openmp:
903 case tok::annot_attr_openmp: {
904 // Ignore any tokens inside of a OMP/OpenACC pragma, as these should just
905 // be taken as 1.
906 tok::TokenKind EndKind = Tok.is(tok::annot_pragma_openacc)
907 ? tok::annot_pragma_openacc_end
908 : tok::annot_pragma_openmp_end;
909 Toks.push_back(Tok);
910 ConsumeAnnotationToken();
911 while (Tok.isNot(EndKind) && Tok.isNot(tok::eof)) {
912 Toks.push_back(Tok);
914 }
915 if (Tok.is(EndKind)) {
916 Toks.push_back(Tok);
917 ConsumeAnnotationToken();
918 }
919 break;
920 }
921
922 case tok::l_paren:
923 // Recursively consume properly-nested parens.
924 Toks.push_back(Tok);
925 ConsumeParen();
926 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
927 break;
928 case tok::l_square:
929 // Recursively consume properly-nested square brackets.
930 Toks.push_back(Tok);
931 ConsumeBracket();
932 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
933 break;
934 case tok::l_brace:
935 // Recursively consume properly-nested braces.
936 Toks.push_back(Tok);
937 ConsumeBrace();
938 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
939 break;
940
941 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
942 // Since the user wasn't looking for this token (if they were, it would
943 // already be handled), this isn't balanced. If there is a LHS token at a
944 // higher level, we will assume that this matches the unbalanced token
945 // and return it. Otherwise, this is a spurious RHS token, which we skip.
946 case tok::r_paren:
947 if (ParenCount && !isFirstTokenConsumed)
948 return false; // Matches something.
949 Toks.push_back(Tok);
950 ConsumeParen();
951 break;
952 case tok::r_square:
953 if (BracketCount && !isFirstTokenConsumed)
954 return false; // Matches something.
955 Toks.push_back(Tok);
956 ConsumeBracket();
957 break;
958 case tok::r_brace:
959 if (BraceCount && !isFirstTokenConsumed)
960 return false; // Matches something.
961 Toks.push_back(Tok);
962 ConsumeBrace();
963 break;
964
965 case tok::semi:
966 if (StopAtSemi)
967 return false;
968 [[fallthrough]];
969 default:
970 // consume this token.
971 Toks.push_back(Tok);
972 ConsumeAnyToken(/*ConsumeCodeCompletionTok*/true);
973 break;
974 }
975 isFirstTokenConsumed = false;
976 }
977}
978
979bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
980 if (Tok.is(tok::kw_try)) {
981 Toks.push_back(Tok);
982 ConsumeToken();
983 }
984
985 if (Tok.isNot(tok::colon)) {
986 // Easy case, just a function body.
987
988 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
989 // brace: an opening one is the function body, while a closing one probably
990 // means we've reached the end of the class.
991 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
992 /*StopAtSemi=*/true,
993 /*ConsumeFinalToken=*/false);
994 if (Tok.isNot(tok::l_brace))
995 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
996
997 Toks.push_back(Tok);
998 ConsumeBrace();
999 return false;
1000 }
1001
1002 Toks.push_back(Tok);
1003 ConsumeToken();
1004
1005 // We can't reliably skip over a mem-initializer-id, because it could be
1006 // a template-id involving not-yet-declared names. Given:
1007 //
1008 // S ( ) : a < b < c > ( e )
1009 //
1010 // 'e' might be an initializer or part of a template argument, depending
1011 // on whether 'b' is a template.
1012
1013 // Track whether we might be inside a template argument. We can give
1014 // significantly better diagnostics if we know that we're not.
1015 bool MightBeTemplateArgument = false;
1016
1017 while (true) {
1018 // Skip over the mem-initializer-id, if possible.
1019 if (Tok.is(tok::kw_decltype)) {
1020 Toks.push_back(Tok);
1021 SourceLocation OpenLoc = ConsumeToken();
1022 if (Tok.isNot(tok::l_paren))
1023 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
1024 << "decltype";
1025 Toks.push_back(Tok);
1026 ConsumeParen();
1027 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
1028 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
1029 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
1030 return true;
1031 }
1032 }
1033 do {
1034 // Walk over a component of a nested-name-specifier.
1035 if (Tok.is(tok::coloncolon)) {
1036 Toks.push_back(Tok);
1037 ConsumeToken();
1038
1039 if (Tok.is(tok::kw_template)) {
1040 Toks.push_back(Tok);
1041 ConsumeToken();
1042 }
1043 }
1044
1045 if (Tok.is(tok::identifier)) {
1046 Toks.push_back(Tok);
1047 ConsumeToken();
1048 } else {
1049 break;
1050 }
1051 // Pack indexing
1052 if (Tok.is(tok::ellipsis) && NextToken().is(tok::l_square)) {
1053 Toks.push_back(Tok);
1054 SourceLocation OpenLoc = ConsumeToken();
1055 Toks.push_back(Tok);
1056 ConsumeBracket();
1057 if (!ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/true)) {
1058 Diag(Tok.getLocation(), diag::err_expected) << tok::r_square;
1059 Diag(OpenLoc, diag::note_matching) << tok::l_square;
1060 return true;
1061 }
1062 }
1063
1064 } while (Tok.is(tok::coloncolon));
1065
1066 if (Tok.is(tok::code_completion)) {
1067 Toks.push_back(Tok);
1068 ConsumeCodeCompletionToken();
1069 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype)) {
1070 // Could be the start of another member initializer (the ',' has not
1071 // been written yet)
1072 continue;
1073 }
1074 }
1075
1076 if (Tok.is(tok::comma)) {
1077 // The initialization is missing, we'll diagnose it later.
1078 Toks.push_back(Tok);
1079 ConsumeToken();
1080 continue;
1081 }
1082 if (Tok.is(tok::less))
1083 MightBeTemplateArgument = true;
1084
1085 if (MightBeTemplateArgument) {
1086 // We may be inside a template argument list. Grab up to the start of the
1087 // next parenthesized initializer or braced-init-list. This *might* be the
1088 // initializer, or it might be a subexpression in the template argument
1089 // list.
1090 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
1091 // if all angles are closed.
1092 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
1093 /*StopAtSemi=*/true,
1094 /*ConsumeFinalToken=*/false)) {
1095 // We're not just missing the initializer, we're also missing the
1096 // function body!
1097 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
1098 }
1099 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
1100 // We found something weird in a mem-initializer-id.
1102 return Diag(Tok.getLocation(), diag::err_expected_either)
1103 << tok::l_paren << tok::l_brace;
1104 else
1105 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
1106 }
1107
1108 tok::TokenKind kind = Tok.getKind();
1109 Toks.push_back(Tok);
1110 bool IsLParen = (kind == tok::l_paren);
1111 SourceLocation OpenLoc = Tok.getLocation();
1112
1113 if (IsLParen) {
1114 ConsumeParen();
1115 } else {
1116 assert(kind == tok::l_brace && "Must be left paren or brace here.");
1117 ConsumeBrace();
1118 // In C++03, this has to be the start of the function body, which
1119 // means the initializer is malformed; we'll diagnose it later.
1120 if (!getLangOpts().CPlusPlus11)
1121 return false;
1122
1123 const Token &PreviousToken = Toks[Toks.size() - 2];
1124 if (!MightBeTemplateArgument &&
1125 !PreviousToken.isOneOf(tok::identifier, tok::greater,
1126 tok::greatergreater)) {
1127 // If the opening brace is not preceded by one of these tokens, we are
1128 // missing the mem-initializer-id. In order to recover better, we need
1129 // to use heuristics to determine if this '{' is most likely the
1130 // beginning of a brace-init-list or the function body.
1131 // Check the token after the corresponding '}'.
1132 TentativeParsingAction PA(*this);
1133 if (SkipUntil(tok::r_brace) &&
1134 !Tok.isOneOf(tok::comma, tok::ellipsis, tok::l_brace)) {
1135 // Consider there was a malformed initializer and this is the start
1136 // of the function body. We'll diagnose it later.
1137 PA.Revert();
1138 return false;
1139 }
1140 PA.Revert();
1141 }
1142 }
1143
1144 // Grab the initializer (or the subexpression of the template argument).
1145 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
1146 // if we might be inside the braces of a lambda-expression.
1147 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
1148 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
1149 Diag(Tok, diag::err_expected) << CloseKind;
1150 Diag(OpenLoc, diag::note_matching) << kind;
1151 return true;
1152 }
1153
1154 // Grab pack ellipsis, if present.
1155 if (Tok.is(tok::ellipsis)) {
1156 Toks.push_back(Tok);
1157 ConsumeToken();
1158 }
1159
1160 // If we know we just consumed a mem-initializer, we must have ',' or '{'
1161 // next.
1162 if (Tok.is(tok::comma)) {
1163 Toks.push_back(Tok);
1164 ConsumeToken();
1165 } else if (Tok.is(tok::l_brace)) {
1166 // This is the function body if the ')' or '}' is immediately followed by
1167 // a '{'. That cannot happen within a template argument, apart from the
1168 // case where a template argument contains a compound literal:
1169 //
1170 // S ( ) : a < b < c > ( d ) { }
1171 // // End of declaration, or still inside the template argument?
1172 //
1173 // ... and the case where the template argument contains a lambda:
1174 //
1175 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
1176 // ( ) > ( ) { }
1177 //
1178 // FIXME: Disambiguate these cases. Note that the latter case is probably
1179 // going to be made ill-formed by core issue 1607.
1180 Toks.push_back(Tok);
1181 ConsumeBrace();
1182 return false;
1183 } else if (!MightBeTemplateArgument) {
1184 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
1185 << tok::comma;
1186 }
1187 }
1188}
1189
1190bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
1191 // Consume '?'.
1192 assert(Tok.is(tok::question));
1193 Toks.push_back(Tok);
1194 ConsumeToken();
1195
1196 while (Tok.isNot(tok::colon)) {
1197 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
1198 /*StopAtSemi=*/true,
1199 /*ConsumeFinalToken=*/false))
1200 return false;
1201
1202 // If we found a nested conditional, consume it.
1203 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
1204 return false;
1205 }
1206
1207 // Consume ':'.
1208 Toks.push_back(Tok);
1209 ConsumeToken();
1210 return true;
1211}
1212
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::ellipsis:
1227 // We found an elipsis at the end of the parameter list;
1228 // it is not part of a parameter declaration.
1229 if (ParenCount == 1 && NextToken().is(tok::r_paren))
1230 return true;
1231 goto consume_token;
1232 case tok::comma:
1233 // If we might be in a template, perform a tentative parse to check.
1234 if (!AngleCount)
1235 // Not a template argument: this is the end of the initializer.
1236 return true;
1237 if (KnownTemplateCount)
1238 goto consume_token;
1239
1240 // We hit a comma inside angle brackets. This is the hard case. The
1241 // rule we follow is:
1242 // * For a default argument, if the tokens after the comma form a
1243 // syntactically-valid parameter-declaration-clause, in which each
1244 // parameter has an initializer, then this comma ends the default
1245 // argument.
1246 // * For a default initializer, if the tokens after the comma form a
1247 // syntactically-valid init-declarator-list, then this comma ends
1248 // the default initializer.
1249 {
1250 TentativeParsingAction TPA(*this, /*Unannotated=*/true);
1251 Sema::TentativeAnalysisScope Scope(Actions);
1252
1253 TPResult Result = TPResult::Error;
1254 ConsumeToken();
1255 switch (CIK) {
1257 Result = TryParseInitDeclaratorList();
1258 // If we parsed a complete, ambiguous init-declarator-list, this
1259 // is only syntactically-valid if it's followed by a semicolon.
1260 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1261 Result = TPResult::False;
1262 break;
1263
1265 bool InvalidAsDeclaration = false;
1266 Result = TryParseParameterDeclarationClause(
1267 &InvalidAsDeclaration, /*VersusTemplateArg=*/true);
1268 // If this is an expression or a declaration with a missing
1269 // 'typename', assume it's not a declaration.
1270 if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1271 Result = TPResult::False;
1272 break;
1273 }
1274
1275 // Put the token stream back and undo any annotations we performed
1276 // after the comma. They may reflect a different parse than the one
1277 // we will actually perform at the end of the class.
1278 TPA.Revert();
1279
1280 // If what follows could be a declaration, it is a declaration.
1281 if (Result != TPResult::False && Result != TPResult::Error)
1282 return true;
1283 }
1284
1285 // Keep going. We know we're inside a template argument list now.
1286 ++KnownTemplateCount;
1287 goto consume_token;
1288
1289 case tok::eof:
1290 // Ran out of tokens.
1291 return false;
1292
1293 case tok::less:
1294 // FIXME: A '<' can only start a template-id if it's preceded by an
1295 // identifier, an operator-function-id, or a literal-operator-id.
1296 ++AngleCount;
1297 goto consume_token;
1298
1299 case tok::question:
1300 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1301 // that is *never* the end of the initializer. Skip to the ':'.
1302 if (!ConsumeAndStoreConditional(Toks))
1303 return false;
1304 break;
1305
1306 case tok::greatergreatergreater:
1307 if (!getLangOpts().CPlusPlus11)
1308 goto consume_token;
1309 if (AngleCount) --AngleCount;
1310 if (KnownTemplateCount) --KnownTemplateCount;
1311 [[fallthrough]];
1312 case tok::greatergreater:
1313 if (!getLangOpts().CPlusPlus11)
1314 goto consume_token;
1315 if (AngleCount) --AngleCount;
1316 if (KnownTemplateCount) --KnownTemplateCount;
1317 [[fallthrough]];
1318 case tok::greater:
1319 if (AngleCount) --AngleCount;
1320 if (KnownTemplateCount) --KnownTemplateCount;
1321 goto consume_token;
1322
1323 case tok::kw_template:
1324 // 'template' identifier '<' is known to start a template argument list,
1325 // and can be used to disambiguate the parse.
1326 // FIXME: Support all forms of 'template' unqualified-id '<'.
1327 Toks.push_back(Tok);
1328 ConsumeToken();
1329 if (Tok.is(tok::identifier)) {
1330 Toks.push_back(Tok);
1331 ConsumeToken();
1332 if (Tok.is(tok::less)) {
1333 ++AngleCount;
1334 ++KnownTemplateCount;
1335 Toks.push_back(Tok);
1336 ConsumeToken();
1337 }
1338 }
1339 break;
1340
1341 case tok::kw_operator:
1342 // If 'operator' precedes other punctuation, that punctuation loses
1343 // its special behavior.
1344 Toks.push_back(Tok);
1345 ConsumeToken();
1346 switch (Tok.getKind()) {
1347 case tok::comma:
1348 case tok::greatergreatergreater:
1349 case tok::greatergreater:
1350 case tok::greater:
1351 case tok::less:
1352 Toks.push_back(Tok);
1353 ConsumeToken();
1354 break;
1355 default:
1356 break;
1357 }
1358 break;
1359
1360 case tok::l_paren:
1361 // Recursively consume properly-nested parens.
1362 Toks.push_back(Tok);
1363 ConsumeParen();
1364 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1365 break;
1366 case tok::l_square:
1367 // Recursively consume properly-nested square brackets.
1368 Toks.push_back(Tok);
1369 ConsumeBracket();
1370 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1371 break;
1372 case tok::l_brace:
1373 // Recursively consume properly-nested braces.
1374 Toks.push_back(Tok);
1375 ConsumeBrace();
1376 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1377 break;
1378
1379 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1380 // Since the user wasn't looking for this token (if they were, it would
1381 // already be handled), this isn't balanced. If there is a LHS token at a
1382 // higher level, we will assume that this matches the unbalanced token
1383 // and return it. Otherwise, this is a spurious RHS token, which we
1384 // consume and pass on to downstream code to diagnose.
1385 case tok::r_paren:
1387 return true; // End of the default argument.
1388 if (ParenCount && !IsFirstToken)
1389 return false;
1390 Toks.push_back(Tok);
1391 ConsumeParen();
1392 continue;
1393 case tok::r_square:
1394 if (BracketCount && !IsFirstToken)
1395 return false;
1396 Toks.push_back(Tok);
1397 ConsumeBracket();
1398 continue;
1399 case tok::r_brace:
1400 if (BraceCount && !IsFirstToken)
1401 return false;
1402 Toks.push_back(Tok);
1403 ConsumeBrace();
1404 continue;
1405
1406 case tok::code_completion:
1407 Toks.push_back(Tok);
1408 ConsumeCodeCompletionToken();
1409 break;
1410
1411 case tok::string_literal:
1412 case tok::wide_string_literal:
1413 case tok::utf8_string_literal:
1414 case tok::utf16_string_literal:
1415 case tok::utf32_string_literal:
1416 Toks.push_back(Tok);
1417 ConsumeStringToken();
1418 break;
1419 case tok::semi:
1421 return true; // End of the default initializer.
1422 [[fallthrough]];
1423 default:
1424 consume_token:
1425 // If it's an annotation token, then we've run out of tokens and should
1426 // bail out. Otherwise, cache the token and consume it.
1427 if (Tok.isAnnotation())
1428 return false;
1429
1430 Toks.push_back(Tok);
1431 ConsumeToken();
1432 break;
1433 }
1434 IsFirstToken = false;
1435 }
1436}
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
bool is(tok::TokenKind Kind) const
Token Tok
The Token.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
static void collectParamRefs(const ParsedAttributes &Attrs, SmallVectorImpl< const DeclRefExpr * > &Refs)
Collect the references to parameters in Attrs' arguments.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:894
bool hasConstexprSpecifier() const
Definition DeclSpec.h:910
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:1137
bool isInIdentifierNamespace(unsigned NS) const
Definition DeclBase.h:911
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
@ IDNS_OrdinaryFriend
This declaration is a friend function.
Definition DeclBase.h:152
DeclContext * getDeclContext()
Definition DeclBase.h:457
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2559
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2849
RAII object that enters a new expression evaluation context.
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2944
QualType getReturnType() const
Definition Decl.h:2992
void setWillHaveBody(bool V=true)
Definition Decl.h:2829
StringRef getName() const
Return the actual identifier string.
[class.mem]p1: "... the class is regarded as complete within
Definition Parser.h:175
This represents a decl that may have a name.
Definition Decl.h:276
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition Decl.cpp:1977
RAII object that makes sure paren/bracket/brace count is correct after declaration/statement parsing,...
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1961
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1965
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3058
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:958
void takeAllAppendingFrom(ParsedAttributes &Other)
Definition ParsedAttr.h:975
Introduces zero or more scopes for parsing.
Definition Parser.h:537
ParseScope - Introduces a new scope for parsing.
Definition Parser.h:501
Parser - This implements a parser for the C family of languages.
Definition Parser.h:264
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition Parser.cpp:100
DiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Definition Parser.cpp:108
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition Parser.h:356
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies)
Definition Parser.cpp:72
void EnterScope(unsigned ScopeFlags)
EnterScope - Start a new scope.
Definition Parser.cpp:438
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition Parser.h:384
bool TryConsumeToken(tok::TokenKind Expected)
Definition Parser.h:364
Scope * getCurScope() const
Definition Parser.h:305
friend struct LateParsedAttribute
Definition Parser.h:1215
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:600
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
const LangOptions & getLangOpts() const
Definition Parser.h:298
friend class ParenBraceBracketBalancer
Definition Parser.h:292
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition Parser.h:581
@ StopAtSemi
Stop skipping at semicolon.
Definition Parser.h:579
ExprResult ParseUnevaluatedStringLiteralExpression()
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition Parser.h:418
ExprResult ParseAssignmentExpression(TypoCorrectionTypeBehavior CorrectionBehavior=TypoCorrectionTypeBehavior::AllowNonTypes)
Parse an expr that doesn't include (top-level) commas.
Definition ParseExpr.cpp:75
friend class BalancedDelimiterTracker
Definition Parser.h:293
A class for parsing a declarator.
const ParsingDeclSpec & getDeclSpec() const
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition Scope.h:414
@ 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
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9507
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2512
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6903
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class,...
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:304
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
Token - This structure provides full information about a lexed token.
Definition Token.h:36
SourceLocation getEndLoc() const
Definition Token.h:169
static Token createEof(SourceLocation Loc=SourceLocation(), const void *Data=nullptr)
Definition Token.h:216
bool isOneOf(Ts... Ks) const
Definition Token.h:105
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2980
const Expr * getInit() const
Definition Decl.h:1393
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2888
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
@ CPlusPlus11
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:276
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:127
@ Result
The result type of a method or function.
Definition TypeBase.h:906
@ ExplicitSpecialization
We are parsing an explicit specialization.
Definition Parser.h:83
@ NonTemplate
We are not parsing a template at all.
Definition Parser.h:79
CachedInitKind
Definition Parser.h:88
U cast(CodeGen::Address addr)
Definition Address.h:327
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:218
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6157
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1787
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
ReenterClassScopeRAII(Parser &P, ParsingClass &Class)
ReenterTemplateScopeRAII(Parser &P, Decl *MaybeTemplated, bool Enter=true)
SmallVector< ParmVarDecl *, 4 > ProtoParams
Parameters of the prototype the attribute was written on, kept because late parsing runs after their ...
Definition Parser.h:209
IdentifierInfo & AttrName
Definition Parser.h:201
SourceLocation AttrNameLoc
Definition Parser.h:203
SmallVector< Decl *, 2 > Decls
Definition Parser.h:204
An RAII helper that pops function a function scope on exit.
Definition Sema.h:1355