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
325 Self->ParseLexedPragma(*this);
326}
327
331 TemplateParameterDepthRAII CurTemplateDepthTracker;
332
333 ReenterTemplateScopeRAII(Parser &P, Decl *MaybeTemplated, bool Enter = true)
334 : P(P), Scopes(P), CurTemplateDepthTracker(P.TemplateParameterDepth) {
335 if (Enter) {
337 P.ReenterTemplateScopes(Scopes, MaybeTemplated));
338 }
339 }
340};
341
343 ParsingClass &Class;
344
346 : ReenterTemplateScopeRAII(P, Class.TagOrTemplate,
347 /*Enter=*/!Class.TopLevelClass),
348 Class(Class) {
349 // If this is the top-level class, we're still within its scope.
350 if (Class.TopLevelClass)
351 return;
352
353 // Re-enter the class scope itself.
355 P.Actions.ActOnStartDelayedMemberDeclarations(P.getCurScope(),
356 Class.TagOrTemplate);
357 }
359 if (Class.TopLevelClass)
360 return;
361
362 P.Actions.ActOnFinishDelayedMemberDeclarations(P.getCurScope(),
363 Class.TagOrTemplate);
364 }
365};
366
367void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
368 ReenterClassScopeRAII InClassScope(*this, Class);
369
370 for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations)
372}
373
374void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
375 // If this is a member template, introduce the template parameter scope.
376 ReenterTemplateScopeRAII InFunctionTemplateScope(*this, LM.Method);
377
378 // Start the delayed C++ method declaration
380
381 // Introduce the parameters into scope and parse their default
382 // arguments.
383 InFunctionTemplateScope.Scopes.Enter(Scope::FunctionPrototypeScope |
386
387 // Delayed default arguments or exception specifications may contain lambdas,
388 // struct S {
389 // void ICE(int x, int = sizeof([x] { return x; }()));
390 // }
391 //
392 // struct X {
393 // void ICE(int val) noexcept(noexcept([val]{}));
394 // };
395 // Lambda capture handling in tryCaptureVariable() expects an enclosing
396 // function scope in Sema's FunctionScopes stack.
397 Sema::FunctionScopeRAII PopFnContext(Actions);
398 Actions.PushFunctionScope();
399
400 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
401 auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
402 // Introduce the parameter into scope.
403 bool HasUnparsed = Param->hasUnparsedDefaultArg();
405 std::unique_ptr<CachedTokens> Toks = std::move(LM.DefaultArgs[I].Toks);
406 if (Toks) {
407 ParenBraceBracketBalancer BalancerRAIIObj(*this);
408
409 // Mark the end of the default argument so that we know when to stop when
410 // we parse it later on.
411 Token LastDefaultArgToken = Toks->back();
412 Token DefArgEnd;
413 DefArgEnd.startToken();
414 DefArgEnd.setKind(tok::eof);
415 DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
416 DefArgEnd.setEofData(Param);
417 Toks->push_back(DefArgEnd);
418
419 // Parse the default argument from its saved token stream.
420 Toks->push_back(Tok); // So that the current token doesn't get lost
421 PP.EnterTokenStream(*Toks, true, /*IsReinject*/ true);
422
423 // Consume the previously-pushed token.
425
426 // Consume the '='.
427 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
428 SourceLocation EqualLoc = ConsumeToken();
429
430 // The argument isn't actually potentially evaluated unless it is
431 // used.
433 Actions,
435
436 ExprResult DefArgResult;
437 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
438 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
439 DefArgResult = ParseBraceInitializer();
440 } else
441 DefArgResult = ParseAssignmentExpression();
442 if (DefArgResult.isInvalid()) {
443 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc,
444 /*DefaultArg=*/nullptr);
445 } else {
446 if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
447 // The last two tokens are the terminator and the saved value of
448 // Tok; the last token in the default argument is the one before
449 // those.
450 assert(Toks->size() >= 3 && "expected a token in default arg");
451 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
452 << SourceRange(Tok.getLocation(),
453 (*Toks)[Toks->size() - 3].getLocation());
454 }
455 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
456 DefArgResult.get());
457 }
458
459 // There could be leftover tokens (e.g. because of an error).
460 // Skip through until we reach the 'end of default argument' token.
461 while (Tok.isNot(tok::eof))
463
464 if (Tok.is(tok::eof) && Tok.getEofData() == Param)
466 } else if (HasUnparsed) {
467 assert(Param->hasInheritedDefaultArg());
468 FunctionDecl *Old;
469 if (const auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(LM.Method))
470 Old =
471 cast<FunctionDecl>(FunTmpl->getTemplatedDecl())->getPreviousDecl();
472 else
473 Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
474 if (Old) {
475 ParmVarDecl *OldParam = Old->getParamDecl(I);
476 assert(!OldParam->hasUnparsedDefaultArg());
477 if (OldParam->hasUninstantiatedDefaultArg())
478 Param->setUninstantiatedDefaultArg(
479 OldParam->getUninstantiatedDefaultArg());
480 else
481 Param->setDefaultArg(OldParam->getInit());
482 }
483 }
484 }
485
486 // Parse a delayed exception-specification, if there is one.
487 if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
488 ParenBraceBracketBalancer BalancerRAIIObj(*this);
489
490 // Add the 'stop' token.
491 Token LastExceptionSpecToken = Toks->back();
492 Token ExceptionSpecEnd;
493 ExceptionSpecEnd.startToken();
494 ExceptionSpecEnd.setKind(tok::eof);
495 ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
496 ExceptionSpecEnd.setEofData(LM.Method);
497 Toks->push_back(ExceptionSpecEnd);
498
499 // Parse the default argument from its saved token stream.
500 Toks->push_back(Tok); // So that the current token doesn't get lost
501 PP.EnterTokenStream(*Toks, true, /*IsReinject*/true);
502
503 // Consume the previously-pushed token.
505
506 // C++11 [expr.prim.general]p3:
507 // If a declaration declares a member function or member function
508 // template of a class X, the expression this is a prvalue of type
509 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
510 // and the end of the function-definition, member-declarator, or
511 // declarator.
512 CXXMethodDecl *Method;
513 FunctionDecl *FunctionToPush;
514 if (FunctionTemplateDecl *FunTmpl
515 = dyn_cast<FunctionTemplateDecl>(LM.Method))
516 FunctionToPush = FunTmpl->getTemplatedDecl();
517 else
518 FunctionToPush = cast<FunctionDecl>(LM.Method);
519 Method = dyn_cast<CXXMethodDecl>(FunctionToPush);
520
521 // Setup the CurScope to match the function DeclContext - we have such
522 // assumption in IsInFnTryBlockHandler().
523 ParseScope FnScope(this, Scope::FnScope);
524 Sema::ContextRAII FnContext(Actions, FunctionToPush,
525 /*NewThisContext=*/false);
526
527 Sema::CXXThisScopeRAII ThisScope(
528 Actions, Method ? Method->getParent() : nullptr,
529 Method ? Method->getMethodQualifiers() : Qualifiers{},
531
532 // Parse the exception-specification.
533 SourceRange SpecificationRange;
534 SmallVector<ParsedType, 4> DynamicExceptions;
535 SmallVector<SourceRange, 4> DynamicExceptionRanges;
536 ExprResult NoexceptExpr;
537 CachedTokens *ExceptionSpecTokens;
538
540 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
541 DynamicExceptions,
542 DynamicExceptionRanges, NoexceptExpr,
543 ExceptionSpecTokens);
544
545 if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
546 Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
547
548 // Attach the exception-specification to the method.
549 Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
550 SpecificationRange,
551 DynamicExceptions,
552 DynamicExceptionRanges,
553 NoexceptExpr.isUsable()?
554 NoexceptExpr.get() : nullptr);
555
556 // There could be leftover tokens (e.g. because of an error).
557 // Skip through until we reach the original token position.
558 while (Tok.isNot(tok::eof))
560
561 // Clean up the remaining EOF token.
562 if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
564
565 delete Toks;
566 LM.ExceptionSpecTokens = nullptr;
567 }
568
569 InFunctionTemplateScope.Scopes.Exit();
570
571 // Finish the delayed C++ method declaration.
572 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
573}
574
575void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
576 ReenterClassScopeRAII InClassScope(*this, Class);
577
578 for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
580}
581
582void Parser::ParseLexedMethodDef(LexedMethod &LM) {
583 // If this is a member template, introduce the template parameter scope.
584 ReenterTemplateScopeRAII InFunctionTemplateScope(*this, LM.D);
585
586 ParenBraceBracketBalancer BalancerRAIIObj(*this);
587
588 assert(!LM.Toks.empty() && "Empty body!");
589 Token LastBodyToken = LM.Toks.back();
590 Token BodyEnd;
591 BodyEnd.startToken();
592 BodyEnd.setKind(tok::eof);
593 BodyEnd.setLocation(LastBodyToken.getEndLoc());
594 BodyEnd.setEofData(LM.D);
595 LM.Toks.push_back(BodyEnd);
596 // Append the current token at the end of the new token stream so that it
597 // doesn't get lost.
598 LM.Toks.push_back(Tok);
599 PP.EnterTokenStream(LM.Toks, true, /*IsReinject*/true);
600
601 // Consume the previously pushed token.
602 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
603 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)
604 && "Inline method not starting with '{', ':' or 'try'");
605
606 // Parse the method body. Function body parsing code is similar enough
607 // to be re-used for method bodies as well.
610 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
611
612 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
613
614 llvm::scope_exit _([&]() {
615 while (Tok.isNot(tok::eof))
617
618 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
620
621 if (auto *FD = dyn_cast_or_null<FunctionDecl>(LM.D))
622 if (isa<CXXMethodDecl>(FD) ||
624 Actions.ActOnFinishInlineFunctionDef(FD);
625 });
626
627 if (Tok.is(tok::kw_try)) {
628 ParseFunctionTryBlock(LM.D, FnScope);
629 return;
630 }
631 if (Tok.is(tok::colon)) {
632 ParseConstructorInitializer(LM.D);
633
634 // Error recovery.
635 if (!Tok.is(tok::l_brace)) {
636 FnScope.Exit();
637 Actions.ActOnFinishFunctionBody(LM.D, nullptr);
638 return;
639 }
640 } else
641 Actions.ActOnDefaultCtorInitializers(LM.D);
642
643 assert((Actions.getDiagnostics().hasErrorOccurred() ||
645 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
646 < TemplateParameterDepth) &&
647 "TemplateParameterDepth should be greater than the depth of "
648 "current template being instantiated!");
649
650 ParseFunctionStatementBody(LM.D, FnScope);
651}
652
653void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
654 ReenterClassScopeRAII InClassScope(*this, Class);
655
656 if (!Class.LateParsedDeclarations.empty()) {
657 // C++11 [expr.prim.general]p4:
658 // Otherwise, if a member-declarator declares a non-static data member
659 // (9.2) of a class X, the expression this is a prvalue of type "pointer
660 // to X" within the optional brace-or-equal-initializer. It shall not
661 // appear elsewhere in the member-declarator.
662 // FIXME: This should be done in ParseLexedMemberInitializer, not here.
663 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
664 Qualifiers());
665
666 for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
668 }
669
670 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
671}
672
673void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
674 if (!MI.Field || MI.Field->isInvalidDecl())
675 return;
676
677 ParenBraceBracketBalancer BalancerRAIIObj(*this);
678
679 // Append the current token at the end of the new token stream so that it
680 // doesn't get lost.
681 MI.Toks.push_back(Tok);
682 PP.EnterTokenStream(MI.Toks, true, /*IsReinject*/true);
683
684 // Consume the previously pushed token.
685 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
686
687 SourceLocation EqualLoc;
688
689 Actions.ActOnStartCXXInClassMemberInitializer();
690
691 // The initializer isn't actually potentially evaluated unless it is
692 // used.
693 EnterExpressionEvaluationContext Eval(
695
696 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
697 EqualLoc);
698
699 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc, Init);
700
701 // The next token should be our artificial terminating EOF token.
702 if (Tok.isNot(tok::eof)) {
703 if (!Init.isInvalid()) {
704 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
705 if (!EndLoc.isValid())
706 EndLoc = Tok.getLocation();
707 // No fixit; we can't recover as if there were a semicolon here.
708 Diag(EndLoc, diag::err_expected_semi_decl_list);
709 }
710
711 // Consume tokens until we hit the artificial EOF.
712 while (Tok.isNot(tok::eof))
714 }
715 // Make sure this is *our* artificial EOF token.
716 if (Tok.getEofData() == MI.Field)
718}
719
720void Parser::ParseLexedAttributes(ParsingClass &Class) {
721 ReenterClassScopeRAII InClassScope(*this, Class);
722
723 for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations)
724 LateD->ParseLexedAttributes();
725}
726
727void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
728 bool EnterScope, bool OnDefinition) {
729 assert(LAs.parseSoon() &&
730 "Attribute list should be marked for immediate parsing.");
731 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
732 if (D)
733 LAs[i]->addDecl(D);
734 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
735 delete LAs[i];
736 }
737 LAs.clear();
738}
739
740void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
741 bool EnterScope, bool OnDefinition) {
742 // Create a fake EOF so that attribute parsing won't go off the end of the
743 // attribute.
744 Token AttrEnd;
745 AttrEnd.startToken();
746 AttrEnd.setKind(tok::eof);
747 AttrEnd.setLocation(Tok.getLocation());
748 AttrEnd.setEofData(LA.Toks.data());
749 LA.Toks.push_back(AttrEnd);
750
751 // Append the current token at the end of the new token stream so that it
752 // doesn't get lost.
753 LA.Toks.push_back(Tok);
754 PP.EnterTokenStream(LA.Toks, true, /*IsReinject=*/true);
755 // Consume the previously pushed token.
756 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
757
758 ParsedAttributes Attrs(AttrFactory);
759
760 if (LA.Decls.size() > 0) {
761 Decl *D = LA.Decls[0];
762 NamedDecl *ND = dyn_cast<NamedDecl>(D);
763 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
764
765 // Allow 'this' within late-parsed attributes.
766 Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
767 ND && ND->isCXXInstanceMember());
768
769 if (LA.Decls.size() == 1) {
770 // If the Decl is templatized, add template parameters to scope.
771 ReenterTemplateScopeRAII InDeclScope(*this, D, EnterScope);
772
773 // If the Decl is on a function, add function parameters to the scope.
774 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
775 if (HasFunScope) {
776 InDeclScope.Scopes.Enter(Scope::FnScope | Scope::DeclScope |
778 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
779 }
780
781 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, nullptr,
782 nullptr, SourceLocation(), ParsedAttr::Form::GNU(),
783 nullptr);
784
785 if (HasFunScope)
786 Actions.ActOnExitFunctionContext();
787 } else {
788 // If there are multiple decls, then the decl cannot be within the
789 // function scope.
790 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, nullptr,
791 nullptr, SourceLocation(), ParsedAttr::Form::GNU(),
792 nullptr);
793 }
794 } else {
795 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
796 }
797
798 if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
799 Attrs.begin()->isKnownToGCC())
800 Diag(Tok, diag::warn_attribute_on_function_definition)
801 << &LA.AttrName;
802
803 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
804 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
805
806 // Due to a parsing error, we either went over the cached tokens or
807 // there are still cached tokens left, so we skip the leftover tokens.
808 while (Tok.isNot(tok::eof))
810
811 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
813}
814
815void Parser::ParseLexedPragmas(ParsingClass &Class) {
816 ReenterClassScopeRAII InClassScope(*this, Class);
817
818 for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
820}
821
822void Parser::ParseLexedPragma(LateParsedPragma &LP) {
823 PP.EnterToken(Tok, /*IsReinject=*/true);
824 PP.EnterTokenStream(LP.toks(), /*DisableMacroExpansion=*/true,
825 /*IsReinject=*/true);
826
827 // Consume the previously pushed token.
828 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
829 assert(Tok.isAnnotation() && "Expected annotation token.");
830 switch (Tok.getKind()) {
831 case tok::annot_attr_openmp:
832 case tok::annot_pragma_openmp: {
833 AccessSpecifier AS = LP.getAccessSpecifier();
834 ParsedAttributes Attrs(AttrFactory);
835 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
836 break;
837 }
838 default:
839 llvm_unreachable("Unexpected token.");
840 }
841}
842
843bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
844 CachedTokens &Toks,
845 bool StopAtSemi, bool ConsumeFinalToken) {
846 // We always want this function to consume at least one token if the first
847 // token isn't T and if not at EOF.
848 bool isFirstTokenConsumed = true;
849 while (true) {
850 // If we found one of the tokens, stop and return true.
851 if (Tok.is(T1) || Tok.is(T2)) {
852 if (ConsumeFinalToken) {
853 Toks.push_back(Tok);
855 }
856 return true;
857 }
858
859 switch (Tok.getKind()) {
860 case tok::eof:
861 case tok::annot_module_begin:
862 case tok::annot_module_end:
863 case tok::annot_module_include:
864 case tok::annot_repl_input_end:
865 // Ran out of tokens.
866 return false;
867
868 case tok::l_paren:
869 // Recursively consume properly-nested parens.
870 Toks.push_back(Tok);
871 ConsumeParen();
872 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
873 break;
874 case tok::l_square:
875 // Recursively consume properly-nested square brackets.
876 Toks.push_back(Tok);
877 ConsumeBracket();
878 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
879 break;
880 case tok::l_brace:
881 // Recursively consume properly-nested braces.
882 Toks.push_back(Tok);
883 ConsumeBrace();
884 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
885 break;
886
887 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
888 // Since the user wasn't looking for this token (if they were, it would
889 // already be handled), this isn't balanced. If there is a LHS token at a
890 // higher level, we will assume that this matches the unbalanced token
891 // and return it. Otherwise, this is a spurious RHS token, which we skip.
892 case tok::r_paren:
893 if (ParenCount && !isFirstTokenConsumed)
894 return false; // Matches something.
895 Toks.push_back(Tok);
896 ConsumeParen();
897 break;
898 case tok::r_square:
899 if (BracketCount && !isFirstTokenConsumed)
900 return false; // Matches something.
901 Toks.push_back(Tok);
902 ConsumeBracket();
903 break;
904 case tok::r_brace:
905 if (BraceCount && !isFirstTokenConsumed)
906 return false; // Matches something.
907 Toks.push_back(Tok);
908 ConsumeBrace();
909 break;
910
911 case tok::semi:
912 if (StopAtSemi)
913 return false;
914 [[fallthrough]];
915 default:
916 // consume this token.
917 Toks.push_back(Tok);
918 ConsumeAnyToken(/*ConsumeCodeCompletionTok*/true);
919 break;
920 }
921 isFirstTokenConsumed = false;
922 }
923}
924
925bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
926 if (Tok.is(tok::kw_try)) {
927 Toks.push_back(Tok);
928 ConsumeToken();
929 }
930
931 if (Tok.isNot(tok::colon)) {
932 // Easy case, just a function body.
933
934 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
935 // brace: an opening one is the function body, while a closing one probably
936 // means we've reached the end of the class.
937 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
938 /*StopAtSemi=*/true,
939 /*ConsumeFinalToken=*/false);
940 if (Tok.isNot(tok::l_brace))
941 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
942
943 Toks.push_back(Tok);
944 ConsumeBrace();
945 return false;
946 }
947
948 Toks.push_back(Tok);
949 ConsumeToken();
950
951 // We can't reliably skip over a mem-initializer-id, because it could be
952 // a template-id involving not-yet-declared names. Given:
953 //
954 // S ( ) : a < b < c > ( e )
955 //
956 // 'e' might be an initializer or part of a template argument, depending
957 // on whether 'b' is a template.
958
959 // Track whether we might be inside a template argument. We can give
960 // significantly better diagnostics if we know that we're not.
961 bool MightBeTemplateArgument = false;
962
963 while (true) {
964 // Skip over the mem-initializer-id, if possible.
965 if (Tok.is(tok::kw_decltype)) {
966 Toks.push_back(Tok);
967 SourceLocation OpenLoc = ConsumeToken();
968 if (Tok.isNot(tok::l_paren))
969 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
970 << "decltype";
971 Toks.push_back(Tok);
972 ConsumeParen();
973 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
974 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
975 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
976 return true;
977 }
978 }
979 do {
980 // Walk over a component of a nested-name-specifier.
981 if (Tok.is(tok::coloncolon)) {
982 Toks.push_back(Tok);
983 ConsumeToken();
984
985 if (Tok.is(tok::kw_template)) {
986 Toks.push_back(Tok);
987 ConsumeToken();
988 }
989 }
990
991 if (Tok.is(tok::identifier)) {
992 Toks.push_back(Tok);
993 ConsumeToken();
994 } else {
995 break;
996 }
997 // Pack indexing
998 if (Tok.is(tok::ellipsis) && NextToken().is(tok::l_square)) {
999 Toks.push_back(Tok);
1000 SourceLocation OpenLoc = ConsumeToken();
1001 Toks.push_back(Tok);
1002 ConsumeBracket();
1003 if (!ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/true)) {
1004 Diag(Tok.getLocation(), diag::err_expected) << tok::r_square;
1005 Diag(OpenLoc, diag::note_matching) << tok::l_square;
1006 return true;
1007 }
1008 }
1009
1010 } while (Tok.is(tok::coloncolon));
1011
1012 if (Tok.is(tok::code_completion)) {
1013 Toks.push_back(Tok);
1014 ConsumeCodeCompletionToken();
1015 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype)) {
1016 // Could be the start of another member initializer (the ',' has not
1017 // been written yet)
1018 continue;
1019 }
1020 }
1021
1022 if (Tok.is(tok::comma)) {
1023 // The initialization is missing, we'll diagnose it later.
1024 Toks.push_back(Tok);
1025 ConsumeToken();
1026 continue;
1027 }
1028 if (Tok.is(tok::less))
1029 MightBeTemplateArgument = true;
1030
1031 if (MightBeTemplateArgument) {
1032 // We may be inside a template argument list. Grab up to the start of the
1033 // next parenthesized initializer or braced-init-list. This *might* be the
1034 // initializer, or it might be a subexpression in the template argument
1035 // list.
1036 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
1037 // if all angles are closed.
1038 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
1039 /*StopAtSemi=*/true,
1040 /*ConsumeFinalToken=*/false)) {
1041 // We're not just missing the initializer, we're also missing the
1042 // function body!
1043 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
1044 }
1045 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
1046 // We found something weird in a mem-initializer-id.
1048 return Diag(Tok.getLocation(), diag::err_expected_either)
1049 << tok::l_paren << tok::l_brace;
1050 else
1051 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
1052 }
1053
1054 tok::TokenKind kind = Tok.getKind();
1055 Toks.push_back(Tok);
1056 bool IsLParen = (kind == tok::l_paren);
1057 SourceLocation OpenLoc = Tok.getLocation();
1058
1059 if (IsLParen) {
1060 ConsumeParen();
1061 } else {
1062 assert(kind == tok::l_brace && "Must be left paren or brace here.");
1063 ConsumeBrace();
1064 // In C++03, this has to be the start of the function body, which
1065 // means the initializer is malformed; we'll diagnose it later.
1066 if (!getLangOpts().CPlusPlus11)
1067 return false;
1068
1069 const Token &PreviousToken = Toks[Toks.size() - 2];
1070 if (!MightBeTemplateArgument &&
1071 !PreviousToken.isOneOf(tok::identifier, tok::greater,
1072 tok::greatergreater)) {
1073 // If the opening brace is not preceded by one of these tokens, we are
1074 // missing the mem-initializer-id. In order to recover better, we need
1075 // to use heuristics to determine if this '{' is most likely the
1076 // beginning of a brace-init-list or the function body.
1077 // Check the token after the corresponding '}'.
1078 TentativeParsingAction PA(*this);
1079 if (SkipUntil(tok::r_brace) &&
1080 !Tok.isOneOf(tok::comma, tok::ellipsis, tok::l_brace)) {
1081 // Consider there was a malformed initializer and this is the start
1082 // of the function body. We'll diagnose it later.
1083 PA.Revert();
1084 return false;
1085 }
1086 PA.Revert();
1087 }
1088 }
1089
1090 // Grab the initializer (or the subexpression of the template argument).
1091 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
1092 // if we might be inside the braces of a lambda-expression.
1093 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
1094 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
1095 Diag(Tok, diag::err_expected) << CloseKind;
1096 Diag(OpenLoc, diag::note_matching) << kind;
1097 return true;
1098 }
1099
1100 // Grab pack ellipsis, if present.
1101 if (Tok.is(tok::ellipsis)) {
1102 Toks.push_back(Tok);
1103 ConsumeToken();
1104 }
1105
1106 // If we know we just consumed a mem-initializer, we must have ',' or '{'
1107 // next.
1108 if (Tok.is(tok::comma)) {
1109 Toks.push_back(Tok);
1110 ConsumeToken();
1111 } else if (Tok.is(tok::l_brace)) {
1112 // This is the function body if the ')' or '}' is immediately followed by
1113 // a '{'. That cannot happen within a template argument, apart from the
1114 // case where a template argument contains a compound literal:
1115 //
1116 // S ( ) : a < b < c > ( d ) { }
1117 // // End of declaration, or still inside the template argument?
1118 //
1119 // ... and the case where the template argument contains a lambda:
1120 //
1121 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
1122 // ( ) > ( ) { }
1123 //
1124 // FIXME: Disambiguate these cases. Note that the latter case is probably
1125 // going to be made ill-formed by core issue 1607.
1126 Toks.push_back(Tok);
1127 ConsumeBrace();
1128 return false;
1129 } else if (!MightBeTemplateArgument) {
1130 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
1131 << tok::comma;
1132 }
1133 }
1134}
1135
1136bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
1137 // Consume '?'.
1138 assert(Tok.is(tok::question));
1139 Toks.push_back(Tok);
1140 ConsumeToken();
1141
1142 while (Tok.isNot(tok::colon)) {
1143 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
1144 /*StopAtSemi=*/true,
1145 /*ConsumeFinalToken=*/false))
1146 return false;
1147
1148 // If we found a nested conditional, consume it.
1149 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
1150 return false;
1151 }
1152
1153 // Consume ':'.
1154 Toks.push_back(Tok);
1155 ConsumeToken();
1156 return true;
1157}
1158
1159bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
1160 CachedInitKind CIK) {
1161 // We always want this function to consume at least one token if not at EOF.
1162 bool IsFirstToken = true;
1163
1164 // Number of possible unclosed <s we've seen so far. These might be templates,
1165 // and might not, but if there were none of them (or we know for sure that
1166 // we're within a template), we can avoid a tentative parse.
1167 unsigned AngleCount = 0;
1168 unsigned KnownTemplateCount = 0;
1169
1170 while (true) {
1171 switch (Tok.getKind()) {
1172 case tok::ellipsis:
1173 // We found an elipsis at the end of the parameter list;
1174 // it is not part of a parameter declaration.
1175 if (ParenCount == 1 && NextToken().is(tok::r_paren))
1176 return true;
1177 goto consume_token;
1178 case tok::comma:
1179 // If we might be in a template, perform a tentative parse to check.
1180 if (!AngleCount)
1181 // Not a template argument: this is the end of the initializer.
1182 return true;
1183 if (KnownTemplateCount)
1184 goto consume_token;
1185
1186 // We hit a comma inside angle brackets. This is the hard case. The
1187 // rule we follow is:
1188 // * For a default argument, if the tokens after the comma form a
1189 // syntactically-valid parameter-declaration-clause, in which each
1190 // parameter has an initializer, then this comma ends the default
1191 // argument.
1192 // * For a default initializer, if the tokens after the comma form a
1193 // syntactically-valid init-declarator-list, then this comma ends
1194 // the default initializer.
1195 {
1196 TentativeParsingAction TPA(*this, /*Unannotated=*/true);
1197 Sema::TentativeAnalysisScope Scope(Actions);
1198
1199 TPResult Result = TPResult::Error;
1200 ConsumeToken();
1201 switch (CIK) {
1203 Result = TryParseInitDeclaratorList();
1204 // If we parsed a complete, ambiguous init-declarator-list, this
1205 // is only syntactically-valid if it's followed by a semicolon.
1206 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1207 Result = TPResult::False;
1208 break;
1209
1211 bool InvalidAsDeclaration = false;
1212 Result = TryParseParameterDeclarationClause(
1213 &InvalidAsDeclaration, /*VersusTemplateArg=*/true);
1214 // If this is an expression or a declaration with a missing
1215 // 'typename', assume it's not a declaration.
1216 if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1217 Result = TPResult::False;
1218 break;
1219 }
1220
1221 // Put the token stream back and undo any annotations we performed
1222 // after the comma. They may reflect a different parse than the one
1223 // we will actually perform at the end of the class.
1224 TPA.Revert();
1225
1226 // If what follows could be a declaration, it is a declaration.
1227 if (Result != TPResult::False && Result != TPResult::Error)
1228 return true;
1229 }
1230
1231 // Keep going. We know we're inside a template argument list now.
1232 ++KnownTemplateCount;
1233 goto consume_token;
1234
1235 case tok::eof:
1236 // Ran out of tokens.
1237 return false;
1238
1239 case tok::less:
1240 // FIXME: A '<' can only start a template-id if it's preceded by an
1241 // identifier, an operator-function-id, or a literal-operator-id.
1242 ++AngleCount;
1243 goto consume_token;
1244
1245 case tok::question:
1246 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1247 // that is *never* the end of the initializer. Skip to the ':'.
1248 if (!ConsumeAndStoreConditional(Toks))
1249 return false;
1250 break;
1251
1252 case tok::greatergreatergreater:
1253 if (!getLangOpts().CPlusPlus11)
1254 goto consume_token;
1255 if (AngleCount) --AngleCount;
1256 if (KnownTemplateCount) --KnownTemplateCount;
1257 [[fallthrough]];
1258 case tok::greatergreater:
1259 if (!getLangOpts().CPlusPlus11)
1260 goto consume_token;
1261 if (AngleCount) --AngleCount;
1262 if (KnownTemplateCount) --KnownTemplateCount;
1263 [[fallthrough]];
1264 case tok::greater:
1265 if (AngleCount) --AngleCount;
1266 if (KnownTemplateCount) --KnownTemplateCount;
1267 goto consume_token;
1268
1269 case tok::kw_template:
1270 // 'template' identifier '<' is known to start a template argument list,
1271 // and can be used to disambiguate the parse.
1272 // FIXME: Support all forms of 'template' unqualified-id '<'.
1273 Toks.push_back(Tok);
1274 ConsumeToken();
1275 if (Tok.is(tok::identifier)) {
1276 Toks.push_back(Tok);
1277 ConsumeToken();
1278 if (Tok.is(tok::less)) {
1279 ++AngleCount;
1280 ++KnownTemplateCount;
1281 Toks.push_back(Tok);
1282 ConsumeToken();
1283 }
1284 }
1285 break;
1286
1287 case tok::kw_operator:
1288 // If 'operator' precedes other punctuation, that punctuation loses
1289 // its special behavior.
1290 Toks.push_back(Tok);
1291 ConsumeToken();
1292 switch (Tok.getKind()) {
1293 case tok::comma:
1294 case tok::greatergreatergreater:
1295 case tok::greatergreater:
1296 case tok::greater:
1297 case tok::less:
1298 Toks.push_back(Tok);
1299 ConsumeToken();
1300 break;
1301 default:
1302 break;
1303 }
1304 break;
1305
1306 case tok::l_paren:
1307 // Recursively consume properly-nested parens.
1308 Toks.push_back(Tok);
1309 ConsumeParen();
1310 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1311 break;
1312 case tok::l_square:
1313 // Recursively consume properly-nested square brackets.
1314 Toks.push_back(Tok);
1315 ConsumeBracket();
1316 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1317 break;
1318 case tok::l_brace:
1319 // Recursively consume properly-nested braces.
1320 Toks.push_back(Tok);
1321 ConsumeBrace();
1322 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1323 break;
1324
1325 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1326 // Since the user wasn't looking for this token (if they were, it would
1327 // already be handled), this isn't balanced. If there is a LHS token at a
1328 // higher level, we will assume that this matches the unbalanced token
1329 // and return it. Otherwise, this is a spurious RHS token, which we
1330 // consume and pass on to downstream code to diagnose.
1331 case tok::r_paren:
1333 return true; // End of the default argument.
1334 if (ParenCount && !IsFirstToken)
1335 return false;
1336 Toks.push_back(Tok);
1337 ConsumeParen();
1338 continue;
1339 case tok::r_square:
1340 if (BracketCount && !IsFirstToken)
1341 return false;
1342 Toks.push_back(Tok);
1343 ConsumeBracket();
1344 continue;
1345 case tok::r_brace:
1346 if (BraceCount && !IsFirstToken)
1347 return false;
1348 Toks.push_back(Tok);
1349 ConsumeBrace();
1350 continue;
1351
1352 case tok::code_completion:
1353 Toks.push_back(Tok);
1354 ConsumeCodeCompletionToken();
1355 break;
1356
1357 case tok::string_literal:
1358 case tok::wide_string_literal:
1359 case tok::utf8_string_literal:
1360 case tok::utf16_string_literal:
1361 case tok::utf32_string_literal:
1362 Toks.push_back(Tok);
1363 ConsumeStringToken();
1364 break;
1365 case tok::semi:
1367 return true; // End of the default initializer.
1368 [[fallthrough]];
1369 default:
1370 consume_token:
1371 // If it's an annotation token, then we've run out of tokens and should
1372 // bail out. Otherwise, cache the token and consume it.
1373 if (Tok.isAnnotation())
1374 return false;
1375
1376 Toks.push_back(Tok);
1377 ConsumeToken();
1378 break;
1379 }
1380 IsFirstToken = false;
1381 }
1382}
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:828
bool hasConstexprSpecifier() const
Definition DeclSpec.h:844
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:2504
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2789
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:3026
Introduces zero or more scopes for parsing.
Definition Parser.h:528
ParseScope - Introduces a new scope for parsing.
Definition Parser.h:492
Parser - This implements a parser for the C family of languages.
Definition Parser.h:256
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:347
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:375
bool TryConsumeToken(tok::TokenKind Expected)
Definition Parser.h:355
Scope * getCurScope() const
Definition Parser.h:296
friend struct LateParsedAttribute
Definition Parser.h:1209
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:591
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:289
friend class ParenBraceBracketBalancer
Definition Parser.h:283
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition Parser.h:572
@ StopAtSemi
Stop skipping at semicolon.
Definition Parser.h:570
ExprResult ParseUnevaluatedStringLiteralExpression()
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition Parser.h:409
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:284
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:2446
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6833
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:2961
const Expr * getInit() const
Definition Decl.h:1381
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2828
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:1252
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5979
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: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:1330