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