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