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, const Decl *D,
727 ArrayRef<const DeclRefExpr *> ParamRefs, 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, nor a parameter declared after the one the attribute is on,
757 // which is instantiated after that parameter's attributes. Reject the
758 // attribute rather than instantiate it wrongly.
759 // FIXME: Map these parameters during template instantiation.
760 if (Actions.CurContext->isDependentContext() ||
761 getCurScope()->getTemplateParamParent() ||
762 Actions.getCurGenericLambda()) {
763 const auto *DParam = dyn_cast_or_null<ParmVarDecl>(D);
764 for (const DeclRefExpr *DRE : ParamRefs) {
765 const auto *PVD = cast<ParmVarDecl>(DRE->getDecl());
766 bool Pointee = IsPointeeParam(PVD);
767 if (!Pointee &&
768 !(DParam &&
769 DParam->getFunctionScopeDepth() == PVD->getFunctionScopeDepth() &&
770 DParam->getFunctionScopeIndex() < PVD->getFunctionScopeIndex()))
771 continue;
772 Diag(DRE->getLocation(), diag::err_late_attribute_param_in_template)
773 << &LPA.AttrName << !Pointee << PVD;
774 return true;
775 }
776 }
777 return false;
778}
779
780void Parser::ParseLexedAttribute(LateParsedAttribute &LPA, bool EnterScope,
781 bool OnDefinition,
782 ParsedAttributes *OutAttrs) {
783 ParsedAttributes Attrs(AttrFactory);
784
785 if (LPA.Decls.size() > 0) {
786 Decl *D = LPA.Decls[0];
787 bool HasFuncScope = EnterScope && LPA.Decls.size() == 1 &&
789 bool IsCPlusPlus = getLangOpts().CPlusPlus;
790
791 NamedDecl *ND = dyn_cast<NamedDecl>(D);
792 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
793
794 // Allow 'this' within late-parsed attributes.
795 Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
796 IsCPlusPlus && ND &&
797 ND->isCXXInstanceMember());
798
799 // If the Decl is templatized, add template parameters to the scope.
800 ReenterTemplateScopeRAII InDeclScope(*this, D, IsCPlusPlus && EnterScope);
801
802 // If the Decl is on a function, add function parameters to the scope.
803 if (HasFuncScope) {
804 InDeclScope.Scopes.Enter(Scope::FnScope | Scope::DeclScope |
806 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
807 }
808
809 // For a function pointer field or variable, the arguments may name a
810 // parameter of the pointee. Re-enter them in a prototype scope nested as it
811 // was when the attribute was written, so they shadow any outer declaration
812 // of the same name. In a C struct, ActOnIdExpression finds the struct's
813 // members only while its scope is innermost, so add the parameters to that
814 // scope instead; it lets them shadow a member of the same name.
815 bool HasProtoParams = !HasFuncScope && !LPA.ProtoParams.empty();
816 bool InCStruct = !IsCPlusPlus && getCurScope()->isClassScope();
817 ParseScope ProtoScope(this,
819 HasProtoParams && !InCStruct);
820 if (HasProtoParams)
821 Actions.ActOnReenterFunctionPrototypeParams(Actions.getCurScope(),
822 LPA.ProtoParams);
823
824 ParsedAttributes Parsed = ParseLexedAttributeTokens(LPA);
825
826 if (HasProtoParams && InCStruct)
827 Actions.ActOnExitFunctionPrototypeParams(Actions.getCurScope(),
828 LPA.ProtoParams);
829 ProtoScope.Exit();
830
831 SmallVector<const DeclRefExpr *, 4> ParamRefs;
832 collectParamRefs(Parsed, ParamRefs);
833 if (!ParamRefs.empty() &&
834 checkLateAttributeParamRefs(LPA, D, ParamRefs, HasProtoParams))
835 Parsed.clear();
836 Attrs.takeAllAppendingFrom(Parsed);
837
838 if (HasFuncScope)
839 Actions.ActOnExitFunctionContext();
840 } else {
841 Diag(LPA.AttrNameLoc, diag::warn_attribute_no_decl)
842 << LPA.AttrName.getName();
843 }
844
845 if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
846 Attrs.begin()->isKnownToGCC())
847 Diag(Tok, diag::warn_attribute_on_function_definition) << &LPA.AttrName;
848
849 for (auto *D : LPA.Decls)
850 Actions.ActOnFinishDelayedAttribute(getCurScope(), D, Attrs);
851
852 if (OutAttrs)
853 OutAttrs->takeAllAppendingFrom(Attrs);
854}
855
856void Parser::ParseLexedPragmas(ParsingClass &Class) {
857 ReenterClassScopeRAII InClassScope(*this, Class);
858
859 for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
861}
862
863void Parser::ParseLexedPragma(LateParsedPragma &LP) {
864 PP.EnterToken(Tok, /*IsReinject=*/true);
865 PP.EnterTokenStream(LP.toks(), /*DisableMacroExpansion=*/true,
866 /*IsReinject=*/true);
867
868 // Consume the previously pushed token.
869 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
870 assert(Tok.isAnnotation() && "Expected annotation token.");
871 switch (Tok.getKind()) {
872 case tok::annot_attr_openmp:
873 case tok::annot_pragma_openmp: {
874 AccessSpecifier AS = LP.getAccessSpecifier();
875 ParsedAttributes Attrs(AttrFactory);
876 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
877 break;
878 }
879 default:
880 llvm_unreachable("Unexpected token.");
881 }
882}
883
884bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
885 CachedTokens &Toks,
886 bool StopAtSemi, bool ConsumeFinalToken) {
887 // We always want this function to consume at least one token if the first
888 // token isn't T and if not at EOF.
889 bool isFirstTokenConsumed = true;
890 while (true) {
891 // If we found one of the tokens, stop and return true.
892 if (Tok.is(T1) || Tok.is(T2)) {
893 if (ConsumeFinalToken) {
894 Toks.push_back(Tok);
896 }
897 return true;
898 }
899
900 switch (Tok.getKind()) {
901 case tok::eof:
902 case tok::annot_module_begin:
903 case tok::annot_module_end:
904 case tok::annot_module_include:
905 case tok::annot_repl_input_end:
906 // Ran out of tokens.
907 return false;
908
909 case tok::annot_pragma_openacc:
910 case tok::annot_pragma_openmp:
911 case tok::annot_attr_openmp: {
912 // Ignore any tokens inside of a OMP/OpenACC pragma, as these should just
913 // be taken as 1.
914 tok::TokenKind EndKind = Tok.is(tok::annot_pragma_openacc)
915 ? tok::annot_pragma_openacc_end
916 : tok::annot_pragma_openmp_end;
917 Toks.push_back(Tok);
918 ConsumeAnnotationToken();
919 while (Tok.isNot(EndKind) && Tok.isNot(tok::eof)) {
920 Toks.push_back(Tok);
922 }
923 if (Tok.is(EndKind)) {
924 Toks.push_back(Tok);
925 ConsumeAnnotationToken();
926 }
927 break;
928 }
929
930 case tok::l_paren:
931 // Recursively consume properly-nested parens.
932 Toks.push_back(Tok);
933 ConsumeParen();
934 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
935 break;
936 case tok::l_square:
937 // Recursively consume properly-nested square brackets.
938 Toks.push_back(Tok);
939 ConsumeBracket();
940 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
941 break;
942 case tok::l_brace:
943 // Recursively consume properly-nested braces.
944 Toks.push_back(Tok);
945 ConsumeBrace();
946 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
947 break;
948
949 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
950 // Since the user wasn't looking for this token (if they were, it would
951 // already be handled), this isn't balanced. If there is a LHS token at a
952 // higher level, we will assume that this matches the unbalanced token
953 // and return it. Otherwise, this is a spurious RHS token, which we skip.
954 case tok::r_paren:
955 if (ParenCount && !isFirstTokenConsumed)
956 return false; // Matches something.
957 Toks.push_back(Tok);
958 ConsumeParen();
959 break;
960 case tok::r_square:
961 if (BracketCount && !isFirstTokenConsumed)
962 return false; // Matches something.
963 Toks.push_back(Tok);
964 ConsumeBracket();
965 break;
966 case tok::r_brace:
967 if (BraceCount && !isFirstTokenConsumed)
968 return false; // Matches something.
969 Toks.push_back(Tok);
970 ConsumeBrace();
971 break;
972
973 case tok::semi:
974 if (StopAtSemi)
975 return false;
976 [[fallthrough]];
977 default:
978 // consume this token.
979 Toks.push_back(Tok);
980 ConsumeAnyToken(/*ConsumeCodeCompletionTok*/true);
981 break;
982 }
983 isFirstTokenConsumed = false;
984 }
985}
986
987bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
988 if (Tok.is(tok::kw_try)) {
989 Toks.push_back(Tok);
990 ConsumeToken();
991 }
992
993 if (Tok.isNot(tok::colon)) {
994 // Easy case, just a function body.
995
996 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
997 // brace: an opening one is the function body, while a closing one probably
998 // means we've reached the end of the class.
999 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
1000 /*StopAtSemi=*/true,
1001 /*ConsumeFinalToken=*/false);
1002 if (Tok.isNot(tok::l_brace))
1003 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
1004
1005 Toks.push_back(Tok);
1006 ConsumeBrace();
1007 return false;
1008 }
1009
1010 Toks.push_back(Tok);
1011 ConsumeToken();
1012
1013 // We can't reliably skip over a mem-initializer-id, because it could be
1014 // a template-id involving not-yet-declared names. Given:
1015 //
1016 // S ( ) : a < b < c > ( e )
1017 //
1018 // 'e' might be an initializer or part of a template argument, depending
1019 // on whether 'b' is a template.
1020
1021 // Track whether we might be inside a template argument. We can give
1022 // significantly better diagnostics if we know that we're not.
1023 bool MightBeTemplateArgument = false;
1024
1025 while (true) {
1026 // Skip over the mem-initializer-id, if possible.
1027 if (Tok.is(tok::kw_decltype)) {
1028 Toks.push_back(Tok);
1029 SourceLocation OpenLoc = ConsumeToken();
1030 if (Tok.isNot(tok::l_paren))
1031 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
1032 << "decltype";
1033 Toks.push_back(Tok);
1034 ConsumeParen();
1035 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
1036 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
1037 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
1038 return true;
1039 }
1040 }
1041 do {
1042 // Walk over a component of a nested-name-specifier.
1043 if (Tok.is(tok::coloncolon)) {
1044 Toks.push_back(Tok);
1045 ConsumeToken();
1046
1047 if (Tok.is(tok::kw_template)) {
1048 Toks.push_back(Tok);
1049 ConsumeToken();
1050 }
1051 }
1052
1053 if (Tok.is(tok::identifier)) {
1054 Toks.push_back(Tok);
1055 ConsumeToken();
1056 } else {
1057 break;
1058 }
1059 // Pack indexing
1060 if (Tok.is(tok::ellipsis) && NextToken().is(tok::l_square)) {
1061 Toks.push_back(Tok);
1062 SourceLocation OpenLoc = ConsumeToken();
1063 Toks.push_back(Tok);
1064 ConsumeBracket();
1065 if (!ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/true)) {
1066 Diag(Tok.getLocation(), diag::err_expected) << tok::r_square;
1067 Diag(OpenLoc, diag::note_matching) << tok::l_square;
1068 return true;
1069 }
1070 }
1071
1072 } while (Tok.is(tok::coloncolon));
1073
1074 if (Tok.is(tok::code_completion)) {
1075 Toks.push_back(Tok);
1076 ConsumeCodeCompletionToken();
1077 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype)) {
1078 // Could be the start of another member initializer (the ',' has not
1079 // been written yet)
1080 continue;
1081 }
1082 }
1083
1084 if (Tok.is(tok::comma)) {
1085 // The initialization is missing, we'll diagnose it later.
1086 Toks.push_back(Tok);
1087 ConsumeToken();
1088 continue;
1089 }
1090 if (Tok.is(tok::less))
1091 MightBeTemplateArgument = true;
1092
1093 if (MightBeTemplateArgument) {
1094 // We may be inside a template argument list. Grab up to the start of the
1095 // next parenthesized initializer or braced-init-list. This *might* be the
1096 // initializer, or it might be a subexpression in the template argument
1097 // list.
1098 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
1099 // if all angles are closed.
1100 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
1101 /*StopAtSemi=*/true,
1102 /*ConsumeFinalToken=*/false)) {
1103 // We're not just missing the initializer, we're also missing the
1104 // function body!
1105 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
1106 }
1107 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
1108 // We found something weird in a mem-initializer-id.
1110 return Diag(Tok.getLocation(), diag::err_expected_either)
1111 << tok::l_paren << tok::l_brace;
1112 else
1113 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
1114 }
1115
1116 tok::TokenKind kind = Tok.getKind();
1117 Toks.push_back(Tok);
1118 bool IsLParen = (kind == tok::l_paren);
1119 SourceLocation OpenLoc = Tok.getLocation();
1120
1121 if (IsLParen) {
1122 ConsumeParen();
1123 } else {
1124 assert(kind == tok::l_brace && "Must be left paren or brace here.");
1125 ConsumeBrace();
1126 // In C++03, this has to be the start of the function body, which
1127 // means the initializer is malformed; we'll diagnose it later.
1128 if (!getLangOpts().CPlusPlus11)
1129 return false;
1130
1131 const Token &PreviousToken = Toks[Toks.size() - 2];
1132 if (!MightBeTemplateArgument &&
1133 !PreviousToken.isOneOf(tok::identifier, tok::greater,
1134 tok::greatergreater)) {
1135 // If the opening brace is not preceded by one of these tokens, we are
1136 // missing the mem-initializer-id. In order to recover better, we need
1137 // to use heuristics to determine if this '{' is most likely the
1138 // beginning of a brace-init-list or the function body.
1139 // Check the token after the corresponding '}'.
1140 TentativeParsingAction PA(*this);
1141 if (SkipUntil(tok::r_brace) &&
1142 !Tok.isOneOf(tok::comma, tok::ellipsis, tok::l_brace)) {
1143 // Consider there was a malformed initializer and this is the start
1144 // of the function body. We'll diagnose it later.
1145 PA.Revert();
1146 return false;
1147 }
1148 PA.Revert();
1149 }
1150 }
1151
1152 // Grab the initializer (or the subexpression of the template argument).
1153 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
1154 // if we might be inside the braces of a lambda-expression.
1155 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
1156 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
1157 Diag(Tok, diag::err_expected) << CloseKind;
1158 Diag(OpenLoc, diag::note_matching) << kind;
1159 return true;
1160 }
1161
1162 // Grab pack ellipsis, if present.
1163 if (Tok.is(tok::ellipsis)) {
1164 Toks.push_back(Tok);
1165 ConsumeToken();
1166 }
1167
1168 // If we know we just consumed a mem-initializer, we must have ',' or '{'
1169 // next.
1170 if (Tok.is(tok::comma)) {
1171 Toks.push_back(Tok);
1172 ConsumeToken();
1173 } else if (Tok.is(tok::l_brace)) {
1174 // This is the function body if the ')' or '}' is immediately followed by
1175 // a '{'. That cannot happen within a template argument, apart from the
1176 // case where a template argument contains a compound literal:
1177 //
1178 // S ( ) : a < b < c > ( d ) { }
1179 // // End of declaration, or still inside the template argument?
1180 //
1181 // ... and the case where the template argument contains a lambda:
1182 //
1183 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
1184 // ( ) > ( ) { }
1185 //
1186 // FIXME: Disambiguate these cases. Note that the latter case is probably
1187 // going to be made ill-formed by core issue 1607.
1188 Toks.push_back(Tok);
1189 ConsumeBrace();
1190 return false;
1191 } else if (!MightBeTemplateArgument) {
1192 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
1193 << tok::comma;
1194 }
1195 }
1196}
1197
1198bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
1199 // Consume '?'.
1200 assert(Tok.is(tok::question));
1201 Toks.push_back(Tok);
1202 ConsumeToken();
1203
1204 while (Tok.isNot(tok::colon)) {
1205 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
1206 /*StopAtSemi=*/true,
1207 /*ConsumeFinalToken=*/false))
1208 return false;
1209
1210 // If we found a nested conditional, consume it.
1211 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
1212 return false;
1213 }
1214
1215 // Consume ':'.
1216 Toks.push_back(Tok);
1217 ConsumeToken();
1218 return true;
1219}
1220
1221bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
1222 CachedInitKind CIK) {
1223 // We always want this function to consume at least one token if not at EOF.
1224 bool IsFirstToken = true;
1225
1226 // Number of possible unclosed <s we've seen so far. These might be templates,
1227 // and might not, but if there were none of them (or we know for sure that
1228 // we're within a template), we can avoid a tentative parse.
1229 unsigned AngleCount = 0;
1230 unsigned KnownTemplateCount = 0;
1231
1232 while (true) {
1233 switch (Tok.getKind()) {
1234 case tok::ellipsis:
1235 // We found an elipsis at the end of the parameter list;
1236 // it is not part of a parameter declaration.
1237 if (ParenCount == 1 && NextToken().is(tok::r_paren))
1238 return true;
1239 goto consume_token;
1240 case tok::comma:
1241 // If we might be in a template, perform a tentative parse to check.
1242 if (!AngleCount)
1243 // Not a template argument: this is the end of the initializer.
1244 return true;
1245 if (KnownTemplateCount)
1246 goto consume_token;
1247
1248 // We hit a comma inside angle brackets. This is the hard case. The
1249 // rule we follow is:
1250 // * For a default argument, if the tokens after the comma form a
1251 // syntactically-valid parameter-declaration-clause, in which each
1252 // parameter has an initializer, then this comma ends the default
1253 // argument.
1254 // * For a default initializer, if the tokens after the comma form a
1255 // syntactically-valid init-declarator-list, then this comma ends
1256 // the default initializer.
1257 {
1258 TentativeParsingAction TPA(*this, /*Unannotated=*/true);
1259 Sema::TentativeAnalysisScope Scope(Actions);
1260
1261 TPResult Result = TPResult::Error;
1262 ConsumeToken();
1263 switch (CIK) {
1265 Result = TryParseInitDeclaratorList();
1266 // If we parsed a complete, ambiguous init-declarator-list, this
1267 // is only syntactically-valid if it's followed by a semicolon.
1268 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1269 Result = TPResult::False;
1270 break;
1271
1273 bool InvalidAsDeclaration = false;
1274 Result = TryParseParameterDeclarationClause(
1275 &InvalidAsDeclaration, /*VersusTemplateArg=*/true);
1276 // If this is an expression or a declaration with a missing
1277 // 'typename', assume it's not a declaration.
1278 if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1279 Result = TPResult::False;
1280 break;
1281 }
1282
1283 // Put the token stream back and undo any annotations we performed
1284 // after the comma. They may reflect a different parse than the one
1285 // we will actually perform at the end of the class.
1286 TPA.Revert();
1287
1288 // If what follows could be a declaration, it is a declaration.
1289 if (Result != TPResult::False && Result != TPResult::Error)
1290 return true;
1291 }
1292
1293 // Keep going. We know we're inside a template argument list now.
1294 ++KnownTemplateCount;
1295 goto consume_token;
1296
1297 case tok::eof:
1298 // Ran out of tokens.
1299 return false;
1300
1301 case tok::less:
1302 // FIXME: A '<' can only start a template-id if it's preceded by an
1303 // identifier, an operator-function-id, or a literal-operator-id.
1304 ++AngleCount;
1305 goto consume_token;
1306
1307 case tok::question:
1308 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1309 // that is *never* the end of the initializer. Skip to the ':'.
1310 if (!ConsumeAndStoreConditional(Toks))
1311 return false;
1312 break;
1313
1314 case tok::greatergreatergreater:
1315 if (!getLangOpts().CPlusPlus11)
1316 goto consume_token;
1317 if (AngleCount) --AngleCount;
1318 if (KnownTemplateCount) --KnownTemplateCount;
1319 [[fallthrough]];
1320 case tok::greatergreater:
1321 if (!getLangOpts().CPlusPlus11)
1322 goto consume_token;
1323 if (AngleCount) --AngleCount;
1324 if (KnownTemplateCount) --KnownTemplateCount;
1325 [[fallthrough]];
1326 case tok::greater:
1327 if (AngleCount) --AngleCount;
1328 if (KnownTemplateCount) --KnownTemplateCount;
1329 goto consume_token;
1330
1331 case tok::kw_template:
1332 // 'template' identifier '<' is known to start a template argument list,
1333 // and can be used to disambiguate the parse.
1334 // FIXME: Support all forms of 'template' unqualified-id '<'.
1335 Toks.push_back(Tok);
1336 ConsumeToken();
1337 if (Tok.is(tok::identifier)) {
1338 Toks.push_back(Tok);
1339 ConsumeToken();
1340 if (Tok.is(tok::less)) {
1341 ++AngleCount;
1342 ++KnownTemplateCount;
1343 Toks.push_back(Tok);
1344 ConsumeToken();
1345 }
1346 }
1347 break;
1348
1349 case tok::kw_operator:
1350 // If 'operator' precedes other punctuation, that punctuation loses
1351 // its special behavior.
1352 Toks.push_back(Tok);
1353 ConsumeToken();
1354 switch (Tok.getKind()) {
1355 case tok::comma:
1356 case tok::greatergreatergreater:
1357 case tok::greatergreater:
1358 case tok::greater:
1359 case tok::less:
1360 Toks.push_back(Tok);
1361 ConsumeToken();
1362 break;
1363 default:
1364 break;
1365 }
1366 break;
1367
1368 case tok::l_paren:
1369 // Recursively consume properly-nested parens.
1370 Toks.push_back(Tok);
1371 ConsumeParen();
1372 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1373 break;
1374 case tok::l_square:
1375 // Recursively consume properly-nested square brackets.
1376 Toks.push_back(Tok);
1377 ConsumeBracket();
1378 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1379 break;
1380 case tok::l_brace:
1381 // Recursively consume properly-nested braces.
1382 Toks.push_back(Tok);
1383 ConsumeBrace();
1384 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1385 break;
1386
1387 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1388 // Since the user wasn't looking for this token (if they were, it would
1389 // already be handled), this isn't balanced. If there is a LHS token at a
1390 // higher level, we will assume that this matches the unbalanced token
1391 // and return it. Otherwise, this is a spurious RHS token, which we
1392 // consume and pass on to downstream code to diagnose.
1393 case tok::r_paren:
1395 return true; // End of the default argument.
1396 if (ParenCount && !IsFirstToken)
1397 return false;
1398 Toks.push_back(Tok);
1399 ConsumeParen();
1400 continue;
1401 case tok::r_square:
1402 if (BracketCount && !IsFirstToken)
1403 return false;
1404 Toks.push_back(Tok);
1405 ConsumeBracket();
1406 continue;
1407 case tok::r_brace:
1408 if (BraceCount && !IsFirstToken)
1409 return false;
1410 Toks.push_back(Tok);
1411 ConsumeBrace();
1412 continue;
1413
1414 case tok::code_completion:
1415 Toks.push_back(Tok);
1416 ConsumeCodeCompletionToken();
1417 break;
1418
1419 case tok::string_literal:
1420 case tok::wide_string_literal:
1421 case tok::utf8_string_literal:
1422 case tok::utf16_string_literal:
1423 case tok::utf32_string_literal:
1424 Toks.push_back(Tok);
1425 ConsumeStringToken();
1426 break;
1427 case tok::semi:
1429 return true; // End of the default initializer.
1430 [[fallthrough]];
1431 default:
1432 consume_token:
1433 // If it's an annotation token, then we've run out of tokens and should
1434 // bail out. Otherwise, cache the token and consume it.
1435 if (Tok.isAnnotation())
1436 return false;
1437
1438 Toks.push_back(Tok);
1439 ConsumeToken();
1440 break;
1441 }
1442 IsFirstToken = false;
1443 }
1444}
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:831
bool hasConstexprSpecifier() const
Definition DeclSpec.h:847
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:1136
bool isInIdentifierNamespace(unsigned NS) const
Definition DeclBase.h:910
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:456
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2511
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2796
RAII object that enters a new expression evaluation context.
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2932
QualType getReturnType() const
Definition Decl.h:2980
void setWillHaveBody(bool V=true)
Definition Decl.h:2817
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:275
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition Decl.cpp:1976
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:1949
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1953
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3043
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:950
void takeAllAppendingFrom(ParsedAttributes &Other)
Definition ParsedAttr.h:967
Introduces zero or more scopes for parsing.
Definition Parser.h:544
ParseScope - Introduces a new scope for parsing.
Definition Parser.h:508
Parser - This implements a parser for the C family of languages.
Definition Parser.h:271
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:363
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies)
Definition Parser.cpp:72
void EnterScope(unsigned ScopeFlags)
EnterScope - Start a new scope.
Definition Parser.cpp:439
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition Parser.h:391
bool TryConsumeToken(tok::TokenKind Expected)
Definition Parser.h:371
Scope * getCurScope() const
Definition Parser.h:312
friend struct LateParsedAttribute
Definition Parser.h:1226
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:607
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:305
friend class ParenBraceBracketBalancer
Definition Parser.h:299
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition Parser.h:588
@ StopAtSemi
Stop skipping at semicolon.
Definition Parser.h:586
ExprResult ParseUnevaluatedStringLiteralExpression()
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition Parser.h:425
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:300
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:9494
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2500
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6892
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:1823
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:1392
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2835
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:1259
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6025
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1775
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:1356