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